xref: /linux/drivers/scsi/lpfc/lpfc_sli.c (revision 09b1704f5b02c18dd02b21343530463fcfc92c54)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2025 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.     *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/pci.h>
26 #include <linux/interrupt.h>
27 #include <linux/delay.h>
28 #include <linux/slab.h>
29 #include <linux/lockdep.h>
30 
31 #include <scsi/scsi.h>
32 #include <scsi/scsi_cmnd.h>
33 #include <scsi/scsi_device.h>
34 #include <scsi/scsi_host.h>
35 #include <scsi/scsi_transport_fc.h>
36 #include <scsi/fc/fc_fs.h>
37 #include <linux/crash_dump.h>
38 #ifdef CONFIG_X86
39 #include <asm/set_memory.h>
40 #endif
41 
42 #include "lpfc_hw4.h"
43 #include "lpfc_hw.h"
44 #include "lpfc_sli.h"
45 #include "lpfc_sli4.h"
46 #include "lpfc_nl.h"
47 #include "lpfc_disc.h"
48 #include "lpfc.h"
49 #include "lpfc_scsi.h"
50 #include "lpfc_nvme.h"
51 #include "lpfc_crtn.h"
52 #include "lpfc_logmsg.h"
53 #include "lpfc_compat.h"
54 #include "lpfc_debugfs.h"
55 #include "lpfc_vport.h"
56 #include "lpfc_version.h"
57 
58 /* There are only four IOCB completion types. */
59 typedef enum _lpfc_iocb_type {
60 	LPFC_UNKNOWN_IOCB,
61 	LPFC_UNSOL_IOCB,
62 	LPFC_SOL_IOCB,
63 	LPFC_ABORT_IOCB
64 } lpfc_iocb_type;
65 
66 
67 /* Provide function prototypes local to this module. */
68 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
69 				  uint32_t);
70 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
71 			      uint8_t *, uint32_t *);
72 static struct lpfc_iocbq *
73 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
74 				  struct lpfc_iocbq *rspiocbq);
75 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
76 				      struct hbq_dmabuf *);
77 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
78 					  struct hbq_dmabuf *dmabuf);
79 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
80 				   struct lpfc_queue *cq, struct lpfc_cqe *cqe);
81 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
82 				       int);
83 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
84 				     struct lpfc_queue *eq,
85 				     struct lpfc_eqe *eqe,
86 				     enum lpfc_poll_mode poll_mode);
87 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
88 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
89 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
90 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
91 				    struct lpfc_queue *cq,
92 				    struct lpfc_cqe *cqe);
93 static uint16_t lpfc_wqe_bpl2sgl(struct lpfc_hba *phba,
94 				 struct lpfc_iocbq *pwqeq,
95 				 struct lpfc_sglq *sglq);
96 
97 union lpfc_wqe128 lpfc_iread_cmd_template;
98 union lpfc_wqe128 lpfc_iwrite_cmd_template;
99 union lpfc_wqe128 lpfc_icmnd_cmd_template;
100 
101 /* Setup WQE templates for IOs */
102 void lpfc_wqe_cmd_template(void)
103 {
104 	union lpfc_wqe128 *wqe;
105 
106 	/* IREAD template */
107 	wqe = &lpfc_iread_cmd_template;
108 	memset(wqe, 0, sizeof(union lpfc_wqe128));
109 
110 	/* Word 0, 1, 2 - BDE is variable */
111 
112 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
113 
114 	/* Word 4 - total_xfer_len is variable */
115 
116 	/* Word 5 - is zero */
117 
118 	/* Word 6 - ctxt_tag, xri_tag is variable */
119 
120 	/* Word 7 */
121 	bf_set(wqe_cmnd, &wqe->fcp_iread.wqe_com, CMD_FCP_IREAD64_WQE);
122 	bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, PARM_READ_CHECK);
123 	bf_set(wqe_class, &wqe->fcp_iread.wqe_com, CLASS3);
124 	bf_set(wqe_ct, &wqe->fcp_iread.wqe_com, SLI4_CT_RPI);
125 
126 	/* Word 8 - abort_tag is variable */
127 
128 	/* Word 9  - reqtag is variable */
129 
130 	/* Word 10 - dbde, wqes is variable */
131 	bf_set(wqe_qosd, &wqe->fcp_iread.wqe_com, 0);
132 	bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
133 	bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com, LPFC_WQE_LENLOC_WORD4);
134 	bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
135 	bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
136 
137 	/* Word 11 - pbde is variable */
138 	bf_set(wqe_cmd_type, &wqe->fcp_iread.wqe_com, COMMAND_DATA_IN);
139 	bf_set(wqe_cqid, &wqe->fcp_iread.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
140 	bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
141 
142 	/* Word 12 - is zero */
143 
144 	/* Word 13, 14, 15 - PBDE is variable */
145 
146 	/* IWRITE template */
147 	wqe = &lpfc_iwrite_cmd_template;
148 	memset(wqe, 0, sizeof(union lpfc_wqe128));
149 
150 	/* Word 0, 1, 2 - BDE is variable */
151 
152 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
153 
154 	/* Word 4 - total_xfer_len is variable */
155 
156 	/* Word 5 - initial_xfer_len is variable */
157 
158 	/* Word 6 - ctxt_tag, xri_tag is variable */
159 
160 	/* Word 7 */
161 	bf_set(wqe_cmnd, &wqe->fcp_iwrite.wqe_com, CMD_FCP_IWRITE64_WQE);
162 	bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, PARM_READ_CHECK);
163 	bf_set(wqe_class, &wqe->fcp_iwrite.wqe_com, CLASS3);
164 	bf_set(wqe_ct, &wqe->fcp_iwrite.wqe_com, SLI4_CT_RPI);
165 
166 	/* Word 8 - abort_tag is variable */
167 
168 	/* Word 9  - reqtag is variable */
169 
170 	/* Word 10 - dbde, wqes is variable */
171 	bf_set(wqe_qosd, &wqe->fcp_iwrite.wqe_com, 0);
172 	bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
173 	bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_LENLOC_WORD4);
174 	bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
175 	bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
176 
177 	/* Word 11 - pbde is variable */
178 	bf_set(wqe_cmd_type, &wqe->fcp_iwrite.wqe_com, COMMAND_DATA_OUT);
179 	bf_set(wqe_cqid, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
180 	bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
181 
182 	/* Word 12 - is zero */
183 
184 	/* Word 13, 14, 15 - PBDE is variable */
185 
186 	/* ICMND template */
187 	wqe = &lpfc_icmnd_cmd_template;
188 	memset(wqe, 0, sizeof(union lpfc_wqe128));
189 
190 	/* Word 0, 1, 2 - BDE is variable */
191 
192 	/* Word 3 - payload_offset_len is variable */
193 
194 	/* Word 4, 5 - is zero */
195 
196 	/* Word 6 - ctxt_tag, xri_tag is variable */
197 
198 	/* Word 7 */
199 	bf_set(wqe_cmnd, &wqe->fcp_icmd.wqe_com, CMD_FCP_ICMND64_WQE);
200 	bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
201 	bf_set(wqe_class, &wqe->fcp_icmd.wqe_com, CLASS3);
202 	bf_set(wqe_ct, &wqe->fcp_icmd.wqe_com, SLI4_CT_RPI);
203 
204 	/* Word 8 - abort_tag is variable */
205 
206 	/* Word 9  - reqtag is variable */
207 
208 	/* Word 10 - dbde, wqes is variable */
209 	bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
210 	bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_NONE);
211 	bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com, LPFC_WQE_LENLOC_NONE);
212 	bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
213 	bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
214 
215 	/* Word 11 */
216 	bf_set(wqe_cmd_type, &wqe->fcp_icmd.wqe_com, COMMAND_DATA_IN);
217 	bf_set(wqe_cqid, &wqe->fcp_icmd.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
218 	bf_set(wqe_pbde, &wqe->fcp_icmd.wqe_com, 0);
219 
220 	/* Word 12, 13, 14, 15 - is zero */
221 }
222 
223 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
224 /**
225  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
226  * @srcp: Source memory pointer.
227  * @destp: Destination memory pointer.
228  * @cnt: Number of words required to be copied.
229  *       Must be a multiple of sizeof(uint64_t)
230  *
231  * This function is used for copying data between driver memory
232  * and the SLI WQ. This function also changes the endianness
233  * of each word if native endianness is different from SLI
234  * endianness. This function can be called with or without
235  * lock.
236  **/
237 static void
238 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
239 {
240 	uint64_t *src = srcp;
241 	uint64_t *dest = destp;
242 	int i;
243 
244 	for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
245 		*dest++ = *src++;
246 }
247 #else
248 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
249 #endif
250 
251 /**
252  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
253  * @q: The Work Queue to operate on.
254  * @wqe: The work Queue Entry to put on the Work queue.
255  *
256  * This routine will copy the contents of @wqe to the next available entry on
257  * the @q. This function will then ring the Work Queue Doorbell to signal the
258  * HBA to start processing the Work Queue Entry. This function returns 0 if
259  * successful. If no entries are available on @q then this function will return
260  * -ENOMEM.
261  * The caller is expected to hold the hbalock when calling this routine.
262  **/
263 static int
264 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
265 {
266 	union lpfc_wqe *temp_wqe;
267 	struct lpfc_register doorbell;
268 	uint32_t host_index;
269 	uint32_t idx;
270 	uint32_t i = 0;
271 	uint8_t *tmp;
272 	u32 if_type;
273 
274 	/* sanity check on queue memory */
275 	if (unlikely(!q))
276 		return -ENOMEM;
277 
278 	temp_wqe = lpfc_sli4_qe(q, q->host_index);
279 
280 	/* If the host has not yet processed the next entry then we are done */
281 	idx = ((q->host_index + 1) % q->entry_count);
282 	if (idx == q->hba_index) {
283 		q->WQ_overflow++;
284 		return -EBUSY;
285 	}
286 	q->WQ_posted++;
287 	/* set consumption flag every once in a while */
288 	if (!((q->host_index + 1) % q->notify_interval))
289 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
290 	else
291 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
292 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
293 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
294 	lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
295 	if (q->dpp_enable && q->phba->cfg_enable_dpp) {
296 		/* write to DPP aperture taking advatage of Combined Writes */
297 		tmp = (uint8_t *)temp_wqe;
298 #ifdef __raw_writeq
299 		for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
300 			__raw_writeq(*((uint64_t *)(tmp + i)),
301 					q->dpp_regaddr + i);
302 #else
303 		for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
304 			__raw_writel(*((uint32_t *)(tmp + i)),
305 					q->dpp_regaddr + i);
306 #endif
307 	}
308 	/* ensure WQE bcopy and DPP flushed before doorbell write */
309 	wmb();
310 
311 	/* Update the host index before invoking device */
312 	host_index = q->host_index;
313 
314 	q->host_index = idx;
315 
316 	/* Ring Doorbell */
317 	doorbell.word0 = 0;
318 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
319 		if (q->dpp_enable && q->phba->cfg_enable_dpp) {
320 			bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
321 			bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
322 			bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
323 			    q->dpp_id);
324 			bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
325 			    q->queue_id);
326 		} else {
327 			bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
328 			bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
329 
330 			/* Leave bits <23:16> clear for if_type 6 dpp */
331 			if_type = bf_get(lpfc_sli_intf_if_type,
332 					 &q->phba->sli4_hba.sli_intf);
333 			if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
334 				bf_set(lpfc_wq_db_list_fm_index, &doorbell,
335 				       host_index);
336 		}
337 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
338 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
339 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
340 	} else {
341 		return -EINVAL;
342 	}
343 	writel(doorbell.word0, q->db_regaddr);
344 
345 	return 0;
346 }
347 
348 /**
349  * lpfc_sli4_wq_release - Updates internal hba index for WQ
350  * @q: The Work Queue to operate on.
351  * @index: The index to advance the hba index to.
352  *
353  * This routine will update the HBA index of a queue to reflect consumption of
354  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
355  * an entry the host calls this function to update the queue's internal
356  * pointers.
357  **/
358 static void
359 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
360 {
361 	/* sanity check on queue memory */
362 	if (unlikely(!q))
363 		return;
364 
365 	q->hba_index = index;
366 }
367 
368 /**
369  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
370  * @q: The Mailbox Queue to operate on.
371  * @mqe: The Mailbox Queue Entry to put on the Work queue.
372  *
373  * This routine will copy the contents of @mqe to the next available entry on
374  * the @q. This function will then ring the Work Queue Doorbell to signal the
375  * HBA to start processing the Work Queue Entry. This function returns 0 if
376  * successful. If no entries are available on @q then this function will return
377  * -ENOMEM.
378  * The caller is expected to hold the hbalock when calling this routine.
379  **/
380 static uint32_t
381 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
382 {
383 	struct lpfc_mqe *temp_mqe;
384 	struct lpfc_register doorbell;
385 
386 	/* sanity check on queue memory */
387 	if (unlikely(!q))
388 		return -ENOMEM;
389 	temp_mqe = lpfc_sli4_qe(q, q->host_index);
390 
391 	/* If the host has not yet processed the next entry then we are done */
392 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
393 		return -ENOMEM;
394 	lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
395 	/* Save off the mailbox pointer for completion */
396 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
397 
398 	/* Update the host index before invoking device */
399 	q->host_index = ((q->host_index + 1) % q->entry_count);
400 
401 	/* Ring Doorbell */
402 	doorbell.word0 = 0;
403 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
404 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
405 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
406 	return 0;
407 }
408 
409 /**
410  * lpfc_sli4_mq_release - Updates internal hba index for MQ
411  * @q: The Mailbox Queue to operate on.
412  *
413  * This routine will update the HBA index of a queue to reflect consumption of
414  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
415  * an entry the host calls this function to update the queue's internal
416  * pointers. This routine returns the number of entries that were consumed by
417  * the HBA.
418  **/
419 static uint32_t
420 lpfc_sli4_mq_release(struct lpfc_queue *q)
421 {
422 	/* sanity check on queue memory */
423 	if (unlikely(!q))
424 		return 0;
425 
426 	/* Clear the mailbox pointer for completion */
427 	q->phba->mbox = NULL;
428 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
429 	return 1;
430 }
431 
432 /**
433  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
434  * @q: The Event Queue to get the first valid EQE from
435  *
436  * This routine will get the first valid Event Queue Entry from @q, update
437  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
438  * the Queue (no more work to do), or the Queue is full of EQEs that have been
439  * processed, but not popped back to the HBA then this routine will return NULL.
440  **/
441 static struct lpfc_eqe *
442 lpfc_sli4_eq_get(struct lpfc_queue *q)
443 {
444 	struct lpfc_eqe *eqe;
445 
446 	/* sanity check on queue memory */
447 	if (unlikely(!q))
448 		return NULL;
449 	eqe = lpfc_sli4_qe(q, q->host_index);
450 
451 	/* If the next EQE is not valid then we are done */
452 	if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
453 		return NULL;
454 
455 	/*
456 	 * insert barrier for instruction interlock : data from the hardware
457 	 * must have the valid bit checked before it can be copied and acted
458 	 * upon. Speculative instructions were allowing a bcopy at the start
459 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
460 	 * after our return, to copy data before the valid bit check above
461 	 * was done. As such, some of the copied data was stale. The barrier
462 	 * ensures the check is before any data is copied.
463 	 */
464 	mb();
465 	return eqe;
466 }
467 
468 /**
469  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
470  * @q: The Event Queue to disable interrupts
471  *
472  **/
473 void
474 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
475 {
476 	struct lpfc_register doorbell;
477 
478 	doorbell.word0 = 0;
479 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
480 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
481 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
482 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
483 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
484 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
485 }
486 
487 /**
488  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
489  * @q: The Event Queue to disable interrupts
490  *
491  **/
492 void
493 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
494 {
495 	struct lpfc_register doorbell;
496 
497 	doorbell.word0 = 0;
498 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
499 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
500 }
501 
502 /**
503  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
504  * @phba: adapter with EQ
505  * @q: The Event Queue that the host has completed processing for.
506  * @count: Number of elements that have been consumed
507  * @arm: Indicates whether the host wants to arms this CQ.
508  *
509  * This routine will notify the HBA, by ringing the doorbell, that count
510  * number of EQEs have been processed. The @arm parameter indicates whether
511  * the queue should be rearmed when ringing the doorbell.
512  **/
513 void
514 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
515 		     uint32_t count, bool arm)
516 {
517 	struct lpfc_register doorbell;
518 
519 	/* sanity check on queue memory */
520 	if (unlikely(!q || (count == 0 && !arm)))
521 		return;
522 
523 	/* ring doorbell for number popped */
524 	doorbell.word0 = 0;
525 	if (arm) {
526 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
527 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
528 	}
529 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
530 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
531 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
532 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
533 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
534 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
535 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
536 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
537 		readl(q->phba->sli4_hba.EQDBregaddr);
538 }
539 
540 /**
541  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
542  * @phba: adapter with EQ
543  * @q: The Event Queue that the host has completed processing for.
544  * @count: Number of elements that have been consumed
545  * @arm: Indicates whether the host wants to arms this CQ.
546  *
547  * This routine will notify the HBA, by ringing the doorbell, that count
548  * number of EQEs have been processed. The @arm parameter indicates whether
549  * the queue should be rearmed when ringing the doorbell.
550  **/
551 void
552 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
553 			  uint32_t count, bool arm)
554 {
555 	struct lpfc_register doorbell;
556 
557 	/* sanity check on queue memory */
558 	if (unlikely(!q || (count == 0 && !arm)))
559 		return;
560 
561 	/* ring doorbell for number popped */
562 	doorbell.word0 = 0;
563 	if (arm)
564 		bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
565 	bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
566 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
567 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
568 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
569 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
570 		readl(q->phba->sli4_hba.EQDBregaddr);
571 }
572 
573 static void
574 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
575 			struct lpfc_eqe *eqe)
576 {
577 	if (!phba->sli4_hba.pc_sli4_params.eqav)
578 		bf_set_le32(lpfc_eqe_valid, eqe, 0);
579 
580 	eq->host_index = ((eq->host_index + 1) % eq->entry_count);
581 
582 	/* if the index wrapped around, toggle the valid bit */
583 	if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
584 		eq->qe_valid = (eq->qe_valid) ? 0 : 1;
585 }
586 
587 static void
588 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
589 {
590 	struct lpfc_eqe *eqe = NULL;
591 	u32 eq_count = 0, cq_count = 0;
592 	struct lpfc_cqe *cqe = NULL;
593 	struct lpfc_queue *cq = NULL, *childq = NULL;
594 	int cqid = 0;
595 
596 	/* walk all the EQ entries and drop on the floor */
597 	eqe = lpfc_sli4_eq_get(eq);
598 	while (eqe) {
599 		/* Get the reference to the corresponding CQ */
600 		cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
601 		cq = NULL;
602 
603 		list_for_each_entry(childq, &eq->child_list, list) {
604 			if (childq->queue_id == cqid) {
605 				cq = childq;
606 				break;
607 			}
608 		}
609 		/* If CQ is valid, iterate through it and drop all the CQEs */
610 		if (cq) {
611 			cqe = lpfc_sli4_cq_get(cq);
612 			while (cqe) {
613 				__lpfc_sli4_consume_cqe(phba, cq, cqe);
614 				cq_count++;
615 				cqe = lpfc_sli4_cq_get(cq);
616 			}
617 			/* Clear and re-arm the CQ */
618 			phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
619 			    LPFC_QUEUE_REARM);
620 			cq_count = 0;
621 		}
622 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
623 		eq_count++;
624 		eqe = lpfc_sli4_eq_get(eq);
625 	}
626 
627 	/* Clear and re-arm the EQ */
628 	phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
629 }
630 
631 static int
632 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
633 		     u8 rearm, enum lpfc_poll_mode poll_mode)
634 {
635 	struct lpfc_eqe *eqe;
636 	int count = 0, consumed = 0;
637 
638 	if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
639 		goto rearm_and_exit;
640 
641 	eqe = lpfc_sli4_eq_get(eq);
642 	while (eqe) {
643 		lpfc_sli4_hba_handle_eqe(phba, eq, eqe, poll_mode);
644 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
645 
646 		consumed++;
647 		if (!(++count % eq->max_proc_limit))
648 			break;
649 
650 		if (!(count % eq->notify_interval)) {
651 			phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
652 							LPFC_QUEUE_NOARM);
653 			consumed = 0;
654 		}
655 
656 		eqe = lpfc_sli4_eq_get(eq);
657 	}
658 	eq->EQ_processed += count;
659 
660 	/* Track the max number of EQEs processed in 1 intr */
661 	if (count > eq->EQ_max_eqe)
662 		eq->EQ_max_eqe = count;
663 
664 	xchg(&eq->queue_claimed, 0);
665 
666 rearm_and_exit:
667 	/* Always clear the EQ. */
668 	phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
669 
670 	return count;
671 }
672 
673 /**
674  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
675  * @q: The Completion Queue to get the first valid CQE from
676  *
677  * This routine will get the first valid Completion Queue Entry from @q, update
678  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
679  * the Queue (no more work to do), or the Queue is full of CQEs that have been
680  * processed, but not popped back to the HBA then this routine will return NULL.
681  **/
682 static struct lpfc_cqe *
683 lpfc_sli4_cq_get(struct lpfc_queue *q)
684 {
685 	struct lpfc_cqe *cqe;
686 
687 	/* sanity check on queue memory */
688 	if (unlikely(!q))
689 		return NULL;
690 	cqe = lpfc_sli4_qe(q, q->host_index);
691 
692 	/* If the next CQE is not valid then we are done */
693 	if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
694 		return NULL;
695 
696 	/*
697 	 * insert barrier for instruction interlock : data from the hardware
698 	 * must have the valid bit checked before it can be copied and acted
699 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
700 	 * instructions allowing action on content before valid bit checked,
701 	 * add barrier here as well. May not be needed as "content" is a
702 	 * single 32-bit entity here (vs multi word structure for cq's).
703 	 */
704 	mb();
705 	return cqe;
706 }
707 
708 static void
709 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
710 			struct lpfc_cqe *cqe)
711 {
712 	if (!phba->sli4_hba.pc_sli4_params.cqav)
713 		bf_set_le32(lpfc_cqe_valid, cqe, 0);
714 
715 	cq->host_index = ((cq->host_index + 1) % cq->entry_count);
716 
717 	/* if the index wrapped around, toggle the valid bit */
718 	if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
719 		cq->qe_valid = (cq->qe_valid) ? 0 : 1;
720 }
721 
722 /**
723  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
724  * @phba: the adapter with the CQ
725  * @q: The Completion Queue that the host has completed processing for.
726  * @count: the number of elements that were consumed
727  * @arm: Indicates whether the host wants to arms this CQ.
728  *
729  * This routine will notify the HBA, by ringing the doorbell, that the
730  * CQEs have been processed. The @arm parameter specifies whether the
731  * queue should be rearmed when ringing the doorbell.
732  **/
733 void
734 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
735 		     uint32_t count, bool arm)
736 {
737 	struct lpfc_register doorbell;
738 
739 	/* sanity check on queue memory */
740 	if (unlikely(!q || (count == 0 && !arm)))
741 		return;
742 
743 	/* ring doorbell for number popped */
744 	doorbell.word0 = 0;
745 	if (arm)
746 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
747 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
748 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
749 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
750 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
751 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
752 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
753 }
754 
755 /**
756  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
757  * @phba: the adapter with the CQ
758  * @q: The Completion Queue that the host has completed processing for.
759  * @count: the number of elements that were consumed
760  * @arm: Indicates whether the host wants to arms this CQ.
761  *
762  * This routine will notify the HBA, by ringing the doorbell, that the
763  * CQEs have been processed. The @arm parameter specifies whether the
764  * queue should be rearmed when ringing the doorbell.
765  **/
766 void
767 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
768 			 uint32_t count, bool arm)
769 {
770 	struct lpfc_register doorbell;
771 
772 	/* sanity check on queue memory */
773 	if (unlikely(!q || (count == 0 && !arm)))
774 		return;
775 
776 	/* ring doorbell for number popped */
777 	doorbell.word0 = 0;
778 	if (arm)
779 		bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
780 	bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
781 	bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
782 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
783 }
784 
785 /*
786  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
787  *
788  * This routine will copy the contents of @wqe to the next available entry on
789  * the @q. This function will then ring the Receive Queue Doorbell to signal the
790  * HBA to start processing the Receive Queue Entry. This function returns the
791  * index that the rqe was copied to if successful. If no entries are available
792  * on @q then this function will return -ENOMEM.
793  * The caller is expected to hold the hbalock when calling this routine.
794  **/
795 int
796 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
797 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
798 {
799 	struct lpfc_rqe *temp_hrqe;
800 	struct lpfc_rqe *temp_drqe;
801 	struct lpfc_register doorbell;
802 	int hq_put_index;
803 	int dq_put_index;
804 
805 	/* sanity check on queue memory */
806 	if (unlikely(!hq) || unlikely(!dq))
807 		return -ENOMEM;
808 	hq_put_index = hq->host_index;
809 	dq_put_index = dq->host_index;
810 	temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
811 	temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
812 
813 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
814 		return -EINVAL;
815 	if (hq_put_index != dq_put_index)
816 		return -EINVAL;
817 	/* If the host has not yet processed the next entry then we are done */
818 	if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
819 		return -EBUSY;
820 	lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
821 	lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
822 
823 	/* Update the host index to point to the next slot */
824 	hq->host_index = ((hq_put_index + 1) % hq->entry_count);
825 	dq->host_index = ((dq_put_index + 1) % dq->entry_count);
826 	hq->RQ_buf_posted++;
827 
828 	/* Ring The Header Receive Queue Doorbell */
829 	if (!(hq->host_index % hq->notify_interval)) {
830 		doorbell.word0 = 0;
831 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
832 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
833 			       hq->notify_interval);
834 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
835 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
836 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
837 			       hq->notify_interval);
838 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
839 			       hq->host_index);
840 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
841 		} else {
842 			return -EINVAL;
843 		}
844 		writel(doorbell.word0, hq->db_regaddr);
845 	}
846 	return hq_put_index;
847 }
848 
849 /*
850  * lpfc_sli4_rq_release - Updates internal hba index for RQ
851  *
852  * This routine will update the HBA index of a queue to reflect consumption of
853  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
854  * consumed an entry the host calls this function to update the queue's
855  * internal pointers. This routine returns the number of entries that were
856  * consumed by the HBA.
857  **/
858 static uint32_t
859 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
860 {
861 	/* sanity check on queue memory */
862 	if (unlikely(!hq) || unlikely(!dq))
863 		return 0;
864 
865 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
866 		return 0;
867 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
868 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
869 	return 1;
870 }
871 
872 /**
873  * lpfc_cmd_iocb - Get next command iocb entry in the ring
874  * @phba: Pointer to HBA context object.
875  * @pring: Pointer to driver SLI ring object.
876  *
877  * This function returns pointer to next command iocb entry
878  * in the command ring. The caller must hold hbalock to prevent
879  * other threads consume the next command iocb.
880  * SLI-2/SLI-3 provide different sized iocbs.
881  **/
882 static inline IOCB_t *
883 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
884 {
885 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
886 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
887 }
888 
889 /**
890  * lpfc_resp_iocb - Get next response iocb entry in the ring
891  * @phba: Pointer to HBA context object.
892  * @pring: Pointer to driver SLI ring object.
893  *
894  * This function returns pointer to next response iocb entry
895  * in the response ring. The caller must hold hbalock to make sure
896  * that no other thread consume the next response iocb.
897  * SLI-2/SLI-3 provide different sized iocbs.
898  **/
899 static inline IOCB_t *
900 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
901 {
902 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
903 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
904 }
905 
906 /**
907  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
908  * @phba: Pointer to HBA context object.
909  *
910  * This function is called with hbalock held. This function
911  * allocates a new driver iocb object from the iocb pool. If the
912  * allocation is successful, it returns pointer to the newly
913  * allocated iocb object else it returns NULL.
914  **/
915 struct lpfc_iocbq *
916 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
917 {
918 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
919 	struct lpfc_iocbq * iocbq = NULL;
920 
921 	lockdep_assert_held(&phba->hbalock);
922 
923 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
924 	if (iocbq)
925 		phba->iocb_cnt++;
926 	if (phba->iocb_cnt > phba->iocb_max)
927 		phba->iocb_max = phba->iocb_cnt;
928 	return iocbq;
929 }
930 
931 /**
932  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
933  * @phba: Pointer to HBA context object.
934  * @xritag: XRI value.
935  *
936  * This function clears the sglq pointer from the array of active
937  * sglq's. The xritag that is passed in is used to index into the
938  * array. Before the xritag can be used it needs to be adjusted
939  * by subtracting the xribase.
940  *
941  * Returns sglq ponter = success, NULL = Failure.
942  **/
943 struct lpfc_sglq *
944 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
945 {
946 	struct lpfc_sglq *sglq;
947 
948 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
949 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
950 	return sglq;
951 }
952 
953 /**
954  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
955  * @phba: Pointer to HBA context object.
956  * @xritag: XRI value.
957  *
958  * This function returns the sglq pointer from the array of active
959  * sglq's. The xritag that is passed in is used to index into the
960  * array. Before the xritag can be used it needs to be adjusted
961  * by subtracting the xribase.
962  *
963  * Returns sglq ponter = success, NULL = Failure.
964  **/
965 struct lpfc_sglq *
966 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
967 {
968 	struct lpfc_sglq *sglq;
969 
970 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
971 	return sglq;
972 }
973 
974 /**
975  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
976  * @phba: Pointer to HBA context object.
977  * @xritag: xri used in this exchange.
978  * @rrq: The RRQ to be cleared.
979  *
980  **/
981 void
982 lpfc_clr_rrq_active(struct lpfc_hba *phba,
983 		    uint16_t xritag,
984 		    struct lpfc_node_rrq *rrq)
985 {
986 	struct lpfc_nodelist *ndlp = NULL;
987 
988 	/* Lookup did to verify if did is still active on this vport */
989 	if (rrq->vport)
990 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
991 
992 	if (!ndlp)
993 		goto out;
994 
995 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
996 		rrq->send_rrq = 0;
997 		rrq->xritag = 0;
998 		rrq->rrq_stop_time = 0;
999 	}
1000 out:
1001 	mempool_free(rrq, phba->rrq_pool);
1002 }
1003 
1004 /**
1005  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
1006  * @phba: Pointer to HBA context object.
1007  *
1008  * This function is called with hbalock held. This function
1009  * Checks if stop_time (ratov from setting rrq active) has
1010  * been reached, if it has and the send_rrq flag is set then
1011  * it will call lpfc_send_rrq. If the send_rrq flag is not set
1012  * then it will just call the routine to clear the rrq and
1013  * free the rrq resource.
1014  * The timer is set to the next rrq that is going to expire before
1015  * leaving the routine.
1016  *
1017  **/
1018 void
1019 lpfc_handle_rrq_active(struct lpfc_hba *phba)
1020 {
1021 	struct lpfc_node_rrq *rrq;
1022 	struct lpfc_node_rrq *nextrrq;
1023 	unsigned long next_time;
1024 	unsigned long iflags;
1025 	LIST_HEAD(send_rrq);
1026 
1027 	clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1028 	next_time = jiffies + secs_to_jiffies(phba->fc_ratov + 1);
1029 	spin_lock_irqsave(&phba->rrq_list_lock, iflags);
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->rrq_list_lock, iflags);
1038 	if ((!list_empty(&phba->active_rrq_list)) &&
1039 	    (!test_bit(FC_UNLOADING, &phba->pport->load_flag)))
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->rrq_list_lock, 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->rrq_list_lock, iflags);
1081 			return rrq;
1082 		}
1083 	}
1084 	spin_unlock_irqrestore(&phba->rrq_list_lock, 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->rrq_list_lock, 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->rrq_list_lock, 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 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
1183 		clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1184 		goto outnl;
1185 	}
1186 
1187 	spin_lock_irqsave(&phba->hbalock, iflags);
1188 	if (ndlp->vport && test_bit(FC_UNLOADING, &ndlp->vport->load_flag))
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 + secs_to_jiffies(phba->fc_ratov + 1);
1212 	rrq->nlp_DID = ndlp->nlp_DID;
1213 	rrq->vport = ndlp->vport;
1214 	rrq->rxid = rxid;
1215 
1216 	spin_lock_irqsave(&phba->rrq_list_lock, iflags);
1217 	empty = list_empty(&phba->active_rrq_list);
1218 	list_add_tail(&rrq->list, &phba->active_rrq_list);
1219 	spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1220 	set_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1221 	if (empty)
1222 		lpfc_worker_wake_up(phba);
1223 	return 0;
1224 out:
1225 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1226 outnl:
1227 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1228 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
1229 			" DID:0x%x Send:%d\n",
1230 			xritag, rxid, ndlp->nlp_DID, send_rrq);
1231 	return -EINVAL;
1232 }
1233 
1234 /**
1235  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1236  * @phba: Pointer to HBA context object.
1237  * @piocbq: Pointer to the iocbq.
1238  *
1239  * The driver calls this function with either the nvme ls ring lock
1240  * or the fc els ring lock held depending on the iocb usage.  This function
1241  * gets a new driver sglq object from the sglq list. If the list is not empty
1242  * then it is successful, it returns pointer to the newly allocated sglq
1243  * object else it returns NULL.
1244  **/
1245 static struct lpfc_sglq *
1246 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1247 {
1248 	struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1249 	struct lpfc_sglq *sglq = NULL;
1250 	struct lpfc_sglq *start_sglq = NULL;
1251 	struct lpfc_io_buf *lpfc_cmd;
1252 	struct lpfc_nodelist *ndlp;
1253 	int found = 0;
1254 	u8 cmnd;
1255 
1256 	cmnd = get_job_cmnd(phba, piocbq);
1257 
1258 	if (piocbq->cmd_flag & LPFC_IO_FCP) {
1259 		lpfc_cmd = piocbq->io_buf;
1260 		ndlp = lpfc_cmd->rdata->pnode;
1261 	} else  if ((cmnd == CMD_GEN_REQUEST64_CR) &&
1262 			!(piocbq->cmd_flag & LPFC_IO_LIBDFC)) {
1263 		ndlp = piocbq->ndlp;
1264 	} else  if (piocbq->cmd_flag & LPFC_IO_LIBDFC) {
1265 		if (piocbq->cmd_flag & LPFC_IO_LOOPBACK)
1266 			ndlp = NULL;
1267 		else
1268 			ndlp = piocbq->ndlp;
1269 	} else {
1270 		ndlp = piocbq->ndlp;
1271 	}
1272 
1273 	spin_lock(&phba->sli4_hba.sgl_list_lock);
1274 	list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1275 	start_sglq = sglq;
1276 	while (!found) {
1277 		if (!sglq)
1278 			break;
1279 		if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1280 		    test_bit(sglq->sli4_lxritag,
1281 		    ndlp->active_rrqs_xri_bitmap)) {
1282 			/* This xri has an rrq outstanding for this DID.
1283 			 * put it back in the list and get another xri.
1284 			 */
1285 			list_add_tail(&sglq->list, lpfc_els_sgl_list);
1286 			sglq = NULL;
1287 			list_remove_head(lpfc_els_sgl_list, sglq,
1288 						struct lpfc_sglq, list);
1289 			if (sglq == start_sglq) {
1290 				list_add_tail(&sglq->list, lpfc_els_sgl_list);
1291 				sglq = NULL;
1292 				break;
1293 			} else
1294 				continue;
1295 		}
1296 		sglq->ndlp = ndlp;
1297 		found = 1;
1298 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1299 		sglq->state = SGL_ALLOCATED;
1300 	}
1301 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
1302 	return sglq;
1303 }
1304 
1305 /**
1306  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1307  * @phba: Pointer to HBA context object.
1308  * @piocbq: Pointer to the iocbq.
1309  *
1310  * This function is called with the sgl_list lock held. This function
1311  * gets a new driver sglq object from the sglq list. If the
1312  * list is not empty then it is successful, it returns pointer to the newly
1313  * allocated sglq object else it returns NULL.
1314  **/
1315 struct lpfc_sglq *
1316 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1317 {
1318 	struct list_head *lpfc_nvmet_sgl_list;
1319 	struct lpfc_sglq *sglq = NULL;
1320 
1321 	lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1322 
1323 	lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1324 
1325 	list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1326 	if (!sglq)
1327 		return NULL;
1328 	phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1329 	sglq->state = SGL_ALLOCATED;
1330 	return sglq;
1331 }
1332 
1333 /**
1334  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1335  * @phba: Pointer to HBA context object.
1336  *
1337  * This function is called with no lock held. This function
1338  * allocates a new driver iocb object from the iocb pool. If the
1339  * allocation is successful, it returns pointer to the newly
1340  * allocated iocb object else it returns NULL.
1341  **/
1342 struct lpfc_iocbq *
1343 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1344 {
1345 	struct lpfc_iocbq * iocbq = NULL;
1346 	unsigned long iflags;
1347 
1348 	spin_lock_irqsave(&phba->hbalock, iflags);
1349 	iocbq = __lpfc_sli_get_iocbq(phba);
1350 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1351 	return iocbq;
1352 }
1353 
1354 /**
1355  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1356  * @phba: Pointer to HBA context object.
1357  * @iocbq: Pointer to driver iocb object.
1358  *
1359  * This function is called to release the driver iocb object
1360  * to the iocb pool. The iotag in the iocb object
1361  * does not change for each use of the iocb object. This function
1362  * clears all other fields of the iocb object when it is freed.
1363  * The sqlq structure that holds the xritag and phys and virtual
1364  * mappings for the scatter gather list is retrieved from the
1365  * active array of sglq. The get of the sglq pointer also clears
1366  * the entry in the array. If the status of the IO indiactes that
1367  * this IO was aborted then the sglq entry it put on the
1368  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1369  * IO has good status or fails for any other reason then the sglq
1370  * entry is added to the free list (lpfc_els_sgl_list). The hbalock is
1371  *  asserted held in the code path calling this routine.
1372  **/
1373 static void
1374 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1375 {
1376 	struct lpfc_sglq *sglq;
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_startat(iocbq, 0, wqe);
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 
1457 	/*
1458 	 * Clean all volatile data fields, preserve iotag and node struct.
1459 	 */
1460 	memset_startat(iocbq, 0, iocb);
1461 	iocbq->sli4_xritag = NO_XRI;
1462 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1463 }
1464 
1465 /**
1466  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1467  * @phba: Pointer to HBA context object.
1468  * @iocbq: Pointer to driver iocb object.
1469  *
1470  * This function is called with hbalock held to release driver
1471  * iocb object to the iocb pool. The iotag in the iocb object
1472  * does not change for each use of the iocb object. This function
1473  * clears all other fields of the iocb object when it is freed.
1474  **/
1475 static void
1476 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1477 {
1478 	lockdep_assert_held(&phba->hbalock);
1479 
1480 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1481 	phba->iocb_cnt--;
1482 }
1483 
1484 /**
1485  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1486  * @phba: Pointer to HBA context object.
1487  * @iocbq: Pointer to driver iocb object.
1488  *
1489  * This function is called with no lock held to release the iocb to
1490  * iocb pool.
1491  **/
1492 void
1493 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1494 {
1495 	unsigned long iflags;
1496 
1497 	/*
1498 	 * Clean all volatile data fields, preserve iotag and node struct.
1499 	 */
1500 	spin_lock_irqsave(&phba->hbalock, iflags);
1501 	__lpfc_sli_release_iocbq(phba, iocbq);
1502 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1503 }
1504 
1505 /**
1506  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1507  * @phba: Pointer to HBA context object.
1508  * @iocblist: List of IOCBs.
1509  * @ulpstatus: ULP status in IOCB command field.
1510  * @ulpWord4: ULP word-4 in IOCB command field.
1511  *
1512  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1513  * on the list by invoking the complete callback function associated with the
1514  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1515  * fields.
1516  **/
1517 void
1518 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1519 		      uint32_t ulpstatus, uint32_t ulpWord4)
1520 {
1521 	struct lpfc_iocbq *piocb;
1522 
1523 	while (!list_empty(iocblist)) {
1524 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1525 		if (piocb->cmd_cmpl) {
1526 			if (piocb->cmd_flag & LPFC_IO_NVME) {
1527 				lpfc_nvme_cancel_iocb(phba, piocb,
1528 						      ulpstatus, ulpWord4);
1529 			} else {
1530 				if (phba->sli_rev == LPFC_SLI_REV4) {
1531 					bf_set(lpfc_wcqe_c_status,
1532 					       &piocb->wcqe_cmpl, ulpstatus);
1533 					piocb->wcqe_cmpl.parameter = ulpWord4;
1534 				} else {
1535 					piocb->iocb.ulpStatus = ulpstatus;
1536 					piocb->iocb.un.ulpWord[4] = ulpWord4;
1537 				}
1538 				(piocb->cmd_cmpl) (phba, piocb, piocb);
1539 			}
1540 		} else {
1541 			lpfc_sli_release_iocbq(phba, piocb);
1542 		}
1543 	}
1544 	return;
1545 }
1546 
1547 /**
1548  * lpfc_sli_iocb_cmd_type - Get the iocb type
1549  * @iocb_cmnd: iocb command code.
1550  *
1551  * This function is called by ring event handler function to get the iocb type.
1552  * This function translates the iocb command to an iocb command type used to
1553  * decide the final disposition of each completed IOCB.
1554  * The function returns
1555  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1556  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1557  * LPFC_ABORT_IOCB   if it is an abort iocb
1558  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1559  *
1560  * The caller is not required to hold any lock.
1561  **/
1562 static lpfc_iocb_type
1563 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1564 {
1565 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1566 
1567 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1568 		return 0;
1569 
1570 	switch (iocb_cmnd) {
1571 	case CMD_XMIT_SEQUENCE_CR:
1572 	case CMD_XMIT_SEQUENCE_CX:
1573 	case CMD_XMIT_BCAST_CN:
1574 	case CMD_XMIT_BCAST_CX:
1575 	case CMD_ELS_REQUEST_CR:
1576 	case CMD_ELS_REQUEST_CX:
1577 	case CMD_CREATE_XRI_CR:
1578 	case CMD_CREATE_XRI_CX:
1579 	case CMD_GET_RPI_CN:
1580 	case CMD_XMIT_ELS_RSP_CX:
1581 	case CMD_GET_RPI_CR:
1582 	case CMD_FCP_IWRITE_CR:
1583 	case CMD_FCP_IWRITE_CX:
1584 	case CMD_FCP_IREAD_CR:
1585 	case CMD_FCP_IREAD_CX:
1586 	case CMD_FCP_ICMND_CR:
1587 	case CMD_FCP_ICMND_CX:
1588 	case CMD_FCP_TSEND_CX:
1589 	case CMD_FCP_TRSP_CX:
1590 	case CMD_FCP_TRECEIVE_CX:
1591 	case CMD_FCP_AUTO_TRSP_CX:
1592 	case CMD_ADAPTER_MSG:
1593 	case CMD_ADAPTER_DUMP:
1594 	case CMD_XMIT_SEQUENCE64_CR:
1595 	case CMD_XMIT_SEQUENCE64_CX:
1596 	case CMD_XMIT_BCAST64_CN:
1597 	case CMD_XMIT_BCAST64_CX:
1598 	case CMD_ELS_REQUEST64_CR:
1599 	case CMD_ELS_REQUEST64_CX:
1600 	case CMD_FCP_IWRITE64_CR:
1601 	case CMD_FCP_IWRITE64_CX:
1602 	case CMD_FCP_IREAD64_CR:
1603 	case CMD_FCP_IREAD64_CX:
1604 	case CMD_FCP_ICMND64_CR:
1605 	case CMD_FCP_ICMND64_CX:
1606 	case CMD_FCP_TSEND64_CX:
1607 	case CMD_FCP_TRSP64_CX:
1608 	case CMD_FCP_TRECEIVE64_CX:
1609 	case CMD_GEN_REQUEST64_CR:
1610 	case CMD_GEN_REQUEST64_CX:
1611 	case CMD_XMIT_ELS_RSP64_CX:
1612 	case DSSCMD_IWRITE64_CR:
1613 	case DSSCMD_IWRITE64_CX:
1614 	case DSSCMD_IREAD64_CR:
1615 	case DSSCMD_IREAD64_CX:
1616 	case CMD_SEND_FRAME:
1617 		type = LPFC_SOL_IOCB;
1618 		break;
1619 	case CMD_ABORT_XRI_CN:
1620 	case CMD_ABORT_XRI_CX:
1621 	case CMD_CLOSE_XRI_CN:
1622 	case CMD_CLOSE_XRI_CX:
1623 	case CMD_XRI_ABORTED_CX:
1624 	case CMD_ABORT_MXRI64_CN:
1625 	case CMD_XMIT_BLS_RSP64_CX:
1626 		type = LPFC_ABORT_IOCB;
1627 		break;
1628 	case CMD_RCV_SEQUENCE_CX:
1629 	case CMD_RCV_ELS_REQ_CX:
1630 	case CMD_RCV_SEQUENCE64_CX:
1631 	case CMD_RCV_ELS_REQ64_CX:
1632 	case CMD_ASYNC_STATUS:
1633 	case CMD_IOCB_RCV_SEQ64_CX:
1634 	case CMD_IOCB_RCV_ELS64_CX:
1635 	case CMD_IOCB_RCV_CONT64_CX:
1636 	case CMD_IOCB_RET_XRI64_CX:
1637 		type = LPFC_UNSOL_IOCB;
1638 		break;
1639 	case CMD_IOCB_XMIT_MSEQ64_CR:
1640 	case CMD_IOCB_XMIT_MSEQ64_CX:
1641 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1642 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1643 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1644 	case CMD_IOCB_ABORT_EXTENDED_CN:
1645 	case CMD_IOCB_RET_HBQE64_CN:
1646 	case CMD_IOCB_FCP_IBIDIR64_CR:
1647 	case CMD_IOCB_FCP_IBIDIR64_CX:
1648 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1649 	case CMD_IOCB_LOGENTRY_CN:
1650 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1651 		printk("%s - Unhandled SLI-3 Command x%x\n",
1652 				__func__, iocb_cmnd);
1653 		type = LPFC_UNKNOWN_IOCB;
1654 		break;
1655 	default:
1656 		type = LPFC_UNKNOWN_IOCB;
1657 		break;
1658 	}
1659 
1660 	return type;
1661 }
1662 
1663 /**
1664  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1665  * @phba: Pointer to HBA context object.
1666  *
1667  * This function is called from SLI initialization code
1668  * to configure every ring of the HBA's SLI interface. The
1669  * caller is not required to hold any lock. This function issues
1670  * a config_ring mailbox command for each ring.
1671  * This function returns zero if successful else returns a negative
1672  * error code.
1673  **/
1674 static int
1675 lpfc_sli_ring_map(struct lpfc_hba *phba)
1676 {
1677 	struct lpfc_sli *psli = &phba->sli;
1678 	LPFC_MBOXQ_t *pmb;
1679 	MAILBOX_t *pmbox;
1680 	int i, rc, ret = 0;
1681 
1682 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1683 	if (!pmb)
1684 		return -ENOMEM;
1685 	pmbox = &pmb->u.mb;
1686 	phba->link_state = LPFC_INIT_MBX_CMDS;
1687 	for (i = 0; i < psli->num_rings; i++) {
1688 		lpfc_config_ring(phba, i, pmb);
1689 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1690 		if (rc != MBX_SUCCESS) {
1691 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1692 					"0446 Adapter failed to init (%d), "
1693 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1694 					"ring %d\n",
1695 					rc, pmbox->mbxCommand,
1696 					pmbox->mbxStatus, i);
1697 			phba->link_state = LPFC_HBA_ERROR;
1698 			ret = -ENXIO;
1699 			break;
1700 		}
1701 	}
1702 	mempool_free(pmb, phba->mbox_mem_pool);
1703 	return ret;
1704 }
1705 
1706 /**
1707  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1708  * @phba: Pointer to HBA context object.
1709  * @pring: Pointer to driver SLI ring object.
1710  * @piocb: Pointer to the driver iocb object.
1711  *
1712  * The driver calls this function with the hbalock held for SLI3 ports or
1713  * the ring lock held for SLI4 ports. The function adds the
1714  * new iocb to txcmplq of the given ring. This function always returns
1715  * 0. If this function is called for ELS ring, this function checks if
1716  * there is a vport associated with the ELS command. This function also
1717  * starts els_tmofunc timer if this is an ELS command.
1718  **/
1719 static int
1720 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1721 			struct lpfc_iocbq *piocb)
1722 {
1723 	u32 ulp_command = 0;
1724 
1725 	BUG_ON(!piocb);
1726 	ulp_command = get_job_cmnd(phba, piocb);
1727 
1728 	list_add_tail(&piocb->list, &pring->txcmplq);
1729 	piocb->cmd_flag |= LPFC_IO_ON_TXCMPLQ;
1730 	pring->txcmplq_cnt++;
1731 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1732 	   (ulp_command != CMD_ABORT_XRI_WQE) &&
1733 	   (ulp_command != CMD_ABORT_XRI_CN) &&
1734 	   (ulp_command != CMD_CLOSE_XRI_CN)) {
1735 		BUG_ON(!piocb->vport);
1736 		if (!test_bit(FC_UNLOADING, &piocb->vport->load_flag))
1737 			mod_timer(&piocb->vport->els_tmofunc,
1738 				  jiffies + secs_to_jiffies(phba->fc_ratov << 1));
1739 	}
1740 
1741 	return 0;
1742 }
1743 
1744 /**
1745  * lpfc_sli_ringtx_get - Get first element of the txq
1746  * @phba: Pointer to HBA context object.
1747  * @pring: Pointer to driver SLI ring object.
1748  *
1749  * This function is called with hbalock held to get next
1750  * iocb in txq of the given ring. If there is any iocb in
1751  * the txq, the function returns first iocb in the list after
1752  * removing the iocb from the list, else it returns NULL.
1753  **/
1754 struct lpfc_iocbq *
1755 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1756 {
1757 	struct lpfc_iocbq *cmd_iocb;
1758 
1759 	lockdep_assert_held(&phba->hbalock);
1760 
1761 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1762 	return cmd_iocb;
1763 }
1764 
1765 /**
1766  * lpfc_cmf_sync_cmpl - Process a CMF_SYNC_WQE cmpl
1767  * @phba: Pointer to HBA context object.
1768  * @cmdiocb: Pointer to driver command iocb object.
1769  * @rspiocb: Pointer to driver response iocb object.
1770  *
1771  * This routine will inform the driver of any BW adjustments we need
1772  * to make. These changes will be picked up during the next CMF
1773  * timer interrupt. In addition, any BW changes will be logged
1774  * with LOG_CGN_MGMT.
1775  **/
1776 static void
1777 lpfc_cmf_sync_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
1778 		   struct lpfc_iocbq *rspiocb)
1779 {
1780 	union lpfc_wqe128 *wqe;
1781 	uint32_t status, info;
1782 	struct lpfc_wcqe_complete *wcqe = &rspiocb->wcqe_cmpl;
1783 	uint64_t bw, bwdif, slop;
1784 	uint64_t pcent, bwpcent;
1785 	int asig, afpin, sigcnt, fpincnt;
1786 	int wsigmax, wfpinmax, cg, tdp;
1787 	char *s;
1788 
1789 	/* First check for error */
1790 	status = bf_get(lpfc_wcqe_c_status, wcqe);
1791 	if (status) {
1792 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1793 				"6211 CMF_SYNC_WQE Error "
1794 				"req_tag x%x status x%x hwstatus x%x "
1795 				"tdatap x%x parm x%x\n",
1796 				bf_get(lpfc_wcqe_c_request_tag, wcqe),
1797 				bf_get(lpfc_wcqe_c_status, wcqe),
1798 				bf_get(lpfc_wcqe_c_hw_status, wcqe),
1799 				wcqe->total_data_placed,
1800 				wcqe->parameter);
1801 		goto out;
1802 	}
1803 
1804 	/* Gather congestion information on a successful cmpl */
1805 	info = wcqe->parameter;
1806 	phba->cmf_active_info = info;
1807 
1808 	/* See if firmware info count is valid or has changed */
1809 	if (info > LPFC_MAX_CMF_INFO || phba->cmf_info_per_interval == info)
1810 		info = 0;
1811 	else
1812 		phba->cmf_info_per_interval = info;
1813 
1814 	tdp = bf_get(lpfc_wcqe_c_cmf_bw, wcqe);
1815 	cg = bf_get(lpfc_wcqe_c_cmf_cg, wcqe);
1816 
1817 	/* Get BW requirement from firmware */
1818 	bw = (uint64_t)tdp * LPFC_CMF_BLK_SIZE;
1819 	if (!bw) {
1820 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1821 				"6212 CMF_SYNC_WQE x%x: NULL bw\n",
1822 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
1823 		goto out;
1824 	}
1825 
1826 	/* Gather information needed for logging if a BW change is required */
1827 	wqe = &cmdiocb->wqe;
1828 	asig = bf_get(cmf_sync_asig, &wqe->cmf_sync);
1829 	afpin = bf_get(cmf_sync_afpin, &wqe->cmf_sync);
1830 	fpincnt = bf_get(cmf_sync_wfpincnt, &wqe->cmf_sync);
1831 	sigcnt = bf_get(cmf_sync_wsigcnt, &wqe->cmf_sync);
1832 	if (phba->cmf_max_bytes_per_interval != bw ||
1833 	    (asig || afpin || sigcnt || fpincnt)) {
1834 		/* Are we increasing or decreasing BW */
1835 		if (phba->cmf_max_bytes_per_interval <  bw) {
1836 			bwdif = bw - phba->cmf_max_bytes_per_interval;
1837 			s = "Increase";
1838 		} else {
1839 			bwdif = phba->cmf_max_bytes_per_interval - bw;
1840 			s = "Decrease";
1841 		}
1842 
1843 		/* What is the change percentage */
1844 		slop = div_u64(phba->cmf_link_byte_count, 200); /*For rounding*/
1845 		pcent = div64_u64(bwdif * 100 + slop,
1846 				  phba->cmf_link_byte_count);
1847 		bwpcent = div64_u64(bw * 100 + slop,
1848 				    phba->cmf_link_byte_count);
1849 		/* Because of bytes adjustment due to shorter timer in
1850 		 * lpfc_cmf_timer() the cmf_link_byte_count can be shorter and
1851 		 * may seem like BW is above 100%.
1852 		 */
1853 		if (bwpcent > 100)
1854 			bwpcent = 100;
1855 
1856 		if (phba->cmf_max_bytes_per_interval < bw &&
1857 		    bwpcent > 95)
1858 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1859 					"6208 Congestion bandwidth "
1860 					"limits removed\n");
1861 		else if ((phba->cmf_max_bytes_per_interval > bw) &&
1862 			 ((bwpcent + pcent) <= 100) && ((bwpcent + pcent) > 95))
1863 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1864 					"6209 Congestion bandwidth "
1865 					"limits in effect\n");
1866 
1867 		if (asig) {
1868 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1869 					"6237 BW Threshold %lld%% (%lld): "
1870 					"%lld%% %s: Signal Alarm: cg:%d "
1871 					"Info:%u\n",
1872 					bwpcent, bw, pcent, s, cg,
1873 					phba->cmf_active_info);
1874 		} else if (afpin) {
1875 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1876 					"6238 BW Threshold %lld%% (%lld): "
1877 					"%lld%% %s: FPIN Alarm: cg:%d "
1878 					"Info:%u\n",
1879 					bwpcent, bw, pcent, s, cg,
1880 					phba->cmf_active_info);
1881 		} else if (sigcnt) {
1882 			wsigmax = bf_get(cmf_sync_wsigmax, &wqe->cmf_sync);
1883 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1884 					"6239 BW Threshold %lld%% (%lld): "
1885 					"%lld%% %s: Signal Warning: "
1886 					"Cnt %d Max %d: cg:%d Info:%u\n",
1887 					bwpcent, bw, pcent, s, sigcnt,
1888 					wsigmax, cg, phba->cmf_active_info);
1889 		} else if (fpincnt) {
1890 			wfpinmax = bf_get(cmf_sync_wfpinmax, &wqe->cmf_sync);
1891 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1892 					"6240 BW Threshold %lld%% (%lld): "
1893 					"%lld%% %s: FPIN Warning: "
1894 					"Cnt %d Max %d: cg:%d Info:%u\n",
1895 					bwpcent, bw, pcent, s, fpincnt,
1896 					wfpinmax, cg, phba->cmf_active_info);
1897 		} else {
1898 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1899 					"6241 BW Threshold %lld%% (%lld): "
1900 					"CMF %lld%% %s: cg:%d Info:%u\n",
1901 					bwpcent, bw, pcent, s, cg,
1902 					phba->cmf_active_info);
1903 		}
1904 	} else if (info) {
1905 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1906 				"6246 Info Threshold %u\n", info);
1907 	}
1908 
1909 	/* Save BW change to be picked up during next timer interrupt */
1910 	phba->cmf_last_sync_bw = bw;
1911 out:
1912 	lpfc_sli_release_iocbq(phba, cmdiocb);
1913 }
1914 
1915 /**
1916  * lpfc_issue_cmf_sync_wqe - Issue a CMF_SYNC_WQE
1917  * @phba: Pointer to HBA context object.
1918  * @ms:   ms to set in WQE interval, 0 means use init op
1919  * @total: Total rcv bytes for this interval
1920  *
1921  * This routine is called every CMF timer interrupt. Its purpose is
1922  * to issue a CMF_SYNC_WQE to the firmware to inform it of any events
1923  * that may indicate we have congestion (FPINs or Signals). Upon
1924  * completion, the firmware will indicate any BW restrictions the
1925  * driver may need to take.
1926  **/
1927 int
1928 lpfc_issue_cmf_sync_wqe(struct lpfc_hba *phba, u32 ms, u64 total)
1929 {
1930 	union lpfc_wqe128 *wqe;
1931 	struct lpfc_iocbq *sync_buf;
1932 	unsigned long iflags;
1933 	u32 ret_val, cgn_sig_freq;
1934 	u32 atot, wtot, max;
1935 	u8 warn_sync_period = 0;
1936 
1937 	/* First address any alarm / warning activity */
1938 	atot = atomic_xchg(&phba->cgn_sync_alarm_cnt, 0);
1939 	wtot = atomic_xchg(&phba->cgn_sync_warn_cnt, 0);
1940 
1941 	spin_lock_irqsave(&phba->hbalock, iflags);
1942 
1943 	/* ONLY Managed mode will send the CMF_SYNC_WQE to the HBA */
1944 	if (phba->cmf_active_mode != LPFC_CFG_MANAGED ||
1945 	    phba->link_state < LPFC_LINK_UP) {
1946 		ret_val = 0;
1947 		goto out_unlock;
1948 	}
1949 
1950 	sync_buf = __lpfc_sli_get_iocbq(phba);
1951 	if (!sync_buf) {
1952 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
1953 				"6244 No available WQEs for CMF_SYNC_WQE\n");
1954 		ret_val = ENOMEM;
1955 		goto out_unlock;
1956 	}
1957 
1958 	wqe = &sync_buf->wqe;
1959 
1960 	/* WQEs are reused.  Clear stale data and set key fields to zero */
1961 	memset(wqe, 0, sizeof(*wqe));
1962 
1963 	/* If this is the very first CMF_SYNC_WQE, issue an init operation */
1964 	if (!ms) {
1965 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1966 				"6441 CMF Init %d - CMF_SYNC_WQE\n",
1967 				phba->fc_eventTag);
1968 		bf_set(cmf_sync_op, &wqe->cmf_sync, 1); /* 1=init */
1969 		bf_set(cmf_sync_interval, &wqe->cmf_sync, LPFC_CMF_INTERVAL);
1970 		goto initpath;
1971 	}
1972 
1973 	bf_set(cmf_sync_op, &wqe->cmf_sync, 0); /* 0=recalc */
1974 	bf_set(cmf_sync_interval, &wqe->cmf_sync, ms);
1975 
1976 	/* Check for alarms / warnings */
1977 	if (atot) {
1978 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1979 			/* We hit an Signal alarm condition */
1980 			bf_set(cmf_sync_asig, &wqe->cmf_sync, 1);
1981 		} else {
1982 			/* We hit a FPIN alarm condition */
1983 			bf_set(cmf_sync_afpin, &wqe->cmf_sync, 1);
1984 		}
1985 	} else if (wtot) {
1986 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
1987 		    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1988 			cgn_sig_freq = phba->cgn_sig_freq ? phba->cgn_sig_freq :
1989 					lpfc_fabric_cgn_frequency;
1990 			/* We hit an Signal warning condition */
1991 			max = LPFC_SEC_TO_MSEC / cgn_sig_freq *
1992 				lpfc_acqe_cgn_frequency;
1993 			bf_set(cmf_sync_wsigmax, &wqe->cmf_sync, max);
1994 			bf_set(cmf_sync_wsigcnt, &wqe->cmf_sync, wtot);
1995 			warn_sync_period = lpfc_acqe_cgn_frequency;
1996 		} else {
1997 			/* We hit a FPIN warning condition */
1998 			bf_set(cmf_sync_wfpinmax, &wqe->cmf_sync, 1);
1999 			bf_set(cmf_sync_wfpincnt, &wqe->cmf_sync, 1);
2000 			if (phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ)
2001 				warn_sync_period =
2002 				LPFC_MSECS_TO_SECS(phba->cgn_fpin_frequency);
2003 		}
2004 	}
2005 
2006 	/* Update total read blocks during previous timer interval */
2007 	wqe->cmf_sync.read_bytes = (u32)(total / LPFC_CMF_BLK_SIZE);
2008 
2009 initpath:
2010 	bf_set(cmf_sync_ver, &wqe->cmf_sync, LPFC_CMF_SYNC_VER);
2011 	wqe->cmf_sync.event_tag = phba->fc_eventTag;
2012 	bf_set(cmf_sync_cmnd, &wqe->cmf_sync, CMD_CMF_SYNC_WQE);
2013 
2014 	/* Setup reqtag to match the wqe completion. */
2015 	bf_set(cmf_sync_reqtag, &wqe->cmf_sync, sync_buf->iotag);
2016 
2017 	bf_set(cmf_sync_qosd, &wqe->cmf_sync, 1);
2018 	bf_set(cmf_sync_period, &wqe->cmf_sync, warn_sync_period);
2019 
2020 	bf_set(cmf_sync_cmd_type, &wqe->cmf_sync, CMF_SYNC_COMMAND);
2021 	bf_set(cmf_sync_wqec, &wqe->cmf_sync, 1);
2022 	bf_set(cmf_sync_cqid, &wqe->cmf_sync, LPFC_WQE_CQ_ID_DEFAULT);
2023 
2024 	sync_buf->vport = phba->pport;
2025 	sync_buf->cmd_cmpl = lpfc_cmf_sync_cmpl;
2026 	sync_buf->cmd_dmabuf = NULL;
2027 	sync_buf->rsp_dmabuf = NULL;
2028 	sync_buf->bpl_dmabuf = NULL;
2029 	sync_buf->sli4_xritag = NO_XRI;
2030 
2031 	sync_buf->cmd_flag |= LPFC_IO_CMF;
2032 	ret_val = lpfc_sli4_issue_wqe(phba, &phba->sli4_hba.hdwq[0], sync_buf);
2033 	if (ret_val) {
2034 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
2035 				"6214 Cannot issue CMF_SYNC_WQE: x%x\n",
2036 				ret_val);
2037 		__lpfc_sli_release_iocbq(phba, sync_buf);
2038 	}
2039 out_unlock:
2040 	spin_unlock_irqrestore(&phba->hbalock, iflags);
2041 	return ret_val;
2042 }
2043 
2044 /**
2045  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
2046  * @phba: Pointer to HBA context object.
2047  * @pring: Pointer to driver SLI ring object.
2048  *
2049  * This function is called with hbalock held and the caller must post the
2050  * iocb without releasing the lock. If the caller releases the lock,
2051  * iocb slot returned by the function is not guaranteed to be available.
2052  * The function returns pointer to the next available iocb slot if there
2053  * is available slot in the ring, else it returns NULL.
2054  * If the get index of the ring is ahead of the put index, the function
2055  * will post an error attention event to the worker thread to take the
2056  * HBA to offline state.
2057  **/
2058 static IOCB_t *
2059 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2060 {
2061 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2062 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
2063 
2064 	lockdep_assert_held(&phba->hbalock);
2065 
2066 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
2067 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
2068 		pring->sli.sli3.next_cmdidx = 0;
2069 
2070 	if (unlikely(pring->sli.sli3.local_getidx ==
2071 		pring->sli.sli3.next_cmdidx)) {
2072 
2073 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
2074 
2075 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
2076 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2077 					"0315 Ring %d issue: portCmdGet %d "
2078 					"is bigger than cmd ring %d\n",
2079 					pring->ringno,
2080 					pring->sli.sli3.local_getidx,
2081 					max_cmd_idx);
2082 
2083 			phba->link_state = LPFC_HBA_ERROR;
2084 			/*
2085 			 * All error attention handlers are posted to
2086 			 * worker thread
2087 			 */
2088 			phba->work_ha |= HA_ERATT;
2089 			phba->work_hs = HS_FFER3;
2090 
2091 			lpfc_worker_wake_up(phba);
2092 
2093 			return NULL;
2094 		}
2095 
2096 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
2097 			return NULL;
2098 	}
2099 
2100 	return lpfc_cmd_iocb(phba, pring);
2101 }
2102 
2103 /**
2104  * lpfc_sli_next_iotag - Get an iotag for the iocb
2105  * @phba: Pointer to HBA context object.
2106  * @iocbq: Pointer to driver iocb object.
2107  *
2108  * This function gets an iotag for the iocb. If there is no unused iotag and
2109  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
2110  * array and assigns a new iotag.
2111  * The function returns the allocated iotag if successful, else returns zero.
2112  * Zero is not a valid iotag.
2113  * The caller is not required to hold any lock.
2114  **/
2115 uint16_t
2116 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
2117 {
2118 	struct lpfc_iocbq **new_arr;
2119 	struct lpfc_iocbq **old_arr;
2120 	size_t new_len;
2121 	struct lpfc_sli *psli = &phba->sli;
2122 	uint16_t iotag;
2123 
2124 	spin_lock_irq(&phba->hbalock);
2125 	iotag = psli->last_iotag;
2126 	if(++iotag < psli->iocbq_lookup_len) {
2127 		psli->last_iotag = iotag;
2128 		psli->iocbq_lookup[iotag] = iocbq;
2129 		spin_unlock_irq(&phba->hbalock);
2130 		iocbq->iotag = iotag;
2131 		return iotag;
2132 	} else if (psli->iocbq_lookup_len < (0xffff
2133 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
2134 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
2135 		spin_unlock_irq(&phba->hbalock);
2136 		new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
2137 				  GFP_KERNEL);
2138 		if (new_arr) {
2139 			spin_lock_irq(&phba->hbalock);
2140 			old_arr = psli->iocbq_lookup;
2141 			if (new_len <= psli->iocbq_lookup_len) {
2142 				/* highly unprobable case */
2143 				kfree(new_arr);
2144 				iotag = psli->last_iotag;
2145 				if(++iotag < psli->iocbq_lookup_len) {
2146 					psli->last_iotag = iotag;
2147 					psli->iocbq_lookup[iotag] = iocbq;
2148 					spin_unlock_irq(&phba->hbalock);
2149 					iocbq->iotag = iotag;
2150 					return iotag;
2151 				}
2152 				spin_unlock_irq(&phba->hbalock);
2153 				return 0;
2154 			}
2155 			if (psli->iocbq_lookup)
2156 				memcpy(new_arr, old_arr,
2157 				       ((psli->last_iotag  + 1) *
2158 					sizeof (struct lpfc_iocbq *)));
2159 			psli->iocbq_lookup = new_arr;
2160 			psli->iocbq_lookup_len = new_len;
2161 			psli->last_iotag = iotag;
2162 			psli->iocbq_lookup[iotag] = iocbq;
2163 			spin_unlock_irq(&phba->hbalock);
2164 			iocbq->iotag = iotag;
2165 			kfree(old_arr);
2166 			return iotag;
2167 		}
2168 	} else
2169 		spin_unlock_irq(&phba->hbalock);
2170 
2171 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2172 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
2173 			psli->last_iotag);
2174 
2175 	return 0;
2176 }
2177 
2178 /**
2179  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
2180  * @phba: Pointer to HBA context object.
2181  * @pring: Pointer to driver SLI ring object.
2182  * @iocb: Pointer to iocb slot in the ring.
2183  * @nextiocb: Pointer to driver iocb object which need to be
2184  *            posted to firmware.
2185  *
2186  * This function is called to post a new iocb to the firmware. This
2187  * function copies the new iocb to ring iocb slot and updates the
2188  * ring pointers. It adds the new iocb to txcmplq if there is
2189  * a completion call back for this iocb else the function will free the
2190  * iocb object.  The hbalock is asserted held in the code path calling
2191  * this routine.
2192  **/
2193 static void
2194 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2195 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
2196 {
2197 	/*
2198 	 * Set up an iotag
2199 	 */
2200 	nextiocb->iocb.ulpIoTag = (nextiocb->cmd_cmpl) ? nextiocb->iotag : 0;
2201 
2202 
2203 	if (pring->ringno == LPFC_ELS_RING) {
2204 		lpfc_debugfs_slow_ring_trc(phba,
2205 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
2206 			*(((uint32_t *) &nextiocb->iocb) + 4),
2207 			*(((uint32_t *) &nextiocb->iocb) + 6),
2208 			*(((uint32_t *) &nextiocb->iocb) + 7));
2209 	}
2210 
2211 	/*
2212 	 * Issue iocb command to adapter
2213 	 */
2214 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
2215 	wmb();
2216 	pring->stats.iocb_cmd++;
2217 
2218 	/*
2219 	 * If there is no completion routine to call, we can release the
2220 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
2221 	 * that have no rsp ring completion, cmd_cmpl MUST be NULL.
2222 	 */
2223 	if (nextiocb->cmd_cmpl)
2224 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
2225 	else
2226 		__lpfc_sli_release_iocbq(phba, nextiocb);
2227 
2228 	/*
2229 	 * Let the HBA know what IOCB slot will be the next one the
2230 	 * driver will put a command into.
2231 	 */
2232 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
2233 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
2234 }
2235 
2236 /**
2237  * lpfc_sli_update_full_ring - Update the chip attention register
2238  * @phba: Pointer to HBA context object.
2239  * @pring: Pointer to driver SLI ring object.
2240  *
2241  * The caller is not required to hold any lock for calling this function.
2242  * This function updates the chip attention bits for the ring to inform firmware
2243  * that there are pending work to be done for this ring and requests an
2244  * interrupt when there is space available in the ring. This function is
2245  * called when the driver is unable to post more iocbs to the ring due
2246  * to unavailability of space in the ring.
2247  **/
2248 static void
2249 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2250 {
2251 	int ringno = pring->ringno;
2252 
2253 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
2254 
2255 	wmb();
2256 
2257 	/*
2258 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
2259 	 * The HBA will tell us when an IOCB entry is available.
2260 	 */
2261 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
2262 	readl(phba->CAregaddr); /* flush */
2263 
2264 	pring->stats.iocb_cmd_full++;
2265 }
2266 
2267 /**
2268  * lpfc_sli_update_ring - Update chip attention register
2269  * @phba: Pointer to HBA context object.
2270  * @pring: Pointer to driver SLI ring object.
2271  *
2272  * This function updates the chip attention register bit for the
2273  * given ring to inform HBA that there is more work to be done
2274  * in this ring. The caller is not required to hold any lock.
2275  **/
2276 static void
2277 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2278 {
2279 	int ringno = pring->ringno;
2280 
2281 	/*
2282 	 * Tell the HBA that there is work to do in this ring.
2283 	 */
2284 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
2285 		wmb();
2286 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
2287 		readl(phba->CAregaddr); /* flush */
2288 	}
2289 }
2290 
2291 /**
2292  * lpfc_sli_resume_iocb - Process iocbs in the txq
2293  * @phba: Pointer to HBA context object.
2294  * @pring: Pointer to driver SLI ring object.
2295  *
2296  * This function is called with hbalock held to post pending iocbs
2297  * in the txq to the firmware. This function is called when driver
2298  * detects space available in the ring.
2299  **/
2300 static void
2301 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2302 {
2303 	IOCB_t *iocb;
2304 	struct lpfc_iocbq *nextiocb;
2305 
2306 	lockdep_assert_held(&phba->hbalock);
2307 
2308 	/*
2309 	 * Check to see if:
2310 	 *  (a) there is anything on the txq to send
2311 	 *  (b) link is up
2312 	 *  (c) link attention events can be processed (fcp ring only)
2313 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
2314 	 */
2315 
2316 	if (lpfc_is_link_up(phba) &&
2317 	    (!list_empty(&pring->txq)) &&
2318 	    (pring->ringno != LPFC_FCP_RING ||
2319 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
2320 
2321 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
2322 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
2323 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
2324 
2325 		if (iocb)
2326 			lpfc_sli_update_ring(phba, pring);
2327 		else
2328 			lpfc_sli_update_full_ring(phba, pring);
2329 	}
2330 
2331 	return;
2332 }
2333 
2334 /**
2335  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
2336  * @phba: Pointer to HBA context object.
2337  * @hbqno: HBQ number.
2338  *
2339  * This function is called with hbalock held to get the next
2340  * available slot for the given HBQ. If there is free slot
2341  * available for the HBQ it will return pointer to the next available
2342  * HBQ entry else it will return NULL.
2343  **/
2344 static struct lpfc_hbq_entry *
2345 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
2346 {
2347 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
2348 
2349 	lockdep_assert_held(&phba->hbalock);
2350 
2351 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
2352 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
2353 		hbqp->next_hbqPutIdx = 0;
2354 
2355 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
2356 		uint32_t raw_index = phba->hbq_get[hbqno];
2357 		uint32_t getidx = le32_to_cpu(raw_index);
2358 
2359 		hbqp->local_hbqGetIdx = getidx;
2360 
2361 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
2362 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2363 					"1802 HBQ %d: local_hbqGetIdx "
2364 					"%u is > than hbqp->entry_count %u\n",
2365 					hbqno, hbqp->local_hbqGetIdx,
2366 					hbqp->entry_count);
2367 
2368 			phba->link_state = LPFC_HBA_ERROR;
2369 			return NULL;
2370 		}
2371 
2372 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
2373 			return NULL;
2374 	}
2375 
2376 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
2377 			hbqp->hbqPutIdx;
2378 }
2379 
2380 /**
2381  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
2382  * @phba: Pointer to HBA context object.
2383  *
2384  * This function is called with no lock held to free all the
2385  * hbq buffers while uninitializing the SLI interface. It also
2386  * frees the HBQ buffers returned by the firmware but not yet
2387  * processed by the upper layers.
2388  **/
2389 void
2390 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
2391 {
2392 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
2393 	struct hbq_dmabuf *hbq_buf;
2394 	unsigned long flags;
2395 	int i, hbq_count;
2396 
2397 	hbq_count = lpfc_sli_hbq_count();
2398 	/* Return all memory used by all HBQs */
2399 	spin_lock_irqsave(&phba->hbalock, flags);
2400 	for (i = 0; i < hbq_count; ++i) {
2401 		list_for_each_entry_safe(dmabuf, next_dmabuf,
2402 				&phba->hbqs[i].hbq_buffer_list, list) {
2403 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2404 			list_del(&hbq_buf->dbuf.list);
2405 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2406 		}
2407 		phba->hbqs[i].buffer_count = 0;
2408 	}
2409 
2410 	/* Mark the HBQs not in use */
2411 	phba->hbq_in_use = 0;
2412 	spin_unlock_irqrestore(&phba->hbalock, flags);
2413 }
2414 
2415 /**
2416  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2417  * @phba: Pointer to HBA context object.
2418  * @hbqno: HBQ number.
2419  * @hbq_buf: Pointer to HBQ buffer.
2420  *
2421  * This function is called with the hbalock held to post a
2422  * hbq buffer to the firmware. If the function finds an empty
2423  * slot in the HBQ, it will post the buffer. The function will return
2424  * pointer to the hbq entry if it successfully post the buffer
2425  * else it will return NULL.
2426  **/
2427 static int
2428 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2429 			 struct hbq_dmabuf *hbq_buf)
2430 {
2431 	lockdep_assert_held(&phba->hbalock);
2432 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2433 }
2434 
2435 /**
2436  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2437  * @phba: Pointer to HBA context object.
2438  * @hbqno: HBQ number.
2439  * @hbq_buf: Pointer to HBQ buffer.
2440  *
2441  * This function is called with the hbalock held to post a hbq buffer to the
2442  * firmware. If the function finds an empty slot in the HBQ, it will post the
2443  * buffer and place it on the hbq_buffer_list. The function will return zero if
2444  * it successfully post the buffer else it will return an error.
2445  **/
2446 static int
2447 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2448 			    struct hbq_dmabuf *hbq_buf)
2449 {
2450 	struct lpfc_hbq_entry *hbqe;
2451 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
2452 
2453 	lockdep_assert_held(&phba->hbalock);
2454 	/* Get next HBQ entry slot to use */
2455 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2456 	if (hbqe) {
2457 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
2458 
2459 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2460 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2461 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2462 		hbqe->bde.tus.f.bdeFlags = 0;
2463 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2464 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2465 				/* Sync SLIM */
2466 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2467 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2468 				/* flush */
2469 		readl(phba->hbq_put + hbqno);
2470 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2471 		return 0;
2472 	} else
2473 		return -ENOMEM;
2474 }
2475 
2476 /**
2477  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2478  * @phba: Pointer to HBA context object.
2479  * @hbqno: HBQ number.
2480  * @hbq_buf: Pointer to HBQ buffer.
2481  *
2482  * This function is called with the hbalock held to post an RQE to the SLI4
2483  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2484  * the hbq_buffer_list and return zero, otherwise it will return an error.
2485  **/
2486 static int
2487 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2488 			    struct hbq_dmabuf *hbq_buf)
2489 {
2490 	int rc;
2491 	struct lpfc_rqe hrqe;
2492 	struct lpfc_rqe drqe;
2493 	struct lpfc_queue *hrq;
2494 	struct lpfc_queue *drq;
2495 
2496 	if (hbqno != LPFC_ELS_HBQ)
2497 		return 1;
2498 	hrq = phba->sli4_hba.hdr_rq;
2499 	drq = phba->sli4_hba.dat_rq;
2500 
2501 	lockdep_assert_held(&phba->hbalock);
2502 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2503 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2504 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2505 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2506 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2507 	if (rc < 0)
2508 		return rc;
2509 	hbq_buf->tag = (rc | (hbqno << 16));
2510 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2511 	return 0;
2512 }
2513 
2514 /* HBQ for ELS and CT traffic. */
2515 static struct lpfc_hbq_init lpfc_els_hbq = {
2516 	.rn = 1,
2517 	.entry_count = 256,
2518 	.mask_count = 0,
2519 	.profile = 0,
2520 	.ring_mask = (1 << LPFC_ELS_RING),
2521 	.buffer_count = 0,
2522 	.init_count = 40,
2523 	.add_count = 40,
2524 };
2525 
2526 /* Array of HBQs */
2527 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2528 	&lpfc_els_hbq,
2529 };
2530 
2531 /**
2532  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2533  * @phba: Pointer to HBA context object.
2534  * @hbqno: HBQ number.
2535  * @count: Number of HBQ buffers to be posted.
2536  *
2537  * This function is called with no lock held to post more hbq buffers to the
2538  * given HBQ. The function returns the number of HBQ buffers successfully
2539  * posted.
2540  **/
2541 static int
2542 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2543 {
2544 	uint32_t i, posted = 0;
2545 	unsigned long flags;
2546 	struct hbq_dmabuf *hbq_buffer;
2547 	LIST_HEAD(hbq_buf_list);
2548 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2549 		return 0;
2550 
2551 	if ((phba->hbqs[hbqno].buffer_count + count) >
2552 	    lpfc_hbq_defs[hbqno]->entry_count)
2553 		count = lpfc_hbq_defs[hbqno]->entry_count -
2554 					phba->hbqs[hbqno].buffer_count;
2555 	if (!count)
2556 		return 0;
2557 	/* Allocate HBQ entries */
2558 	for (i = 0; i < count; i++) {
2559 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2560 		if (!hbq_buffer)
2561 			break;
2562 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2563 	}
2564 	/* Check whether HBQ is still in use */
2565 	spin_lock_irqsave(&phba->hbalock, flags);
2566 	if (!phba->hbq_in_use)
2567 		goto err;
2568 	while (!list_empty(&hbq_buf_list)) {
2569 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2570 				 dbuf.list);
2571 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2572 				      (hbqno << 16));
2573 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2574 			phba->hbqs[hbqno].buffer_count++;
2575 			posted++;
2576 		} else
2577 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2578 	}
2579 	spin_unlock_irqrestore(&phba->hbalock, flags);
2580 	return posted;
2581 err:
2582 	spin_unlock_irqrestore(&phba->hbalock, flags);
2583 	while (!list_empty(&hbq_buf_list)) {
2584 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2585 				 dbuf.list);
2586 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2587 	}
2588 	return 0;
2589 }
2590 
2591 /**
2592  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2593  * @phba: Pointer to HBA context object.
2594  * @qno: HBQ number.
2595  *
2596  * This function posts more buffers to the HBQ. This function
2597  * is called with no lock held. The function returns the number of HBQ entries
2598  * successfully allocated.
2599  **/
2600 int
2601 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2602 {
2603 	if (phba->sli_rev == LPFC_SLI_REV4)
2604 		return 0;
2605 	else
2606 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2607 					 lpfc_hbq_defs[qno]->add_count);
2608 }
2609 
2610 /**
2611  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2612  * @phba: Pointer to HBA context object.
2613  * @qno:  HBQ queue number.
2614  *
2615  * This function is called from SLI initialization code path with
2616  * no lock held to post initial HBQ buffers to firmware. The
2617  * function returns the number of HBQ entries successfully allocated.
2618  **/
2619 static int
2620 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2621 {
2622 	if (phba->sli_rev == LPFC_SLI_REV4)
2623 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2624 					lpfc_hbq_defs[qno]->entry_count);
2625 	else
2626 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2627 					 lpfc_hbq_defs[qno]->init_count);
2628 }
2629 
2630 /*
2631  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2632  *
2633  * This function removes the first hbq buffer on an hbq list and returns a
2634  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2635  **/
2636 static struct hbq_dmabuf *
2637 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2638 {
2639 	struct lpfc_dmabuf *d_buf;
2640 
2641 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2642 	if (!d_buf)
2643 		return NULL;
2644 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2645 }
2646 
2647 /**
2648  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2649  * @phba: Pointer to HBA context object.
2650  * @hrq: HBQ number.
2651  *
2652  * This function removes the first RQ buffer on an RQ buffer list and returns a
2653  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2654  **/
2655 static struct rqb_dmabuf *
2656 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2657 {
2658 	struct lpfc_dmabuf *h_buf;
2659 	struct lpfc_rqb *rqbp;
2660 
2661 	rqbp = hrq->rqbp;
2662 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2663 			 struct lpfc_dmabuf, list);
2664 	if (!h_buf)
2665 		return NULL;
2666 	rqbp->buffer_count--;
2667 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2668 }
2669 
2670 /**
2671  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2672  * @phba: Pointer to HBA context object.
2673  * @tag: Tag of the hbq buffer.
2674  *
2675  * This function searches for the hbq buffer associated with the given tag in
2676  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2677  * otherwise it returns NULL.
2678  **/
2679 static struct hbq_dmabuf *
2680 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2681 {
2682 	struct lpfc_dmabuf *d_buf;
2683 	struct hbq_dmabuf *hbq_buf;
2684 	uint32_t hbqno;
2685 
2686 	hbqno = tag >> 16;
2687 	if (hbqno >= LPFC_MAX_HBQS)
2688 		return NULL;
2689 
2690 	spin_lock_irq(&phba->hbalock);
2691 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2692 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2693 		if (hbq_buf->tag == tag) {
2694 			spin_unlock_irq(&phba->hbalock);
2695 			return hbq_buf;
2696 		}
2697 	}
2698 	spin_unlock_irq(&phba->hbalock);
2699 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2700 			"1803 Bad hbq tag. Data: x%x x%x\n",
2701 			tag, phba->hbqs[tag >> 16].buffer_count);
2702 	return NULL;
2703 }
2704 
2705 /**
2706  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2707  * @phba: Pointer to HBA context object.
2708  * @hbq_buffer: Pointer to HBQ buffer.
2709  *
2710  * This function is called with hbalock. This function gives back
2711  * the hbq buffer to firmware. If the HBQ does not have space to
2712  * post the buffer, it will free the buffer.
2713  **/
2714 void
2715 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2716 {
2717 	uint32_t hbqno;
2718 
2719 	if (hbq_buffer) {
2720 		hbqno = hbq_buffer->tag >> 16;
2721 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2722 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2723 	}
2724 }
2725 
2726 /**
2727  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2728  * @mbxCommand: mailbox command code.
2729  *
2730  * This function is called by the mailbox event handler function to verify
2731  * that the completed mailbox command is a legitimate mailbox command. If the
2732  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2733  * and the mailbox event handler will take the HBA offline.
2734  **/
2735 static int
2736 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2737 {
2738 	uint8_t ret;
2739 
2740 	switch (mbxCommand) {
2741 	case MBX_LOAD_SM:
2742 	case MBX_READ_NV:
2743 	case MBX_WRITE_NV:
2744 	case MBX_WRITE_VPARMS:
2745 	case MBX_RUN_BIU_DIAG:
2746 	case MBX_INIT_LINK:
2747 	case MBX_DOWN_LINK:
2748 	case MBX_CONFIG_LINK:
2749 	case MBX_CONFIG_RING:
2750 	case MBX_RESET_RING:
2751 	case MBX_READ_CONFIG:
2752 	case MBX_READ_RCONFIG:
2753 	case MBX_READ_SPARM:
2754 	case MBX_READ_STATUS:
2755 	case MBX_READ_RPI:
2756 	case MBX_READ_XRI:
2757 	case MBX_READ_REV:
2758 	case MBX_READ_LNK_STAT:
2759 	case MBX_REG_LOGIN:
2760 	case MBX_UNREG_LOGIN:
2761 	case MBX_CLEAR_LA:
2762 	case MBX_DUMP_MEMORY:
2763 	case MBX_DUMP_CONTEXT:
2764 	case MBX_RUN_DIAGS:
2765 	case MBX_RESTART:
2766 	case MBX_UPDATE_CFG:
2767 	case MBX_DOWN_LOAD:
2768 	case MBX_DEL_LD_ENTRY:
2769 	case MBX_RUN_PROGRAM:
2770 	case MBX_SET_MASK:
2771 	case MBX_SET_VARIABLE:
2772 	case MBX_UNREG_D_ID:
2773 	case MBX_KILL_BOARD:
2774 	case MBX_CONFIG_FARP:
2775 	case MBX_BEACON:
2776 	case MBX_LOAD_AREA:
2777 	case MBX_RUN_BIU_DIAG64:
2778 	case MBX_CONFIG_PORT:
2779 	case MBX_READ_SPARM64:
2780 	case MBX_READ_RPI64:
2781 	case MBX_REG_LOGIN64:
2782 	case MBX_READ_TOPOLOGY:
2783 	case MBX_WRITE_WWN:
2784 	case MBX_SET_DEBUG:
2785 	case MBX_LOAD_EXP_ROM:
2786 	case MBX_ASYNCEVT_ENABLE:
2787 	case MBX_REG_VPI:
2788 	case MBX_UNREG_VPI:
2789 	case MBX_HEARTBEAT:
2790 	case MBX_PORT_CAPABILITIES:
2791 	case MBX_PORT_IOV_CONTROL:
2792 	case MBX_SLI4_CONFIG:
2793 	case MBX_SLI4_REQ_FTRS:
2794 	case MBX_REG_FCFI:
2795 	case MBX_UNREG_FCFI:
2796 	case MBX_REG_VFI:
2797 	case MBX_UNREG_VFI:
2798 	case MBX_INIT_VPI:
2799 	case MBX_INIT_VFI:
2800 	case MBX_RESUME_RPI:
2801 	case MBX_READ_EVENT_LOG_STATUS:
2802 	case MBX_READ_EVENT_LOG:
2803 	case MBX_SECURITY_MGMT:
2804 	case MBX_AUTH_PORT:
2805 	case MBX_ACCESS_VDATA:
2806 		ret = mbxCommand;
2807 		break;
2808 	default:
2809 		ret = MBX_SHUTDOWN;
2810 		break;
2811 	}
2812 	return ret;
2813 }
2814 
2815 /**
2816  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2817  * @phba: Pointer to HBA context object.
2818  * @pmboxq: Pointer to mailbox command.
2819  *
2820  * This is completion handler function for mailbox commands issued from
2821  * lpfc_sli_issue_mbox_wait function. This function is called by the
2822  * mailbox event handler function with no lock held. This function
2823  * will wake up thread waiting on the wait queue pointed by context1
2824  * of the mailbox.
2825  **/
2826 void
2827 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2828 {
2829 	unsigned long drvr_flag;
2830 	struct completion *pmbox_done;
2831 
2832 	/*
2833 	 * If pmbox_done is empty, the driver thread gave up waiting and
2834 	 * continued running.
2835 	 */
2836 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2837 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2838 	pmbox_done = pmboxq->ctx_u.mbox_wait;
2839 	if (pmbox_done)
2840 		complete(pmbox_done);
2841 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2842 	return;
2843 }
2844 
2845 /**
2846  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2847  * @phba: Pointer to HBA context object.
2848  * @pmb: Pointer to mailbox object.
2849  *
2850  * This function is the default mailbox completion handler. It
2851  * frees the memory resources associated with the completed mailbox
2852  * command. If the completed command is a REG_LOGIN mailbox command,
2853  * this function will issue a UREG_LOGIN to re-claim the RPI.
2854  **/
2855 void
2856 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2857 {
2858 	struct lpfc_vport  *vport = pmb->vport;
2859 	struct lpfc_dmabuf *mp;
2860 	struct lpfc_nodelist *ndlp;
2861 	struct Scsi_Host *shost;
2862 	uint16_t rpi, vpi;
2863 	int rc;
2864 
2865 	/*
2866 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2867 	 * is in re-discovery driver need to cleanup the RPI.
2868 	 */
2869 	if (!test_bit(FC_UNLOADING, &phba->pport->load_flag) &&
2870 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2871 	    !pmb->u.mb.mbxStatus) {
2872 		mp = pmb->ctx_buf;
2873 		if (mp) {
2874 			pmb->ctx_buf = NULL;
2875 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
2876 			kfree(mp);
2877 		}
2878 		rpi = pmb->u.mb.un.varWords[0];
2879 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2880 		if (phba->sli_rev == LPFC_SLI_REV4)
2881 			vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2882 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2883 		pmb->vport = vport;
2884 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2885 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2886 		if (rc != MBX_NOT_FINISHED)
2887 			return;
2888 	}
2889 
2890 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2891 		!test_bit(FC_UNLOADING, &phba->pport->load_flag) &&
2892 		!pmb->u.mb.mbxStatus) {
2893 		shost = lpfc_shost_from_vport(vport);
2894 		spin_lock_irq(shost->host_lock);
2895 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2896 		spin_unlock_irq(shost->host_lock);
2897 		clear_bit(FC_VPORT_NEEDS_REG_VPI, &vport->fc_flag);
2898 	}
2899 
2900 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2901 		ndlp = pmb->ctx_ndlp;
2902 		lpfc_nlp_put(ndlp);
2903 	}
2904 
2905 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2906 		ndlp = pmb->ctx_ndlp;
2907 
2908 		/* Check to see if there are any deferred events to process */
2909 		if (ndlp) {
2910 			lpfc_printf_vlog(
2911 				vport,
2912 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2913 				"1438 UNREG cmpl deferred mbox x%x "
2914 				"on NPort x%x Data: x%lx x%x x%px x%lx x%x\n",
2915 				ndlp->nlp_rpi, ndlp->nlp_DID,
2916 				ndlp->nlp_flag, ndlp->nlp_defer_did,
2917 				ndlp, vport->load_flag, kref_read(&ndlp->kref));
2918 
2919 			if (test_bit(NLP_UNREG_INP, &ndlp->nlp_flag) &&
2920 			    ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING) {
2921 				clear_bit(NLP_UNREG_INP, &ndlp->nlp_flag);
2922 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2923 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2924 			} else {
2925 				clear_bit(NLP_UNREG_INP, &ndlp->nlp_flag);
2926 			}
2927 
2928 			/* The unreg_login mailbox is complete and had a
2929 			 * reference that has to be released.  The PLOGI
2930 			 * got its own ref.
2931 			 */
2932 			lpfc_nlp_put(ndlp);
2933 			pmb->ctx_ndlp = NULL;
2934 		}
2935 	}
2936 
2937 	/* This nlp_put pairs with lpfc_sli4_resume_rpi */
2938 	if (pmb->u.mb.mbxCommand == MBX_RESUME_RPI) {
2939 		ndlp = pmb->ctx_ndlp;
2940 		lpfc_nlp_put(ndlp);
2941 	}
2942 
2943 	/* Check security permission status on INIT_LINK mailbox command */
2944 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2945 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2946 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2947 				"2860 SLI authentication is required "
2948 				"for INIT_LINK but has not done yet\n");
2949 
2950 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2951 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2952 	else
2953 		lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2954 }
2955  /**
2956  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2957  * @phba: Pointer to HBA context object.
2958  * @pmb: Pointer to mailbox object.
2959  *
2960  * This function is the unreg rpi mailbox completion handler. It
2961  * frees the memory resources associated with the completed mailbox
2962  * command. An additional reference is put on the ndlp to prevent
2963  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2964  * the unreg mailbox command completes, this routine puts the
2965  * reference back.
2966  *
2967  **/
2968 void
2969 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2970 {
2971 	struct lpfc_vport  *vport = pmb->vport;
2972 	struct lpfc_nodelist *ndlp;
2973 	bool unreg_inp;
2974 
2975 	ndlp = pmb->ctx_ndlp;
2976 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2977 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2978 		    (bf_get(lpfc_sli_intf_if_type,
2979 		     &phba->sli4_hba.sli_intf) >=
2980 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2981 			if (ndlp) {
2982 				lpfc_printf_vlog(
2983 					 vport, KERN_INFO,
2984 					 LOG_MBOX | LOG_SLI | LOG_NODE,
2985 					 "0010 UNREG_LOGIN vpi:x%x "
2986 					 "rpi:%x DID:%x defer x%x flg x%lx "
2987 					 "x%px\n",
2988 					 vport->vpi, ndlp->nlp_rpi,
2989 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
2990 					 ndlp->nlp_flag,
2991 					 ndlp);
2992 
2993 				/* Cleanup the nlp_flag now that the UNREG RPI
2994 				 * has completed.
2995 				 */
2996 				unreg_inp = test_and_clear_bit(NLP_UNREG_INP,
2997 							       &ndlp->nlp_flag);
2998 				clear_bit(NLP_LOGO_ACC, &ndlp->nlp_flag);
2999 
3000 				/* Check to see if there are any deferred
3001 				 * events to process
3002 				 */
3003 				if (unreg_inp &&
3004 				    ndlp->nlp_defer_did !=
3005 				    NLP_EVT_NOTHING_PENDING) {
3006 					lpfc_printf_vlog(
3007 						vport, KERN_INFO,
3008 						LOG_MBOX | LOG_SLI | LOG_NODE,
3009 						"4111 UNREG cmpl deferred "
3010 						"clr x%x on "
3011 						"NPort x%x Data: x%x x%px\n",
3012 						ndlp->nlp_rpi, ndlp->nlp_DID,
3013 						ndlp->nlp_defer_did, ndlp);
3014 					ndlp->nlp_defer_did =
3015 						NLP_EVT_NOTHING_PENDING;
3016 					lpfc_issue_els_plogi(
3017 						vport, ndlp->nlp_DID, 0);
3018 				}
3019 
3020 				lpfc_nlp_put(ndlp);
3021 			}
3022 		}
3023 	}
3024 
3025 	mempool_free(pmb, phba->mbox_mem_pool);
3026 }
3027 
3028 /**
3029  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
3030  * @phba: Pointer to HBA context object.
3031  *
3032  * This function is called with no lock held. This function processes all
3033  * the completed mailbox commands and gives it to upper layers. The interrupt
3034  * service routine processes mailbox completion interrupt and adds completed
3035  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
3036  * Worker thread call lpfc_sli_handle_mb_event, which will return the
3037  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
3038  * function returns the mailbox commands to the upper layer by calling the
3039  * completion handler function of each mailbox.
3040  **/
3041 int
3042 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
3043 {
3044 	MAILBOX_t *pmbox;
3045 	LPFC_MBOXQ_t *pmb;
3046 	int rc;
3047 	LIST_HEAD(cmplq);
3048 
3049 	phba->sli.slistat.mbox_event++;
3050 
3051 	/* Get all completed mailboxe buffers into the cmplq */
3052 	spin_lock_irq(&phba->hbalock);
3053 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
3054 	spin_unlock_irq(&phba->hbalock);
3055 
3056 	/* Get a Mailbox buffer to setup mailbox commands for callback */
3057 	do {
3058 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
3059 		if (pmb == NULL)
3060 			break;
3061 
3062 		pmbox = &pmb->u.mb;
3063 
3064 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
3065 			if (pmb->vport) {
3066 				lpfc_debugfs_disc_trc(pmb->vport,
3067 					LPFC_DISC_TRC_MBOX_VPORT,
3068 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
3069 					(uint32_t)pmbox->mbxCommand,
3070 					pmbox->un.varWords[0],
3071 					pmbox->un.varWords[1]);
3072 			}
3073 			else {
3074 				lpfc_debugfs_disc_trc(phba->pport,
3075 					LPFC_DISC_TRC_MBOX,
3076 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
3077 					(uint32_t)pmbox->mbxCommand,
3078 					pmbox->un.varWords[0],
3079 					pmbox->un.varWords[1]);
3080 			}
3081 		}
3082 
3083 		/*
3084 		 * It is a fatal error if unknown mbox command completion.
3085 		 */
3086 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
3087 		    MBX_SHUTDOWN) {
3088 			/* Unknown mailbox command compl */
3089 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3090 					"(%d):0323 Unknown Mailbox command "
3091 					"x%x (x%x/x%x) Cmpl\n",
3092 					pmb->vport ? pmb->vport->vpi :
3093 					LPFC_VPORT_UNKNOWN,
3094 					pmbox->mbxCommand,
3095 					lpfc_sli_config_mbox_subsys_get(phba,
3096 									pmb),
3097 					lpfc_sli_config_mbox_opcode_get(phba,
3098 									pmb));
3099 			phba->link_state = LPFC_HBA_ERROR;
3100 			phba->work_hs = HS_FFER3;
3101 			lpfc_handle_eratt(phba);
3102 			continue;
3103 		}
3104 
3105 		if (pmbox->mbxStatus) {
3106 			phba->sli.slistat.mbox_stat_err++;
3107 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
3108 				/* Mbox cmd cmpl error - RETRYing */
3109 				lpfc_printf_log(phba, KERN_INFO,
3110 					LOG_MBOX | LOG_SLI,
3111 					"(%d):0305 Mbox cmd cmpl "
3112 					"error - RETRYing Data: x%x "
3113 					"(x%x/x%x) x%x x%x x%x\n",
3114 					pmb->vport ? pmb->vport->vpi :
3115 					LPFC_VPORT_UNKNOWN,
3116 					pmbox->mbxCommand,
3117 					lpfc_sli_config_mbox_subsys_get(phba,
3118 									pmb),
3119 					lpfc_sli_config_mbox_opcode_get(phba,
3120 									pmb),
3121 					pmbox->mbxStatus,
3122 					pmbox->un.varWords[0],
3123 					pmb->vport ? pmb->vport->port_state :
3124 					LPFC_VPORT_UNKNOWN);
3125 				pmbox->mbxStatus = 0;
3126 				pmbox->mbxOwner = OWN_HOST;
3127 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3128 				if (rc != MBX_NOT_FINISHED)
3129 					continue;
3130 			}
3131 		}
3132 
3133 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
3134 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
3135 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
3136 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
3137 				"x%x x%x x%x\n",
3138 				pmb->vport ? pmb->vport->vpi : 0,
3139 				pmbox->mbxCommand,
3140 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
3141 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
3142 				pmb->mbox_cmpl,
3143 				*((uint32_t *) pmbox),
3144 				pmbox->un.varWords[0],
3145 				pmbox->un.varWords[1],
3146 				pmbox->un.varWords[2],
3147 				pmbox->un.varWords[3],
3148 				pmbox->un.varWords[4],
3149 				pmbox->un.varWords[5],
3150 				pmbox->un.varWords[6],
3151 				pmbox->un.varWords[7],
3152 				pmbox->un.varWords[8],
3153 				pmbox->un.varWords[9],
3154 				pmbox->un.varWords[10]);
3155 
3156 		if (pmb->mbox_cmpl)
3157 			pmb->mbox_cmpl(phba,pmb);
3158 	} while (1);
3159 	return 0;
3160 }
3161 
3162 /**
3163  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
3164  * @phba: Pointer to HBA context object.
3165  * @pring: Pointer to driver SLI ring object.
3166  * @tag: buffer tag.
3167  *
3168  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
3169  * is set in the tag the buffer is posted for a particular exchange,
3170  * the function will return the buffer without replacing the buffer.
3171  * If the buffer is for unsolicited ELS or CT traffic, this function
3172  * returns the buffer and also posts another buffer to the firmware.
3173  **/
3174 static struct lpfc_dmabuf *
3175 lpfc_sli_get_buff(struct lpfc_hba *phba,
3176 		  struct lpfc_sli_ring *pring,
3177 		  uint32_t tag)
3178 {
3179 	struct hbq_dmabuf *hbq_entry;
3180 
3181 	if (tag & QUE_BUFTAG_BIT)
3182 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
3183 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
3184 	if (!hbq_entry)
3185 		return NULL;
3186 	return &hbq_entry->dbuf;
3187 }
3188 
3189 /**
3190  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
3191  *                              containing a NVME LS request.
3192  * @phba: pointer to lpfc hba data structure.
3193  * @piocb: pointer to the iocbq struct representing the sequence starting
3194  *        frame.
3195  *
3196  * This routine initially validates the NVME LS, validates there is a login
3197  * with the port that sent the LS, and then calls the appropriate nvme host
3198  * or target LS request handler.
3199  **/
3200 static void
3201 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
3202 {
3203 	struct lpfc_nodelist *ndlp;
3204 	struct lpfc_dmabuf *d_buf;
3205 	struct hbq_dmabuf *nvmebuf;
3206 	struct fc_frame_header *fc_hdr;
3207 	struct lpfc_async_xchg_ctx *axchg = NULL;
3208 	char *failwhy = NULL;
3209 	uint32_t oxid, sid, did, fctl, size;
3210 	int ret = 1;
3211 
3212 	d_buf = piocb->cmd_dmabuf;
3213 
3214 	nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
3215 	fc_hdr = nvmebuf->hbuf.virt;
3216 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
3217 	sid = sli4_sid_from_fc_hdr(fc_hdr);
3218 	did = sli4_did_from_fc_hdr(fc_hdr);
3219 	fctl = (fc_hdr->fh_f_ctl[0] << 16 |
3220 		fc_hdr->fh_f_ctl[1] << 8 |
3221 		fc_hdr->fh_f_ctl[2]);
3222 	size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
3223 
3224 	lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
3225 			 oxid, size, sid);
3226 
3227 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
3228 		failwhy = "Driver Unloading";
3229 	} else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
3230 		failwhy = "NVME FC4 Disabled";
3231 	} else if (!phba->nvmet_support && !phba->pport->localport) {
3232 		failwhy = "No Localport";
3233 	} else if (phba->nvmet_support && !phba->targetport) {
3234 		failwhy = "No Targetport";
3235 	} else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
3236 		failwhy = "Bad NVME LS R_CTL";
3237 	} else if (unlikely((fctl & 0x00FF0000) !=
3238 			(FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
3239 		failwhy = "Bad NVME LS F_CTL";
3240 	} else {
3241 		axchg = kzalloc(sizeof(*axchg), GFP_ATOMIC);
3242 		if (!axchg)
3243 			failwhy = "No CTX memory";
3244 	}
3245 
3246 	if (unlikely(failwhy)) {
3247 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3248 				"6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
3249 				sid, oxid, failwhy);
3250 		goto out_fail;
3251 	}
3252 
3253 	/* validate the source of the LS is logged in */
3254 	ndlp = lpfc_findnode_did(phba->pport, sid);
3255 	if (!ndlp ||
3256 	    ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
3257 	     (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
3258 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
3259 				"6216 NVME Unsol rcv: No ndlp: "
3260 				"NPort_ID x%x oxid x%x\n",
3261 				sid, oxid);
3262 		goto out_fail;
3263 	}
3264 
3265 	axchg->phba = phba;
3266 	axchg->ndlp = ndlp;
3267 	axchg->size = size;
3268 	axchg->oxid = oxid;
3269 	axchg->sid = sid;
3270 	axchg->wqeq = NULL;
3271 	axchg->state = LPFC_NVME_STE_LS_RCV;
3272 	axchg->entry_cnt = 1;
3273 	axchg->rqb_buffer = (void *)nvmebuf;
3274 	axchg->hdwq = &phba->sli4_hba.hdwq[0];
3275 	axchg->payload = nvmebuf->dbuf.virt;
3276 	INIT_LIST_HEAD(&axchg->list);
3277 
3278 	if (phba->nvmet_support) {
3279 		ret = lpfc_nvmet_handle_lsreq(phba, axchg);
3280 		spin_lock_irq(&ndlp->lock);
3281 		if (!ret && !(ndlp->fc4_xpt_flags & NLP_XPT_HAS_HH)) {
3282 			ndlp->fc4_xpt_flags |= NLP_XPT_HAS_HH;
3283 			spin_unlock_irq(&ndlp->lock);
3284 
3285 			/* This reference is a single occurrence to hold the
3286 			 * node valid until the nvmet transport calls
3287 			 * host_release.
3288 			 */
3289 			if (!lpfc_nlp_get(ndlp))
3290 				goto out_fail;
3291 
3292 			lpfc_printf_log(phba, KERN_ERR, LOG_NODE,
3293 					"6206 NVMET unsol ls_req ndlp x%px "
3294 					"DID x%x xflags x%x refcnt %d\n",
3295 					ndlp, ndlp->nlp_DID,
3296 					ndlp->fc4_xpt_flags,
3297 					kref_read(&ndlp->kref));
3298 		} else {
3299 			spin_unlock_irq(&ndlp->lock);
3300 		}
3301 	} else {
3302 		ret = lpfc_nvme_handle_lsreq(phba, axchg);
3303 	}
3304 
3305 	/* if zero, LS was successfully handled. If non-zero, LS not handled */
3306 	if (!ret)
3307 		return;
3308 
3309 out_fail:
3310 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3311 			"6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
3312 			"NVMe%s handler failed %d\n",
3313 			did, sid, oxid,
3314 			(phba->nvmet_support) ? "T" : "I", ret);
3315 
3316 	/* recycle receive buffer */
3317 	lpfc_in_buf_free(phba, &nvmebuf->dbuf);
3318 
3319 	/* If start of new exchange, abort it */
3320 	if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
3321 		ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
3322 
3323 	if (ret)
3324 		kfree(axchg);
3325 }
3326 
3327 /**
3328  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
3329  * @phba: Pointer to HBA context object.
3330  * @pring: Pointer to driver SLI ring object.
3331  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
3332  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
3333  * @fch_type: the type for the first frame of the sequence.
3334  *
3335  * This function is called with no lock held. This function uses the r_ctl and
3336  * type of the received sequence to find the correct callback function to call
3337  * to process the sequence.
3338  **/
3339 static int
3340 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3341 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
3342 			 uint32_t fch_type)
3343 {
3344 	int i;
3345 
3346 	switch (fch_type) {
3347 	case FC_TYPE_NVME:
3348 		lpfc_nvme_unsol_ls_handler(phba, saveq);
3349 		return 1;
3350 	default:
3351 		break;
3352 	}
3353 
3354 	/* unSolicited Responses */
3355 	if (pring->prt[0].profile) {
3356 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
3357 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
3358 									saveq);
3359 		return 1;
3360 	}
3361 	/* We must search, based on rctl / type
3362 	   for the right routine */
3363 	for (i = 0; i < pring->num_mask; i++) {
3364 		if ((pring->prt[i].rctl == fch_r_ctl) &&
3365 		    (pring->prt[i].type == fch_type)) {
3366 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
3367 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
3368 						(phba, pring, saveq);
3369 			return 1;
3370 		}
3371 	}
3372 	return 0;
3373 }
3374 
3375 static void
3376 lpfc_sli_prep_unsol_wqe(struct lpfc_hba *phba,
3377 			struct lpfc_iocbq *saveq)
3378 {
3379 	IOCB_t *irsp;
3380 	union lpfc_wqe128 *wqe;
3381 	u16 i = 0;
3382 
3383 	irsp = &saveq->iocb;
3384 	wqe = &saveq->wqe;
3385 
3386 	/* Fill wcqe with the IOCB status fields */
3387 	bf_set(lpfc_wcqe_c_status, &saveq->wcqe_cmpl, irsp->ulpStatus);
3388 	saveq->wcqe_cmpl.word3 = irsp->ulpBdeCount;
3389 	saveq->wcqe_cmpl.parameter = irsp->un.ulpWord[4];
3390 	saveq->wcqe_cmpl.total_data_placed = irsp->unsli3.rcvsli3.acc_len;
3391 
3392 	/* Source ID */
3393 	bf_set(els_rsp64_sid, &wqe->xmit_els_rsp, irsp->un.rcvels.parmRo);
3394 
3395 	/* rx-id of the response frame */
3396 	bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com, irsp->ulpContext);
3397 
3398 	/* ox-id of the frame */
3399 	bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
3400 	       irsp->unsli3.rcvsli3.ox_id);
3401 
3402 	/* DID */
3403 	bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
3404 	       irsp->un.rcvels.remoteID);
3405 
3406 	/* unsol data len */
3407 	for (i = 0; i < irsp->ulpBdeCount; i++) {
3408 		struct lpfc_hbq_entry *hbqe = NULL;
3409 
3410 		if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3411 			if (i == 0) {
3412 				hbqe = (struct lpfc_hbq_entry *)
3413 					&irsp->un.ulpWord[0];
3414 				saveq->wqe.gen_req.bde.tus.f.bdeSize =
3415 					hbqe->bde.tus.f.bdeSize;
3416 			} else if (i == 1) {
3417 				hbqe = (struct lpfc_hbq_entry *)
3418 					&irsp->unsli3.sli3Words[4];
3419 				saveq->unsol_rcv_len = hbqe->bde.tus.f.bdeSize;
3420 			}
3421 		}
3422 	}
3423 }
3424 
3425 /**
3426  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
3427  * @phba: Pointer to HBA context object.
3428  * @pring: Pointer to driver SLI ring object.
3429  * @saveq: Pointer to the unsolicited iocb.
3430  *
3431  * This function is called with no lock held by the ring event handler
3432  * when there is an unsolicited iocb posted to the response ring by the
3433  * firmware. This function gets the buffer associated with the iocbs
3434  * and calls the event handler for the ring. This function handles both
3435  * qring buffers and hbq buffers.
3436  * When the function returns 1 the caller can free the iocb object otherwise
3437  * upper layer functions will free the iocb objects.
3438  **/
3439 static int
3440 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3441 			    struct lpfc_iocbq *saveq)
3442 {
3443 	IOCB_t           * irsp;
3444 	WORD5            * w5p;
3445 	dma_addr_t	 paddr;
3446 	uint32_t           Rctl, Type;
3447 	struct lpfc_iocbq *iocbq;
3448 	struct lpfc_dmabuf *dmzbuf;
3449 
3450 	irsp = &saveq->iocb;
3451 	saveq->vport = phba->pport;
3452 
3453 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
3454 		if (pring->lpfc_sli_rcv_async_status)
3455 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
3456 		else
3457 			lpfc_printf_log(phba,
3458 					KERN_WARNING,
3459 					LOG_SLI,
3460 					"0316 Ring %d handler: unexpected "
3461 					"ASYNC_STATUS iocb received evt_code "
3462 					"0x%x\n",
3463 					pring->ringno,
3464 					irsp->un.asyncstat.evt_code);
3465 		return 1;
3466 	}
3467 
3468 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3469 	    (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3470 		if (irsp->ulpBdeCount > 0) {
3471 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3472 						   irsp->un.ulpWord[3]);
3473 			lpfc_in_buf_free(phba, dmzbuf);
3474 		}
3475 
3476 		if (irsp->ulpBdeCount > 1) {
3477 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3478 						   irsp->unsli3.sli3Words[3]);
3479 			lpfc_in_buf_free(phba, dmzbuf);
3480 		}
3481 
3482 		if (irsp->ulpBdeCount > 2) {
3483 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3484 						   irsp->unsli3.sli3Words[7]);
3485 			lpfc_in_buf_free(phba, dmzbuf);
3486 		}
3487 
3488 		return 1;
3489 	}
3490 
3491 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3492 		if (irsp->ulpBdeCount != 0) {
3493 			saveq->cmd_dmabuf = lpfc_sli_get_buff(phba, pring,
3494 						irsp->un.ulpWord[3]);
3495 			if (!saveq->cmd_dmabuf)
3496 				lpfc_printf_log(phba,
3497 					KERN_ERR,
3498 					LOG_SLI,
3499 					"0341 Ring %d Cannot find buffer for "
3500 					"an unsolicited iocb. tag 0x%x\n",
3501 					pring->ringno,
3502 					irsp->un.ulpWord[3]);
3503 		}
3504 		if (irsp->ulpBdeCount == 2) {
3505 			saveq->bpl_dmabuf = lpfc_sli_get_buff(phba, pring,
3506 						irsp->unsli3.sli3Words[7]);
3507 			if (!saveq->bpl_dmabuf)
3508 				lpfc_printf_log(phba,
3509 					KERN_ERR,
3510 					LOG_SLI,
3511 					"0342 Ring %d Cannot find buffer for an"
3512 					" unsolicited iocb. tag 0x%x\n",
3513 					pring->ringno,
3514 					irsp->unsli3.sli3Words[7]);
3515 		}
3516 		list_for_each_entry(iocbq, &saveq->list, list) {
3517 			irsp = &iocbq->iocb;
3518 			if (irsp->ulpBdeCount != 0) {
3519 				iocbq->cmd_dmabuf = lpfc_sli_get_buff(phba,
3520 							pring,
3521 							irsp->un.ulpWord[3]);
3522 				if (!iocbq->cmd_dmabuf)
3523 					lpfc_printf_log(phba,
3524 						KERN_ERR,
3525 						LOG_SLI,
3526 						"0343 Ring %d Cannot find "
3527 						"buffer for an unsolicited iocb"
3528 						". tag 0x%x\n", pring->ringno,
3529 						irsp->un.ulpWord[3]);
3530 			}
3531 			if (irsp->ulpBdeCount == 2) {
3532 				iocbq->bpl_dmabuf = lpfc_sli_get_buff(phba,
3533 						pring,
3534 						irsp->unsli3.sli3Words[7]);
3535 				if (!iocbq->bpl_dmabuf)
3536 					lpfc_printf_log(phba,
3537 						KERN_ERR,
3538 						LOG_SLI,
3539 						"0344 Ring %d Cannot find "
3540 						"buffer for an unsolicited "
3541 						"iocb. tag 0x%x\n",
3542 						pring->ringno,
3543 						irsp->unsli3.sli3Words[7]);
3544 			}
3545 		}
3546 	} else {
3547 		paddr = getPaddr(irsp->un.cont64[0].addrHigh,
3548 				 irsp->un.cont64[0].addrLow);
3549 		saveq->cmd_dmabuf = lpfc_sli_ringpostbuf_get(phba, pring,
3550 							     paddr);
3551 		if (irsp->ulpBdeCount == 2) {
3552 			paddr = getPaddr(irsp->un.cont64[1].addrHigh,
3553 					 irsp->un.cont64[1].addrLow);
3554 			saveq->bpl_dmabuf = lpfc_sli_ringpostbuf_get(phba,
3555 								   pring,
3556 								   paddr);
3557 		}
3558 	}
3559 
3560 	if (irsp->ulpBdeCount != 0 &&
3561 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3562 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3563 		int found = 0;
3564 
3565 		/* search continue save q for same XRI */
3566 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3567 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3568 				saveq->iocb.unsli3.rcvsli3.ox_id) {
3569 				list_add_tail(&saveq->list, &iocbq->list);
3570 				found = 1;
3571 				break;
3572 			}
3573 		}
3574 		if (!found)
3575 			list_add_tail(&saveq->clist,
3576 				      &pring->iocb_continue_saveq);
3577 
3578 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3579 			list_del_init(&iocbq->clist);
3580 			saveq = iocbq;
3581 			irsp = &saveq->iocb;
3582 		} else {
3583 			return 0;
3584 		}
3585 	}
3586 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3587 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3588 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3589 		Rctl = FC_RCTL_ELS_REQ;
3590 		Type = FC_TYPE_ELS;
3591 	} else {
3592 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3593 		Rctl = w5p->hcsw.Rctl;
3594 		Type = w5p->hcsw.Type;
3595 
3596 		/* Firmware Workaround */
3597 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3598 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3599 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3600 			Rctl = FC_RCTL_ELS_REQ;
3601 			Type = FC_TYPE_ELS;
3602 			w5p->hcsw.Rctl = Rctl;
3603 			w5p->hcsw.Type = Type;
3604 		}
3605 	}
3606 
3607 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) &&
3608 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX ||
3609 	    irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3610 		if (irsp->unsli3.rcvsli3.vpi == 0xffff)
3611 			saveq->vport = phba->pport;
3612 		else
3613 			saveq->vport = lpfc_find_vport_by_vpid(phba,
3614 					       irsp->unsli3.rcvsli3.vpi);
3615 	}
3616 
3617 	/* Prepare WQE with Unsol frame */
3618 	lpfc_sli_prep_unsol_wqe(phba, saveq);
3619 
3620 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3621 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3622 				"0313 Ring %d handler: unexpected Rctl x%x "
3623 				"Type x%x received\n",
3624 				pring->ringno, Rctl, Type);
3625 
3626 	return 1;
3627 }
3628 
3629 /**
3630  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3631  * @phba: Pointer to HBA context object.
3632  * @pring: Pointer to driver SLI ring object.
3633  * @prspiocb: Pointer to response iocb object.
3634  *
3635  * This function looks up the iocb_lookup table to get the command iocb
3636  * corresponding to the given response iocb using the iotag of the
3637  * response iocb. The driver calls this function with the hbalock held
3638  * for SLI3 ports or the ring lock held for SLI4 ports.
3639  * This function returns the command iocb object if it finds the command
3640  * iocb else returns NULL.
3641  **/
3642 static struct lpfc_iocbq *
3643 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3644 		      struct lpfc_sli_ring *pring,
3645 		      struct lpfc_iocbq *prspiocb)
3646 {
3647 	struct lpfc_iocbq *cmd_iocb = NULL;
3648 	u16 iotag;
3649 
3650 	if (phba->sli_rev == LPFC_SLI_REV4)
3651 		iotag = get_wqe_reqtag(prspiocb);
3652 	else
3653 		iotag = prspiocb->iocb.ulpIoTag;
3654 
3655 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3656 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3657 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3658 			/* remove from txcmpl queue list */
3659 			list_del_init(&cmd_iocb->list);
3660 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3661 			pring->txcmplq_cnt--;
3662 			return cmd_iocb;
3663 		}
3664 	}
3665 
3666 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3667 			"0317 iotag x%x is out of "
3668 			"range: max iotag x%x\n",
3669 			iotag, phba->sli.last_iotag);
3670 	return NULL;
3671 }
3672 
3673 /**
3674  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3675  * @phba: Pointer to HBA context object.
3676  * @pring: Pointer to driver SLI ring object.
3677  * @iotag: IOCB tag.
3678  *
3679  * This function looks up the iocb_lookup table to get the command iocb
3680  * corresponding to the given iotag. The driver calls this function with
3681  * the ring lock held because this function is an SLI4 port only helper.
3682  * This function returns the command iocb object if it finds the command
3683  * iocb else returns NULL.
3684  **/
3685 static struct lpfc_iocbq *
3686 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3687 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3688 {
3689 	struct lpfc_iocbq *cmd_iocb = NULL;
3690 
3691 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3692 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3693 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3694 			/* remove from txcmpl queue list */
3695 			list_del_init(&cmd_iocb->list);
3696 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3697 			pring->txcmplq_cnt--;
3698 			return cmd_iocb;
3699 		}
3700 	}
3701 
3702 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3703 			"0372 iotag x%x lookup error: max iotag (x%x) "
3704 			"cmd_flag x%x\n",
3705 			iotag, phba->sli.last_iotag,
3706 			cmd_iocb ? cmd_iocb->cmd_flag : 0xffff);
3707 	return NULL;
3708 }
3709 
3710 /**
3711  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3712  * @phba: Pointer to HBA context object.
3713  * @pring: Pointer to driver SLI ring object.
3714  * @saveq: Pointer to the response iocb to be processed.
3715  *
3716  * This function is called by the ring event handler for non-fcp
3717  * rings when there is a new response iocb in the response ring.
3718  * The caller is not required to hold any locks. This function
3719  * gets the command iocb associated with the response iocb and
3720  * calls the completion handler for the command iocb. If there
3721  * is no completion handler, the function will free the resources
3722  * associated with command iocb. If the response iocb is for
3723  * an already aborted command iocb, the status of the completion
3724  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3725  * This function always returns 1.
3726  **/
3727 static int
3728 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3729 			  struct lpfc_iocbq *saveq)
3730 {
3731 	struct lpfc_iocbq *cmdiocbp;
3732 	unsigned long iflag;
3733 	u32 ulp_command, ulp_status, ulp_word4, ulp_context, iotag;
3734 
3735 	if (phba->sli_rev == LPFC_SLI_REV4)
3736 		spin_lock_irqsave(&pring->ring_lock, iflag);
3737 	else
3738 		spin_lock_irqsave(&phba->hbalock, iflag);
3739 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3740 	if (phba->sli_rev == LPFC_SLI_REV4)
3741 		spin_unlock_irqrestore(&pring->ring_lock, iflag);
3742 	else
3743 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3744 
3745 	ulp_command = get_job_cmnd(phba, saveq);
3746 	ulp_status = get_job_ulpstatus(phba, saveq);
3747 	ulp_word4 = get_job_word4(phba, saveq);
3748 	ulp_context = get_job_ulpcontext(phba, saveq);
3749 	if (phba->sli_rev == LPFC_SLI_REV4)
3750 		iotag = get_wqe_reqtag(saveq);
3751 	else
3752 		iotag = saveq->iocb.ulpIoTag;
3753 
3754 	if (cmdiocbp) {
3755 		ulp_command = get_job_cmnd(phba, cmdiocbp);
3756 		if (cmdiocbp->cmd_cmpl) {
3757 			/*
3758 			 * If an ELS command failed send an event to mgmt
3759 			 * application.
3760 			 */
3761 			if (ulp_status &&
3762 			     (pring->ringno == LPFC_ELS_RING) &&
3763 			     (ulp_command == CMD_ELS_REQUEST64_CR))
3764 				lpfc_send_els_failure_event(phba,
3765 					cmdiocbp, saveq);
3766 
3767 			/*
3768 			 * Post all ELS completions to the worker thread.
3769 			 * All other are passed to the completion callback.
3770 			 */
3771 			if (pring->ringno == LPFC_ELS_RING) {
3772 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3773 				    (cmdiocbp->cmd_flag &
3774 							LPFC_DRIVER_ABORTED)) {
3775 					spin_lock_irqsave(&phba->hbalock,
3776 							  iflag);
3777 					cmdiocbp->cmd_flag &=
3778 						~LPFC_DRIVER_ABORTED;
3779 					spin_unlock_irqrestore(&phba->hbalock,
3780 							       iflag);
3781 					saveq->iocb.ulpStatus =
3782 						IOSTAT_LOCAL_REJECT;
3783 					saveq->iocb.un.ulpWord[4] =
3784 						IOERR_SLI_ABORTED;
3785 
3786 					/* Firmware could still be in progress
3787 					 * of DMAing payload, so don't free data
3788 					 * buffer till after a hbeat.
3789 					 */
3790 					spin_lock_irqsave(&phba->hbalock,
3791 							  iflag);
3792 					saveq->cmd_flag |= LPFC_DELAY_MEM_FREE;
3793 					spin_unlock_irqrestore(&phba->hbalock,
3794 							       iflag);
3795 				}
3796 				if (phba->sli_rev == LPFC_SLI_REV4) {
3797 					if (saveq->cmd_flag &
3798 					    LPFC_EXCHANGE_BUSY) {
3799 						/* Set cmdiocb flag for the
3800 						 * exchange busy so sgl (xri)
3801 						 * will not be released until
3802 						 * the abort xri is received
3803 						 * from hba.
3804 						 */
3805 						spin_lock_irqsave(
3806 							&phba->hbalock, iflag);
3807 						cmdiocbp->cmd_flag |=
3808 							LPFC_EXCHANGE_BUSY;
3809 						spin_unlock_irqrestore(
3810 							&phba->hbalock, iflag);
3811 					}
3812 					if (cmdiocbp->cmd_flag &
3813 					    LPFC_DRIVER_ABORTED) {
3814 						/*
3815 						 * Clear LPFC_DRIVER_ABORTED
3816 						 * bit in case it was driver
3817 						 * initiated abort.
3818 						 */
3819 						spin_lock_irqsave(
3820 							&phba->hbalock, iflag);
3821 						cmdiocbp->cmd_flag &=
3822 							~LPFC_DRIVER_ABORTED;
3823 						spin_unlock_irqrestore(
3824 							&phba->hbalock, iflag);
3825 						set_job_ulpstatus(cmdiocbp,
3826 								  IOSTAT_LOCAL_REJECT);
3827 						set_job_ulpword4(cmdiocbp,
3828 								 IOERR_ABORT_REQUESTED);
3829 						/*
3830 						 * For SLI4, irspiocb contains
3831 						 * NO_XRI in sli_xritag, it
3832 						 * shall not affect releasing
3833 						 * sgl (xri) process.
3834 						 */
3835 						set_job_ulpstatus(saveq,
3836 								  IOSTAT_LOCAL_REJECT);
3837 						set_job_ulpword4(saveq,
3838 								 IOERR_SLI_ABORTED);
3839 						spin_lock_irqsave(
3840 							&phba->hbalock, iflag);
3841 						saveq->cmd_flag |=
3842 							LPFC_DELAY_MEM_FREE;
3843 						spin_unlock_irqrestore(
3844 							&phba->hbalock, iflag);
3845 					}
3846 				}
3847 			}
3848 			cmdiocbp->cmd_cmpl(phba, cmdiocbp, saveq);
3849 		} else
3850 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3851 	} else {
3852 		/*
3853 		 * Unknown initiating command based on the response iotag.
3854 		 * This could be the case on the ELS ring because of
3855 		 * lpfc_els_abort().
3856 		 */
3857 		if (pring->ringno != LPFC_ELS_RING) {
3858 			/*
3859 			 * Ring <ringno> handler: unexpected completion IoTag
3860 			 * <IoTag>
3861 			 */
3862 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3863 					 "0322 Ring %d handler: "
3864 					 "unexpected completion IoTag x%x "
3865 					 "Data: x%x x%x x%x x%x\n",
3866 					 pring->ringno, iotag, ulp_status,
3867 					 ulp_word4, ulp_command, ulp_context);
3868 		}
3869 	}
3870 
3871 	return 1;
3872 }
3873 
3874 /**
3875  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3876  * @phba: Pointer to HBA context object.
3877  * @pring: Pointer to driver SLI ring object.
3878  *
3879  * This function is called from the iocb ring event handlers when
3880  * put pointer is ahead of the get pointer for a ring. This function signal
3881  * an error attention condition to the worker thread and the worker
3882  * thread will transition the HBA to offline state.
3883  **/
3884 static void
3885 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3886 {
3887 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3888 	/*
3889 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3890 	 * rsp ring <portRspMax>
3891 	 */
3892 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3893 			"0312 Ring %d handler: portRspPut %d "
3894 			"is bigger than rsp ring %d\n",
3895 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3896 			pring->sli.sli3.numRiocb);
3897 
3898 	phba->link_state = LPFC_HBA_ERROR;
3899 
3900 	/*
3901 	 * All error attention handlers are posted to
3902 	 * worker thread
3903 	 */
3904 	phba->work_ha |= HA_ERATT;
3905 	phba->work_hs = HS_FFER3;
3906 
3907 	lpfc_worker_wake_up(phba);
3908 
3909 	return;
3910 }
3911 
3912 /**
3913  * lpfc_poll_eratt - Error attention polling timer timeout handler
3914  * @t: Context to fetch pointer to address of HBA context object from.
3915  *
3916  * This function is invoked by the Error Attention polling timer when the
3917  * timer times out. It will check the SLI Error Attention register for
3918  * possible attention events. If so, it will post an Error Attention event
3919  * and wake up worker thread to process it. Otherwise, it will set up the
3920  * Error Attention polling timer for the next poll.
3921  **/
3922 void lpfc_poll_eratt(struct timer_list *t)
3923 {
3924 	struct lpfc_hba *phba;
3925 	uint32_t eratt = 0;
3926 	uint64_t sli_intr, cnt;
3927 
3928 	phba = timer_container_of(phba, t, eratt_poll);
3929 
3930 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
3931 		return;
3932 
3933 	if (phba->sli_rev == LPFC_SLI_REV4 &&
3934 	    !test_bit(HBA_SETUP, &phba->hba_flag)) {
3935 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3936 				"0663 HBA still initializing 0x%lx, restart "
3937 				"timer\n",
3938 				phba->hba_flag);
3939 		goto restart_timer;
3940 	}
3941 
3942 	/* Here we will also keep track of interrupts per sec of the hba */
3943 	sli_intr = phba->sli.slistat.sli_intr;
3944 
3945 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3946 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3947 			sli_intr);
3948 	else
3949 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3950 
3951 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3952 	do_div(cnt, phba->eratt_poll_interval);
3953 	phba->sli.slistat.sli_ips = cnt;
3954 
3955 	phba->sli.slistat.sli_prev_intr = sli_intr;
3956 
3957 	/* Check chip HA register for error event */
3958 	eratt = lpfc_sli_check_eratt(phba);
3959 
3960 	if (eratt) {
3961 		/* Tell the worker thread there is work to do */
3962 		lpfc_worker_wake_up(phba);
3963 		return;
3964 	}
3965 
3966 restart_timer:
3967 	/* Restart the timer for next eratt poll */
3968 	mod_timer(&phba->eratt_poll,
3969 		  jiffies + secs_to_jiffies(phba->eratt_poll_interval));
3970 	return;
3971 }
3972 
3973 
3974 /**
3975  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3976  * @phba: Pointer to HBA context object.
3977  * @pring: Pointer to driver SLI ring object.
3978  * @mask: Host attention register mask for this ring.
3979  *
3980  * This function is called from the interrupt context when there is a ring
3981  * event for the fcp ring. The caller does not hold any lock.
3982  * The function processes each response iocb in the response ring until it
3983  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3984  * LE bit set. The function will call the completion handler of the command iocb
3985  * if the response iocb indicates a completion for a command iocb or it is
3986  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3987  * function if this is an unsolicited iocb.
3988  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3989  * to check it explicitly.
3990  */
3991 int
3992 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3993 				struct lpfc_sli_ring *pring, uint32_t mask)
3994 {
3995 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3996 	IOCB_t *irsp = NULL;
3997 	IOCB_t *entry = NULL;
3998 	struct lpfc_iocbq *cmdiocbq = NULL;
3999 	struct lpfc_iocbq rspiocbq;
4000 	uint32_t status;
4001 	uint32_t portRspPut, portRspMax;
4002 	int rc = 1;
4003 	lpfc_iocb_type type;
4004 	unsigned long iflag;
4005 	uint32_t rsp_cmpl = 0;
4006 
4007 	spin_lock_irqsave(&phba->hbalock, iflag);
4008 	pring->stats.iocb_event++;
4009 
4010 	/*
4011 	 * The next available response entry should never exceed the maximum
4012 	 * entries.  If it does, treat it as an adapter hardware error.
4013 	 */
4014 	portRspMax = pring->sli.sli3.numRiocb;
4015 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4016 	if (unlikely(portRspPut >= portRspMax)) {
4017 		lpfc_sli_rsp_pointers_error(phba, pring);
4018 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4019 		return 1;
4020 	}
4021 	if (phba->fcp_ring_in_use) {
4022 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4023 		return 1;
4024 	} else
4025 		phba->fcp_ring_in_use = 1;
4026 
4027 	rmb();
4028 	while (pring->sli.sli3.rspidx != portRspPut) {
4029 		/*
4030 		 * Fetch an entry off the ring and copy it into a local data
4031 		 * structure.  The copy involves a byte-swap since the
4032 		 * network byte order and pci byte orders are different.
4033 		 */
4034 		entry = lpfc_resp_iocb(phba, pring);
4035 		phba->last_completion_time = jiffies;
4036 
4037 		if (++pring->sli.sli3.rspidx >= portRspMax)
4038 			pring->sli.sli3.rspidx = 0;
4039 
4040 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
4041 				      (uint32_t *) &rspiocbq.iocb,
4042 				      phba->iocb_rsp_size);
4043 		INIT_LIST_HEAD(&(rspiocbq.list));
4044 		irsp = &rspiocbq.iocb;
4045 
4046 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
4047 		pring->stats.iocb_rsp++;
4048 		rsp_cmpl++;
4049 
4050 		if (unlikely(irsp->ulpStatus)) {
4051 			/*
4052 			 * If resource errors reported from HBA, reduce
4053 			 * queuedepths of the SCSI device.
4054 			 */
4055 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
4056 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
4057 			     IOERR_NO_RESOURCES)) {
4058 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4059 				phba->lpfc_rampdown_queue_depth(phba);
4060 				spin_lock_irqsave(&phba->hbalock, iflag);
4061 			}
4062 
4063 			/* Rsp ring <ringno> error: IOCB */
4064 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4065 					"0336 Rsp Ring %d error: IOCB Data: "
4066 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
4067 					pring->ringno,
4068 					irsp->un.ulpWord[0],
4069 					irsp->un.ulpWord[1],
4070 					irsp->un.ulpWord[2],
4071 					irsp->un.ulpWord[3],
4072 					irsp->un.ulpWord[4],
4073 					irsp->un.ulpWord[5],
4074 					*(uint32_t *)&irsp->un1,
4075 					*((uint32_t *)&irsp->un1 + 1));
4076 		}
4077 
4078 		switch (type) {
4079 		case LPFC_ABORT_IOCB:
4080 		case LPFC_SOL_IOCB:
4081 			/*
4082 			 * Idle exchange closed via ABTS from port.  No iocb
4083 			 * resources need to be recovered.
4084 			 */
4085 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
4086 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4087 						"0333 IOCB cmd 0x%x"
4088 						" processed. Skipping"
4089 						" completion\n",
4090 						irsp->ulpCommand);
4091 				break;
4092 			}
4093 
4094 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
4095 							 &rspiocbq);
4096 			if (unlikely(!cmdiocbq))
4097 				break;
4098 			if (cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED)
4099 				cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
4100 			if (cmdiocbq->cmd_cmpl) {
4101 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4102 				cmdiocbq->cmd_cmpl(phba, cmdiocbq, &rspiocbq);
4103 				spin_lock_irqsave(&phba->hbalock, iflag);
4104 			}
4105 			break;
4106 		case LPFC_UNSOL_IOCB:
4107 			spin_unlock_irqrestore(&phba->hbalock, iflag);
4108 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
4109 			spin_lock_irqsave(&phba->hbalock, iflag);
4110 			break;
4111 		default:
4112 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
4113 				char adaptermsg[LPFC_MAX_ADPTMSG];
4114 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4115 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
4116 				       MAX_MSG_DATA);
4117 				dev_warn(&((phba->pcidev)->dev),
4118 					 "lpfc%d: %s\n",
4119 					 phba->brd_no, adaptermsg);
4120 			} else {
4121 				/* Unknown IOCB command */
4122 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4123 						"0334 Unknown IOCB command "
4124 						"Data: x%x, x%x x%x x%x x%x\n",
4125 						type, irsp->ulpCommand,
4126 						irsp->ulpStatus,
4127 						irsp->ulpIoTag,
4128 						irsp->ulpContext);
4129 			}
4130 			break;
4131 		}
4132 
4133 		/*
4134 		 * The response IOCB has been processed.  Update the ring
4135 		 * pointer in SLIM.  If the port response put pointer has not
4136 		 * been updated, sync the pgp->rspPutInx and fetch the new port
4137 		 * response put pointer.
4138 		 */
4139 		writel(pring->sli.sli3.rspidx,
4140 			&phba->host_gp[pring->ringno].rspGetInx);
4141 
4142 		if (pring->sli.sli3.rspidx == portRspPut)
4143 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4144 	}
4145 
4146 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
4147 		pring->stats.iocb_rsp_full++;
4148 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4149 		writel(status, phba->CAregaddr);
4150 		readl(phba->CAregaddr);
4151 	}
4152 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4153 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4154 		pring->stats.iocb_cmd_empty++;
4155 
4156 		/* Force update of the local copy of cmdGetInx */
4157 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4158 		lpfc_sli_resume_iocb(phba, pring);
4159 
4160 		if ((pring->lpfc_sli_cmd_available))
4161 			(pring->lpfc_sli_cmd_available) (phba, pring);
4162 
4163 	}
4164 
4165 	phba->fcp_ring_in_use = 0;
4166 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4167 	return rc;
4168 }
4169 
4170 /**
4171  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
4172  * @phba: Pointer to HBA context object.
4173  * @pring: Pointer to driver SLI ring object.
4174  * @rspiocbp: Pointer to driver response IOCB object.
4175  *
4176  * This function is called from the worker thread when there is a slow-path
4177  * response IOCB to process. This function chains all the response iocbs until
4178  * seeing the iocb with the LE bit set. The function will call
4179  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
4180  * completion of a command iocb. The function will call the
4181  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
4182  * The function frees the resources or calls the completion handler if this
4183  * iocb is an abort completion. The function returns NULL when the response
4184  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
4185  * this function shall chain the iocb on to the iocb_continueq and return the
4186  * response iocb passed in.
4187  **/
4188 static struct lpfc_iocbq *
4189 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
4190 			struct lpfc_iocbq *rspiocbp)
4191 {
4192 	struct lpfc_iocbq *saveq;
4193 	struct lpfc_iocbq *cmdiocb;
4194 	struct lpfc_iocbq *next_iocb;
4195 	IOCB_t *irsp;
4196 	uint32_t free_saveq;
4197 	u8 cmd_type;
4198 	lpfc_iocb_type type;
4199 	unsigned long iflag;
4200 	u32 ulp_status = get_job_ulpstatus(phba, rspiocbp);
4201 	u32 ulp_word4 = get_job_word4(phba, rspiocbp);
4202 	u32 ulp_command = get_job_cmnd(phba, rspiocbp);
4203 	int rc;
4204 
4205 	spin_lock_irqsave(&phba->hbalock, iflag);
4206 	/* First add the response iocb to the countinueq list */
4207 	list_add_tail(&rspiocbp->list, &pring->iocb_continueq);
4208 	pring->iocb_continueq_cnt++;
4209 
4210 	/*
4211 	 * By default, the driver expects to free all resources
4212 	 * associated with this iocb completion.
4213 	 */
4214 	free_saveq = 1;
4215 	saveq = list_get_first(&pring->iocb_continueq,
4216 			       struct lpfc_iocbq, list);
4217 	list_del_init(&pring->iocb_continueq);
4218 	pring->iocb_continueq_cnt = 0;
4219 
4220 	pring->stats.iocb_rsp++;
4221 
4222 	/*
4223 	 * If resource errors reported from HBA, reduce
4224 	 * queuedepths of the SCSI device.
4225 	 */
4226 	if (ulp_status == IOSTAT_LOCAL_REJECT &&
4227 	    ((ulp_word4 & IOERR_PARAM_MASK) ==
4228 	     IOERR_NO_RESOURCES)) {
4229 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4230 		phba->lpfc_rampdown_queue_depth(phba);
4231 		spin_lock_irqsave(&phba->hbalock, iflag);
4232 	}
4233 
4234 	if (ulp_status) {
4235 		/* Rsp ring <ringno> error: IOCB */
4236 		if (phba->sli_rev < LPFC_SLI_REV4) {
4237 			irsp = &rspiocbp->iocb;
4238 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4239 					"0328 Rsp Ring %d error: ulp_status x%x "
4240 					"IOCB Data: "
4241 					"x%08x x%08x x%08x x%08x "
4242 					"x%08x x%08x x%08x x%08x "
4243 					"x%08x x%08x x%08x x%08x "
4244 					"x%08x x%08x x%08x x%08x\n",
4245 					pring->ringno, ulp_status,
4246 					get_job_ulpword(rspiocbp, 0),
4247 					get_job_ulpword(rspiocbp, 1),
4248 					get_job_ulpword(rspiocbp, 2),
4249 					get_job_ulpword(rspiocbp, 3),
4250 					get_job_ulpword(rspiocbp, 4),
4251 					get_job_ulpword(rspiocbp, 5),
4252 					*(((uint32_t *)irsp) + 6),
4253 					*(((uint32_t *)irsp) + 7),
4254 					*(((uint32_t *)irsp) + 8),
4255 					*(((uint32_t *)irsp) + 9),
4256 					*(((uint32_t *)irsp) + 10),
4257 					*(((uint32_t *)irsp) + 11),
4258 					*(((uint32_t *)irsp) + 12),
4259 					*(((uint32_t *)irsp) + 13),
4260 					*(((uint32_t *)irsp) + 14),
4261 					*(((uint32_t *)irsp) + 15));
4262 		} else {
4263 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4264 					"0321 Rsp Ring %d error: "
4265 					"IOCB Data: "
4266 					"x%x x%x x%x x%x\n",
4267 					pring->ringno,
4268 					rspiocbp->wcqe_cmpl.word0,
4269 					rspiocbp->wcqe_cmpl.total_data_placed,
4270 					rspiocbp->wcqe_cmpl.parameter,
4271 					rspiocbp->wcqe_cmpl.word3);
4272 		}
4273 	}
4274 
4275 
4276 	/*
4277 	 * Fetch the iocb command type and call the correct completion
4278 	 * routine. Solicited and Unsolicited IOCBs on the ELS ring
4279 	 * get freed back to the lpfc_iocb_list by the discovery
4280 	 * kernel thread.
4281 	 */
4282 	cmd_type = ulp_command & CMD_IOCB_MASK;
4283 	type = lpfc_sli_iocb_cmd_type(cmd_type);
4284 	switch (type) {
4285 	case LPFC_SOL_IOCB:
4286 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4287 		rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
4288 		spin_lock_irqsave(&phba->hbalock, iflag);
4289 		break;
4290 	case LPFC_UNSOL_IOCB:
4291 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4292 		rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
4293 		spin_lock_irqsave(&phba->hbalock, iflag);
4294 		if (!rc)
4295 			free_saveq = 0;
4296 		break;
4297 	case LPFC_ABORT_IOCB:
4298 		cmdiocb = NULL;
4299 		if (ulp_command != CMD_XRI_ABORTED_CX)
4300 			cmdiocb = lpfc_sli_iocbq_lookup(phba, pring,
4301 							saveq);
4302 		if (cmdiocb) {
4303 			/* Call the specified completion routine */
4304 			if (cmdiocb->cmd_cmpl) {
4305 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4306 				cmdiocb->cmd_cmpl(phba, cmdiocb, saveq);
4307 				spin_lock_irqsave(&phba->hbalock, iflag);
4308 			} else {
4309 				__lpfc_sli_release_iocbq(phba, cmdiocb);
4310 			}
4311 		}
4312 		break;
4313 	case LPFC_UNKNOWN_IOCB:
4314 		if (ulp_command == CMD_ADAPTER_MSG) {
4315 			char adaptermsg[LPFC_MAX_ADPTMSG];
4316 
4317 			memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4318 			memcpy(&adaptermsg[0], (uint8_t *)&rspiocbp->wqe,
4319 			       MAX_MSG_DATA);
4320 			dev_warn(&((phba->pcidev)->dev),
4321 				 "lpfc%d: %s\n",
4322 				 phba->brd_no, adaptermsg);
4323 		} else {
4324 			/* Unknown command */
4325 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4326 					"0335 Unknown IOCB "
4327 					"command Data: x%x "
4328 					"x%x x%x x%x\n",
4329 					ulp_command,
4330 					ulp_status,
4331 					get_wqe_reqtag(rspiocbp),
4332 					get_job_ulpcontext(phba, rspiocbp));
4333 		}
4334 		break;
4335 	}
4336 
4337 	if (free_saveq) {
4338 		list_for_each_entry_safe(rspiocbp, next_iocb,
4339 					 &saveq->list, list) {
4340 			list_del_init(&rspiocbp->list);
4341 			__lpfc_sli_release_iocbq(phba, rspiocbp);
4342 		}
4343 		__lpfc_sli_release_iocbq(phba, saveq);
4344 	}
4345 	rspiocbp = NULL;
4346 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4347 	return rspiocbp;
4348 }
4349 
4350 /**
4351  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
4352  * @phba: Pointer to HBA context object.
4353  * @pring: Pointer to driver SLI ring object.
4354  * @mask: Host attention register mask for this ring.
4355  *
4356  * This routine wraps the actual slow_ring event process routine from the
4357  * API jump table function pointer from the lpfc_hba struct.
4358  **/
4359 void
4360 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
4361 				struct lpfc_sli_ring *pring, uint32_t mask)
4362 {
4363 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
4364 }
4365 
4366 /**
4367  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
4368  * @phba: Pointer to HBA context object.
4369  * @pring: Pointer to driver SLI ring object.
4370  * @mask: Host attention register mask for this ring.
4371  *
4372  * This function is called from the worker thread when there is a ring event
4373  * for non-fcp rings. The caller does not hold any lock. The function will
4374  * remove each response iocb in the response ring and calls the handle
4375  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4376  **/
4377 static void
4378 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
4379 				   struct lpfc_sli_ring *pring, uint32_t mask)
4380 {
4381 	struct lpfc_pgp *pgp;
4382 	IOCB_t *entry;
4383 	IOCB_t *irsp = NULL;
4384 	struct lpfc_iocbq *rspiocbp = NULL;
4385 	uint32_t portRspPut, portRspMax;
4386 	unsigned long iflag;
4387 	uint32_t status;
4388 
4389 	pgp = &phba->port_gp[pring->ringno];
4390 	spin_lock_irqsave(&phba->hbalock, iflag);
4391 	pring->stats.iocb_event++;
4392 
4393 	/*
4394 	 * The next available response entry should never exceed the maximum
4395 	 * entries.  If it does, treat it as an adapter hardware error.
4396 	 */
4397 	portRspMax = pring->sli.sli3.numRiocb;
4398 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4399 	if (portRspPut >= portRspMax) {
4400 		/*
4401 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
4402 		 * rsp ring <portRspMax>
4403 		 */
4404 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4405 				"0303 Ring %d handler: portRspPut %d "
4406 				"is bigger than rsp ring %d\n",
4407 				pring->ringno, portRspPut, portRspMax);
4408 
4409 		phba->link_state = LPFC_HBA_ERROR;
4410 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4411 
4412 		phba->work_hs = HS_FFER3;
4413 		lpfc_handle_eratt(phba);
4414 
4415 		return;
4416 	}
4417 
4418 	rmb();
4419 	while (pring->sli.sli3.rspidx != portRspPut) {
4420 		/*
4421 		 * Build a completion list and call the appropriate handler.
4422 		 * The process is to get the next available response iocb, get
4423 		 * a free iocb from the list, copy the response data into the
4424 		 * free iocb, insert to the continuation list, and update the
4425 		 * next response index to slim.  This process makes response
4426 		 * iocb's in the ring available to DMA as fast as possible but
4427 		 * pays a penalty for a copy operation.  Since the iocb is
4428 		 * only 32 bytes, this penalty is considered small relative to
4429 		 * the PCI reads for register values and a slim write.  When
4430 		 * the ulpLe field is set, the entire Command has been
4431 		 * received.
4432 		 */
4433 		entry = lpfc_resp_iocb(phba, pring);
4434 
4435 		phba->last_completion_time = jiffies;
4436 		rspiocbp = __lpfc_sli_get_iocbq(phba);
4437 		if (rspiocbp == NULL) {
4438 			printk(KERN_ERR "%s: out of buffers! Failing "
4439 			       "completion.\n", __func__);
4440 			break;
4441 		}
4442 
4443 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
4444 				      phba->iocb_rsp_size);
4445 		irsp = &rspiocbp->iocb;
4446 
4447 		if (++pring->sli.sli3.rspidx >= portRspMax)
4448 			pring->sli.sli3.rspidx = 0;
4449 
4450 		if (pring->ringno == LPFC_ELS_RING) {
4451 			lpfc_debugfs_slow_ring_trc(phba,
4452 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
4453 				*(((uint32_t *) irsp) + 4),
4454 				*(((uint32_t *) irsp) + 6),
4455 				*(((uint32_t *) irsp) + 7));
4456 		}
4457 
4458 		writel(pring->sli.sli3.rspidx,
4459 			&phba->host_gp[pring->ringno].rspGetInx);
4460 
4461 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4462 		/* Handle the response IOCB */
4463 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
4464 		spin_lock_irqsave(&phba->hbalock, iflag);
4465 
4466 		/*
4467 		 * If the port response put pointer has not been updated, sync
4468 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
4469 		 * response put pointer.
4470 		 */
4471 		if (pring->sli.sli3.rspidx == portRspPut) {
4472 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4473 		}
4474 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
4475 
4476 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
4477 		/* At least one response entry has been freed */
4478 		pring->stats.iocb_rsp_full++;
4479 		/* SET RxRE_RSP in Chip Att register */
4480 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4481 		writel(status, phba->CAregaddr);
4482 		readl(phba->CAregaddr); /* flush */
4483 	}
4484 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4485 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4486 		pring->stats.iocb_cmd_empty++;
4487 
4488 		/* Force update of the local copy of cmdGetInx */
4489 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4490 		lpfc_sli_resume_iocb(phba, pring);
4491 
4492 		if ((pring->lpfc_sli_cmd_available))
4493 			(pring->lpfc_sli_cmd_available) (phba, pring);
4494 
4495 	}
4496 
4497 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4498 	return;
4499 }
4500 
4501 /**
4502  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
4503  * @phba: Pointer to HBA context object.
4504  * @pring: Pointer to driver SLI ring object.
4505  * @mask: Host attention register mask for this ring.
4506  *
4507  * This function is called from the worker thread when there is a pending
4508  * ELS response iocb on the driver internal slow-path response iocb worker
4509  * queue. The caller does not hold any lock. The function will remove each
4510  * response iocb from the response worker queue and calls the handle
4511  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4512  **/
4513 static void
4514 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4515 				   struct lpfc_sli_ring *pring, uint32_t mask)
4516 {
4517 	struct lpfc_iocbq *irspiocbq;
4518 	struct hbq_dmabuf *dmabuf;
4519 	struct lpfc_cq_event *cq_event;
4520 	unsigned long iflag;
4521 	int count = 0;
4522 
4523 	clear_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
4524 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4525 		/* Get the response iocb from the head of work queue */
4526 		spin_lock_irqsave(&phba->hbalock, iflag);
4527 		list_remove_head(&phba->sli4_hba.sp_queue_event,
4528 				 cq_event, struct lpfc_cq_event, list);
4529 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4530 
4531 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4532 		case CQE_CODE_COMPL_WQE:
4533 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4534 						 cq_event);
4535 			/* Translate ELS WCQE to response IOCBQ */
4536 			irspiocbq = lpfc_sli4_els_preprocess_rspiocbq(phba,
4537 								      irspiocbq);
4538 			if (irspiocbq)
4539 				lpfc_sli_sp_handle_rspiocb(phba, pring,
4540 							   irspiocbq);
4541 			count++;
4542 			break;
4543 		case CQE_CODE_RECEIVE:
4544 		case CQE_CODE_RECEIVE_V1:
4545 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
4546 					      cq_event);
4547 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
4548 			count++;
4549 			break;
4550 		default:
4551 			break;
4552 		}
4553 
4554 		/* Limit the number of events to 64 to avoid soft lockups */
4555 		if (count == 64)
4556 			break;
4557 	}
4558 }
4559 
4560 /**
4561  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4562  * @phba: Pointer to HBA context object.
4563  * @pring: Pointer to driver SLI ring object.
4564  *
4565  * This function aborts all iocbs in the given ring and frees all the iocb
4566  * objects in txq. This function issues an abort iocb for all the iocb commands
4567  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4568  * the return of this function. The caller is not required to hold any locks.
4569  **/
4570 void
4571 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4572 {
4573 	LIST_HEAD(tx_completions);
4574 	LIST_HEAD(txcmplq_completions);
4575 	struct lpfc_iocbq *iocb, *next_iocb;
4576 	int offline;
4577 
4578 	if (pring->ringno == LPFC_ELS_RING) {
4579 		lpfc_fabric_abort_hba(phba);
4580 	}
4581 	offline = pci_channel_offline(phba->pcidev);
4582 
4583 	/* Error everything on txq and txcmplq
4584 	 * First do the txq.
4585 	 */
4586 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4587 		spin_lock_irq(&pring->ring_lock);
4588 		list_splice_init(&pring->txq, &tx_completions);
4589 		pring->txq_cnt = 0;
4590 
4591 		if (offline) {
4592 			list_splice_init(&pring->txcmplq,
4593 					 &txcmplq_completions);
4594 		} else {
4595 			/* Next issue ABTS for everything on the txcmplq */
4596 			list_for_each_entry_safe(iocb, next_iocb,
4597 						 &pring->txcmplq, list)
4598 				lpfc_sli_issue_abort_iotag(phba, pring,
4599 							   iocb, NULL);
4600 		}
4601 		spin_unlock_irq(&pring->ring_lock);
4602 	} else {
4603 		spin_lock_irq(&phba->hbalock);
4604 		list_splice_init(&pring->txq, &tx_completions);
4605 		pring->txq_cnt = 0;
4606 
4607 		if (offline) {
4608 			list_splice_init(&pring->txcmplq, &txcmplq_completions);
4609 		} else {
4610 			/* Next issue ABTS for everything on the txcmplq */
4611 			list_for_each_entry_safe(iocb, next_iocb,
4612 						 &pring->txcmplq, list)
4613 				lpfc_sli_issue_abort_iotag(phba, pring,
4614 							   iocb, NULL);
4615 		}
4616 		spin_unlock_irq(&phba->hbalock);
4617 	}
4618 
4619 	if (offline) {
4620 		/* Cancel all the IOCBs from the completions list */
4621 		lpfc_sli_cancel_iocbs(phba, &txcmplq_completions,
4622 				      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
4623 	} else {
4624 		/* Make sure HBA is alive */
4625 		lpfc_issue_hb_tmo(phba);
4626 	}
4627 	/* Cancel all the IOCBs from the completions list */
4628 	lpfc_sli_cancel_iocbs(phba, &tx_completions, IOSTAT_LOCAL_REJECT,
4629 			      IOERR_SLI_ABORTED);
4630 }
4631 
4632 /**
4633  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4634  * @phba: Pointer to HBA context object.
4635  *
4636  * This function aborts all iocbs in FCP rings and frees all the iocb
4637  * objects in txq. This function issues an abort iocb for all the iocb commands
4638  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4639  * the return of this function. The caller is not required to hold any locks.
4640  **/
4641 void
4642 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4643 {
4644 	struct lpfc_sli *psli = &phba->sli;
4645 	struct lpfc_sli_ring  *pring;
4646 	uint32_t i;
4647 
4648 	/* Look on all the FCP Rings for the iotag */
4649 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4650 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4651 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4652 			lpfc_sli_abort_iocb_ring(phba, pring);
4653 		}
4654 	} else {
4655 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4656 		lpfc_sli_abort_iocb_ring(phba, pring);
4657 	}
4658 }
4659 
4660 /**
4661  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4662  * @phba: Pointer to HBA context object.
4663  *
4664  * This function flushes all iocbs in the IO ring and frees all the iocb
4665  * objects in txq and txcmplq. This function will not issue abort iocbs
4666  * for all the iocb commands in txcmplq, they will just be returned with
4667  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4668  * slot has been permanently disabled.
4669  **/
4670 void
4671 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4672 {
4673 	LIST_HEAD(txq);
4674 	LIST_HEAD(txcmplq);
4675 	struct lpfc_sli *psli = &phba->sli;
4676 	struct lpfc_sli_ring  *pring;
4677 	uint32_t i;
4678 	struct lpfc_iocbq *piocb, *next_iocb;
4679 
4680 	/* Indicate the I/O queues are flushed */
4681 	set_bit(HBA_IOQ_FLUSH, &phba->hba_flag);
4682 
4683 	/* Look on all the FCP Rings for the iotag */
4684 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4685 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4686 			if (!phba->sli4_hba.hdwq ||
4687 			    !phba->sli4_hba.hdwq[i].io_wq) {
4688 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4689 						"7777 hdwq's deleted %lx "
4690 						"%lx %x %x\n",
4691 						phba->pport->load_flag,
4692 						phba->hba_flag,
4693 						phba->link_state,
4694 						phba->sli.sli_flag);
4695 				return;
4696 			}
4697 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4698 
4699 			spin_lock_irq(&pring->ring_lock);
4700 			/* Retrieve everything on txq */
4701 			list_splice_init(&pring->txq, &txq);
4702 			list_for_each_entry_safe(piocb, next_iocb,
4703 						 &pring->txcmplq, list)
4704 				piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4705 			/* Retrieve everything on the txcmplq */
4706 			list_splice_init(&pring->txcmplq, &txcmplq);
4707 			pring->txq_cnt = 0;
4708 			pring->txcmplq_cnt = 0;
4709 			spin_unlock_irq(&pring->ring_lock);
4710 
4711 			/* Flush the txq */
4712 			lpfc_sli_cancel_iocbs(phba, &txq,
4713 					      IOSTAT_LOCAL_REJECT,
4714 					      IOERR_SLI_DOWN);
4715 			/* Flush the txcmplq */
4716 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4717 					      IOSTAT_LOCAL_REJECT,
4718 					      IOERR_SLI_DOWN);
4719 			if (unlikely(pci_channel_offline(phba->pcidev)))
4720 				lpfc_sli4_io_xri_aborted(phba, NULL, 0);
4721 		}
4722 	} else {
4723 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4724 
4725 		spin_lock_irq(&phba->hbalock);
4726 		/* Retrieve everything on txq */
4727 		list_splice_init(&pring->txq, &txq);
4728 		list_for_each_entry_safe(piocb, next_iocb,
4729 					 &pring->txcmplq, list)
4730 			piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4731 		/* Retrieve everything on the txcmplq */
4732 		list_splice_init(&pring->txcmplq, &txcmplq);
4733 		pring->txq_cnt = 0;
4734 		pring->txcmplq_cnt = 0;
4735 		spin_unlock_irq(&phba->hbalock);
4736 
4737 		/* Flush the txq */
4738 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4739 				      IOERR_SLI_DOWN);
4740 		/* Flush the txcmpq */
4741 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4742 				      IOERR_SLI_DOWN);
4743 	}
4744 }
4745 
4746 /**
4747  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4748  * @phba: Pointer to HBA context object.
4749  * @mask: Bit mask to be checked.
4750  *
4751  * This function reads the host status register and compares
4752  * with the provided bit mask to check if HBA completed
4753  * the restart. This function will wait in a loop for the
4754  * HBA to complete restart. If the HBA does not restart within
4755  * 15 iterations, the function will reset the HBA again. The
4756  * function returns 1 when HBA fail to restart otherwise returns
4757  * zero.
4758  **/
4759 static int
4760 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4761 {
4762 	uint32_t status;
4763 	int i = 0;
4764 	int retval = 0;
4765 
4766 	/* Read the HBA Host Status Register */
4767 	if (lpfc_readl(phba->HSregaddr, &status))
4768 		return 1;
4769 
4770 	set_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
4771 
4772 	/*
4773 	 * Check status register every 100ms for 5 retries, then every
4774 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4775 	 * every 2.5 sec for 4.
4776 	 * Break our of the loop if errors occurred during init.
4777 	 */
4778 	while (((status & mask) != mask) &&
4779 	       !(status & HS_FFERM) &&
4780 	       i++ < 20) {
4781 
4782 		if (i <= 5)
4783 			msleep(10);
4784 		else if (i <= 10)
4785 			msleep(500);
4786 		else
4787 			msleep(2500);
4788 
4789 		if (i == 15) {
4790 				/* Do post */
4791 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4792 			lpfc_sli_brdrestart(phba);
4793 		}
4794 		/* Read the HBA Host Status Register */
4795 		if (lpfc_readl(phba->HSregaddr, &status)) {
4796 			retval = 1;
4797 			break;
4798 		}
4799 	}
4800 
4801 	/* Check to see if any errors occurred during init */
4802 	if ((status & HS_FFERM) || (i >= 20)) {
4803 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4804 				"2751 Adapter failed to restart, "
4805 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4806 				status,
4807 				readl(phba->MBslimaddr + 0xa8),
4808 				readl(phba->MBslimaddr + 0xac));
4809 		phba->link_state = LPFC_HBA_ERROR;
4810 		retval = 1;
4811 	}
4812 
4813 	return retval;
4814 }
4815 
4816 /**
4817  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4818  * @phba: Pointer to HBA context object.
4819  * @mask: Bit mask to be checked.
4820  *
4821  * This function checks the host status register to check if HBA is
4822  * ready. This function will wait in a loop for the HBA to be ready
4823  * If the HBA is not ready , the function will will reset the HBA PCI
4824  * function again. The function returns 1 when HBA fail to be ready
4825  * otherwise returns zero.
4826  **/
4827 static int
4828 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4829 {
4830 	uint32_t status;
4831 	int retval = 0;
4832 
4833 	/* Read the HBA Host Status Register */
4834 	status = lpfc_sli4_post_status_check(phba);
4835 
4836 	if (status) {
4837 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4838 		lpfc_sli_brdrestart(phba);
4839 		status = lpfc_sli4_post_status_check(phba);
4840 	}
4841 
4842 	/* Check to see if any errors occurred during init */
4843 	if (status) {
4844 		phba->link_state = LPFC_HBA_ERROR;
4845 		retval = 1;
4846 	} else
4847 		phba->sli4_hba.intr_enable = 0;
4848 
4849 	clear_bit(HBA_SETUP, &phba->hba_flag);
4850 	return retval;
4851 }
4852 
4853 /**
4854  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4855  * @phba: Pointer to HBA context object.
4856  * @mask: Bit mask to be checked.
4857  *
4858  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4859  * from the API jump table function pointer from the lpfc_hba struct.
4860  **/
4861 int
4862 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4863 {
4864 	return phba->lpfc_sli_brdready(phba, mask);
4865 }
4866 
4867 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4868 
4869 /**
4870  * lpfc_reset_barrier - Make HBA ready for HBA reset
4871  * @phba: Pointer to HBA context object.
4872  *
4873  * This function is called before resetting an HBA. This function is called
4874  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4875  **/
4876 void lpfc_reset_barrier(struct lpfc_hba *phba)
4877 {
4878 	uint32_t __iomem *resp_buf;
4879 	uint32_t __iomem *mbox_buf;
4880 	volatile struct MAILBOX_word0 mbox;
4881 	uint32_t hc_copy, ha_copy, resp_data;
4882 	int  i;
4883 	uint8_t hdrtype;
4884 
4885 	lockdep_assert_held(&phba->hbalock);
4886 
4887 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4888 	if (hdrtype != PCI_HEADER_TYPE_MFD ||
4889 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4890 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4891 		return;
4892 
4893 	/*
4894 	 * Tell the other part of the chip to suspend temporarily all
4895 	 * its DMA activity.
4896 	 */
4897 	resp_buf = phba->MBslimaddr;
4898 
4899 	/* Disable the error attention */
4900 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4901 		return;
4902 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4903 	readl(phba->HCregaddr); /* flush */
4904 	phba->link_flag |= LS_IGNORE_ERATT;
4905 
4906 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4907 		return;
4908 	if (ha_copy & HA_ERATT) {
4909 		/* Clear Chip error bit */
4910 		writel(HA_ERATT, phba->HAregaddr);
4911 		phba->pport->stopped = 1;
4912 	}
4913 
4914 	mbox.word0 = 0;
4915 	mbox.mbxCommand = MBX_KILL_BOARD;
4916 	mbox.mbxOwner = OWN_CHIP;
4917 
4918 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4919 	mbox_buf = phba->MBslimaddr;
4920 	writel(mbox.word0, mbox_buf);
4921 
4922 	for (i = 0; i < 50; i++) {
4923 		if (lpfc_readl((resp_buf + 1), &resp_data))
4924 			return;
4925 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4926 			mdelay(1);
4927 		else
4928 			break;
4929 	}
4930 	resp_data = 0;
4931 	if (lpfc_readl((resp_buf + 1), &resp_data))
4932 		return;
4933 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4934 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4935 		    phba->pport->stopped)
4936 			goto restore_hc;
4937 		else
4938 			goto clear_errat;
4939 	}
4940 
4941 	mbox.mbxOwner = OWN_HOST;
4942 	resp_data = 0;
4943 	for (i = 0; i < 500; i++) {
4944 		if (lpfc_readl(resp_buf, &resp_data))
4945 			return;
4946 		if (resp_data != mbox.word0)
4947 			mdelay(1);
4948 		else
4949 			break;
4950 	}
4951 
4952 clear_errat:
4953 
4954 	while (++i < 500) {
4955 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4956 			return;
4957 		if (!(ha_copy & HA_ERATT))
4958 			mdelay(1);
4959 		else
4960 			break;
4961 	}
4962 
4963 	if (readl(phba->HAregaddr) & HA_ERATT) {
4964 		writel(HA_ERATT, phba->HAregaddr);
4965 		phba->pport->stopped = 1;
4966 	}
4967 
4968 restore_hc:
4969 	phba->link_flag &= ~LS_IGNORE_ERATT;
4970 	writel(hc_copy, phba->HCregaddr);
4971 	readl(phba->HCregaddr); /* flush */
4972 }
4973 
4974 /**
4975  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4976  * @phba: Pointer to HBA context object.
4977  *
4978  * This function issues a kill_board mailbox command and waits for
4979  * the error attention interrupt. This function is called for stopping
4980  * the firmware processing. The caller is not required to hold any
4981  * locks. This function calls lpfc_hba_down_post function to free
4982  * any pending commands after the kill. The function will return 1 when it
4983  * fails to kill the board else will return 0.
4984  **/
4985 int
4986 lpfc_sli_brdkill(struct lpfc_hba *phba)
4987 {
4988 	struct lpfc_sli *psli;
4989 	LPFC_MBOXQ_t *pmb;
4990 	uint32_t status;
4991 	uint32_t ha_copy;
4992 	int retval;
4993 	int i = 0;
4994 
4995 	psli = &phba->sli;
4996 
4997 	/* Kill HBA */
4998 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4999 			"0329 Kill HBA Data: x%x x%x\n",
5000 			phba->pport->port_state, psli->sli_flag);
5001 
5002 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5003 	if (!pmb)
5004 		return 1;
5005 
5006 	/* Disable the error attention */
5007 	spin_lock_irq(&phba->hbalock);
5008 	if (lpfc_readl(phba->HCregaddr, &status)) {
5009 		spin_unlock_irq(&phba->hbalock);
5010 		mempool_free(pmb, phba->mbox_mem_pool);
5011 		return 1;
5012 	}
5013 	status &= ~HC_ERINT_ENA;
5014 	writel(status, phba->HCregaddr);
5015 	readl(phba->HCregaddr); /* flush */
5016 	phba->link_flag |= LS_IGNORE_ERATT;
5017 	spin_unlock_irq(&phba->hbalock);
5018 
5019 	lpfc_kill_board(phba, pmb);
5020 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
5021 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5022 
5023 	if (retval != MBX_SUCCESS) {
5024 		if (retval != MBX_BUSY)
5025 			mempool_free(pmb, phba->mbox_mem_pool);
5026 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5027 				"2752 KILL_BOARD command failed retval %d\n",
5028 				retval);
5029 		spin_lock_irq(&phba->hbalock);
5030 		phba->link_flag &= ~LS_IGNORE_ERATT;
5031 		spin_unlock_irq(&phba->hbalock);
5032 		return 1;
5033 	}
5034 
5035 	spin_lock_irq(&phba->hbalock);
5036 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
5037 	spin_unlock_irq(&phba->hbalock);
5038 
5039 	mempool_free(pmb, phba->mbox_mem_pool);
5040 
5041 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
5042 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
5043 	 * 3 seconds we still set HBA_ERROR state because the status of the
5044 	 * board is now undefined.
5045 	 */
5046 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
5047 		return 1;
5048 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
5049 		mdelay(100);
5050 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
5051 			return 1;
5052 	}
5053 
5054 	timer_delete_sync(&psli->mbox_tmo);
5055 	if (ha_copy & HA_ERATT) {
5056 		writel(HA_ERATT, phba->HAregaddr);
5057 		phba->pport->stopped = 1;
5058 	}
5059 	spin_lock_irq(&phba->hbalock);
5060 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5061 	psli->mbox_active = NULL;
5062 	phba->link_flag &= ~LS_IGNORE_ERATT;
5063 	spin_unlock_irq(&phba->hbalock);
5064 
5065 	lpfc_hba_down_post(phba);
5066 	phba->link_state = LPFC_HBA_ERROR;
5067 
5068 	return ha_copy & HA_ERATT ? 0 : 1;
5069 }
5070 
5071 /**
5072  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
5073  * @phba: Pointer to HBA context object.
5074  *
5075  * This function resets the HBA by writing HC_INITFF to the control
5076  * register. After the HBA resets, this function resets all the iocb ring
5077  * indices. This function disables PCI layer parity checking during
5078  * the reset.
5079  * This function returns 0 always.
5080  * The caller is not required to hold any locks.
5081  **/
5082 int
5083 lpfc_sli_brdreset(struct lpfc_hba *phba)
5084 {
5085 	struct lpfc_sli *psli;
5086 	struct lpfc_sli_ring *pring;
5087 	uint16_t cfg_value;
5088 	int i;
5089 
5090 	psli = &phba->sli;
5091 
5092 	/* Reset HBA */
5093 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5094 			"0325 Reset HBA Data: x%x x%x\n",
5095 			(phba->pport) ? phba->pport->port_state : 0,
5096 			psli->sli_flag);
5097 
5098 	/* perform board reset */
5099 	phba->fc_eventTag = 0;
5100 	phba->link_events = 0;
5101 	set_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
5102 	if (phba->pport) {
5103 		phba->pport->fc_myDID = 0;
5104 		phba->pport->fc_prevDID = 0;
5105 	}
5106 
5107 	/* Turn off parity checking and serr during the physical reset */
5108 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
5109 		return -EIO;
5110 
5111 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
5112 			      (cfg_value &
5113 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5114 
5115 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
5116 
5117 	/* Now toggle INITFF bit in the Host Control Register */
5118 	writel(HC_INITFF, phba->HCregaddr);
5119 	mdelay(1);
5120 	readl(phba->HCregaddr); /* flush */
5121 	writel(0, phba->HCregaddr);
5122 	readl(phba->HCregaddr); /* flush */
5123 
5124 	/* Restore PCI cmd register */
5125 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5126 
5127 	/* Initialize relevant SLI info */
5128 	for (i = 0; i < psli->num_rings; i++) {
5129 		pring = &psli->sli3_ring[i];
5130 		pring->flag = 0;
5131 		pring->sli.sli3.rspidx = 0;
5132 		pring->sli.sli3.next_cmdidx  = 0;
5133 		pring->sli.sli3.local_getidx = 0;
5134 		pring->sli.sli3.cmdidx = 0;
5135 		pring->missbufcnt = 0;
5136 	}
5137 
5138 	phba->link_state = LPFC_WARM_START;
5139 	return 0;
5140 }
5141 
5142 /**
5143  * lpfc_sli4_brdreset - Reset a sli-4 HBA
5144  * @phba: Pointer to HBA context object.
5145  *
5146  * This function resets a SLI4 HBA. This function disables PCI layer parity
5147  * checking during resets the device. The caller is not required to hold
5148  * any locks.
5149  *
5150  * This function returns 0 on success else returns negative error code.
5151  **/
5152 int
5153 lpfc_sli4_brdreset(struct lpfc_hba *phba)
5154 {
5155 	struct lpfc_sli *psli = &phba->sli;
5156 	uint16_t cfg_value;
5157 	int rc = 0;
5158 
5159 	/* Reset HBA */
5160 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5161 			"0295 Reset HBA Data: x%x x%x x%lx\n",
5162 			phba->pport->port_state, psli->sli_flag,
5163 			phba->hba_flag);
5164 
5165 	/* perform board reset */
5166 	phba->fc_eventTag = 0;
5167 	phba->link_events = 0;
5168 	phba->pport->fc_myDID = 0;
5169 	phba->pport->fc_prevDID = 0;
5170 
5171 	spin_lock_irq(&phba->hbalock);
5172 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
5173 	phba->fcf.fcf_flag = 0;
5174 	spin_unlock_irq(&phba->hbalock);
5175 
5176 	/* Now physically reset the device */
5177 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5178 			"0389 Performing PCI function reset!\n");
5179 
5180 	/* Turn off parity checking and serr during the physical reset */
5181 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
5182 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5183 				"3205 PCI read Config failed\n");
5184 		return -EIO;
5185 	}
5186 
5187 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
5188 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5189 
5190 	/* Perform FCoE PCI function reset before freeing queue memory */
5191 	rc = lpfc_pci_function_reset(phba);
5192 
5193 	/* Restore PCI cmd register */
5194 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5195 
5196 	return rc;
5197 }
5198 
5199 /**
5200  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
5201  * @phba: Pointer to HBA context object.
5202  *
5203  * This function is called in the SLI initialization code path to
5204  * restart the HBA. The caller is not required to hold any lock.
5205  * This function writes MBX_RESTART mailbox command to the SLIM and
5206  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
5207  * function to free any pending commands. The function enables
5208  * POST only during the first initialization. The function returns zero.
5209  * The function does not guarantee completion of MBX_RESTART mailbox
5210  * command before the return of this function.
5211  **/
5212 static int
5213 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
5214 {
5215 	volatile struct MAILBOX_word0 mb;
5216 	struct lpfc_sli *psli;
5217 	void __iomem *to_slim;
5218 
5219 	spin_lock_irq(&phba->hbalock);
5220 
5221 	psli = &phba->sli;
5222 
5223 	/* Restart HBA */
5224 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5225 			"0337 Restart HBA Data: x%x x%x\n",
5226 			(phba->pport) ? phba->pport->port_state : 0,
5227 			psli->sli_flag);
5228 
5229 	mb.word0 = 0;
5230 	mb.mbxCommand = MBX_RESTART;
5231 	mb.mbxHc = 1;
5232 
5233 	lpfc_reset_barrier(phba);
5234 
5235 	to_slim = phba->MBslimaddr;
5236 	writel(mb.word0, to_slim);
5237 	readl(to_slim); /* flush */
5238 
5239 	/* Only skip post after fc_ffinit is completed */
5240 	if (phba->pport && phba->pport->port_state)
5241 		mb.word0 = 1;	/* This is really setting up word1 */
5242 	else
5243 		mb.word0 = 0;	/* This is really setting up word1 */
5244 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
5245 	writel(mb.word0, to_slim);
5246 	readl(to_slim); /* flush */
5247 
5248 	lpfc_sli_brdreset(phba);
5249 	if (phba->pport)
5250 		phba->pport->stopped = 0;
5251 	phba->link_state = LPFC_INIT_START;
5252 	phba->hba_flag = 0;
5253 	spin_unlock_irq(&phba->hbalock);
5254 
5255 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5256 	psli->stats_start = ktime_get_seconds();
5257 
5258 	/* Give the INITFF and Post time to settle. */
5259 	mdelay(100);
5260 
5261 	lpfc_hba_down_post(phba);
5262 
5263 	return 0;
5264 }
5265 
5266 /**
5267  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
5268  * @phba: Pointer to HBA context object.
5269  *
5270  * This function is called in the SLI initialization code path to restart
5271  * a SLI4 HBA. The caller is not required to hold any lock.
5272  * At the end of the function, it calls lpfc_hba_down_post function to
5273  * free any pending commands.
5274  **/
5275 static int
5276 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
5277 {
5278 	struct lpfc_sli *psli = &phba->sli;
5279 	int rc;
5280 
5281 	/* Restart HBA */
5282 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5283 			"0296 Restart HBA Data: x%x x%x\n",
5284 			phba->pport->port_state, psli->sli_flag);
5285 
5286 	clear_bit(HBA_SETUP, &phba->hba_flag);
5287 	lpfc_sli4_queue_unset(phba);
5288 
5289 	rc = lpfc_sli4_brdreset(phba);
5290 	if (rc) {
5291 		phba->link_state = LPFC_HBA_ERROR;
5292 		goto hba_down_queue;
5293 	}
5294 
5295 	spin_lock_irq(&phba->hbalock);
5296 	phba->pport->stopped = 0;
5297 	phba->link_state = LPFC_INIT_START;
5298 	phba->hba_flag = 0;
5299 	/* Preserve FA-PWWN expectation */
5300 	phba->sli4_hba.fawwpn_flag &= LPFC_FAWWPN_FABRIC;
5301 	spin_unlock_irq(&phba->hbalock);
5302 
5303 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5304 	psli->stats_start = ktime_get_seconds();
5305 
5306 hba_down_queue:
5307 	lpfc_hba_down_post(phba);
5308 	lpfc_sli4_queue_destroy(phba);
5309 
5310 	return rc;
5311 }
5312 
5313 /**
5314  * lpfc_sli_brdrestart - Wrapper func for restarting hba
5315  * @phba: Pointer to HBA context object.
5316  *
5317  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
5318  * API jump table function pointer from the lpfc_hba struct.
5319 **/
5320 int
5321 lpfc_sli_brdrestart(struct lpfc_hba *phba)
5322 {
5323 	return phba->lpfc_sli_brdrestart(phba);
5324 }
5325 
5326 /**
5327  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
5328  * @phba: Pointer to HBA context object.
5329  *
5330  * This function is called after a HBA restart to wait for successful
5331  * restart of the HBA. Successful restart of the HBA is indicated by
5332  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
5333  * iteration, the function will restart the HBA again. The function returns
5334  * zero if HBA successfully restarted else returns negative error code.
5335  **/
5336 int
5337 lpfc_sli_chipset_init(struct lpfc_hba *phba)
5338 {
5339 	uint32_t status, i = 0;
5340 
5341 	/* Read the HBA Host Status Register */
5342 	if (lpfc_readl(phba->HSregaddr, &status))
5343 		return -EIO;
5344 
5345 	/* Check status register to see what current state is */
5346 	i = 0;
5347 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
5348 
5349 		/* Check every 10ms for 10 retries, then every 100ms for 90
5350 		 * retries, then every 1 sec for 50 retires for a total of
5351 		 * ~60 seconds before reset the board again and check every
5352 		 * 1 sec for 50 retries. The up to 60 seconds before the
5353 		 * board ready is required by the Falcon FIPS zeroization
5354 		 * complete, and any reset the board in between shall cause
5355 		 * restart of zeroization, further delay the board ready.
5356 		 */
5357 		if (i++ >= 200) {
5358 			/* Adapter failed to init, timeout, status reg
5359 			   <status> */
5360 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5361 					"0436 Adapter failed to init, "
5362 					"timeout, status reg x%x, "
5363 					"FW Data: A8 x%x AC x%x\n", status,
5364 					readl(phba->MBslimaddr + 0xa8),
5365 					readl(phba->MBslimaddr + 0xac));
5366 			phba->link_state = LPFC_HBA_ERROR;
5367 			return -ETIMEDOUT;
5368 		}
5369 
5370 		/* Check to see if any errors occurred during init */
5371 		if (status & HS_FFERM) {
5372 			/* ERROR: During chipset initialization */
5373 			/* Adapter failed to init, chipset, status reg
5374 			   <status> */
5375 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5376 					"0437 Adapter failed to init, "
5377 					"chipset, status reg x%x, "
5378 					"FW Data: A8 x%x AC x%x\n", status,
5379 					readl(phba->MBslimaddr + 0xa8),
5380 					readl(phba->MBslimaddr + 0xac));
5381 			phba->link_state = LPFC_HBA_ERROR;
5382 			return -EIO;
5383 		}
5384 
5385 		if (i <= 10)
5386 			msleep(10);
5387 		else if (i <= 100)
5388 			msleep(100);
5389 		else
5390 			msleep(1000);
5391 
5392 		if (i == 150) {
5393 			/* Do post */
5394 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5395 			lpfc_sli_brdrestart(phba);
5396 		}
5397 		/* Read the HBA Host Status Register */
5398 		if (lpfc_readl(phba->HSregaddr, &status))
5399 			return -EIO;
5400 	}
5401 
5402 	/* Check to see if any errors occurred during init */
5403 	if (status & HS_FFERM) {
5404 		/* ERROR: During chipset initialization */
5405 		/* Adapter failed to init, chipset, status reg <status> */
5406 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5407 				"0438 Adapter failed to init, chipset, "
5408 				"status reg x%x, "
5409 				"FW Data: A8 x%x AC x%x\n", status,
5410 				readl(phba->MBslimaddr + 0xa8),
5411 				readl(phba->MBslimaddr + 0xac));
5412 		phba->link_state = LPFC_HBA_ERROR;
5413 		return -EIO;
5414 	}
5415 
5416 	set_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
5417 
5418 	/* Clear all interrupt enable conditions */
5419 	writel(0, phba->HCregaddr);
5420 	readl(phba->HCregaddr); /* flush */
5421 
5422 	/* setup host attn register */
5423 	writel(0xffffffff, phba->HAregaddr);
5424 	readl(phba->HAregaddr); /* flush */
5425 	return 0;
5426 }
5427 
5428 /**
5429  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5430  *
5431  * This function calculates and returns the number of HBQs required to be
5432  * configured.
5433  **/
5434 int
5435 lpfc_sli_hbq_count(void)
5436 {
5437 	return ARRAY_SIZE(lpfc_hbq_defs);
5438 }
5439 
5440 /**
5441  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5442  *
5443  * This function adds the number of hbq entries in every HBQ to get
5444  * the total number of hbq entries required for the HBA and returns
5445  * the total count.
5446  **/
5447 static int
5448 lpfc_sli_hbq_entry_count(void)
5449 {
5450 	int  hbq_count = lpfc_sli_hbq_count();
5451 	int  count = 0;
5452 	int  i;
5453 
5454 	for (i = 0; i < hbq_count; ++i)
5455 		count += lpfc_hbq_defs[i]->entry_count;
5456 	return count;
5457 }
5458 
5459 /**
5460  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5461  *
5462  * This function calculates amount of memory required for all hbq entries
5463  * to be configured and returns the total memory required.
5464  **/
5465 int
5466 lpfc_sli_hbq_size(void)
5467 {
5468 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5469 }
5470 
5471 /**
5472  * lpfc_sli_hbq_setup - configure and initialize HBQs
5473  * @phba: Pointer to HBA context object.
5474  *
5475  * This function is called during the SLI initialization to configure
5476  * all the HBQs and post buffers to the HBQ. The caller is not
5477  * required to hold any locks. This function will return zero if successful
5478  * else it will return negative error code.
5479  **/
5480 static int
5481 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5482 {
5483 	int  hbq_count = lpfc_sli_hbq_count();
5484 	LPFC_MBOXQ_t *pmb;
5485 	MAILBOX_t *pmbox;
5486 	uint32_t hbqno;
5487 	uint32_t hbq_entry_index;
5488 
5489 				/* Get a Mailbox buffer to setup mailbox
5490 				 * commands for HBA initialization
5491 				 */
5492 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5493 
5494 	if (!pmb)
5495 		return -ENOMEM;
5496 
5497 	pmbox = &pmb->u.mb;
5498 
5499 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
5500 	phba->link_state = LPFC_INIT_MBX_CMDS;
5501 	phba->hbq_in_use = 1;
5502 
5503 	hbq_entry_index = 0;
5504 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5505 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
5506 		phba->hbqs[hbqno].hbqPutIdx      = 0;
5507 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5508 		phba->hbqs[hbqno].entry_count =
5509 			lpfc_hbq_defs[hbqno]->entry_count;
5510 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5511 			hbq_entry_index, pmb);
5512 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
5513 
5514 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5515 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5516 			   mbxStatus <status>, ring <num> */
5517 
5518 			lpfc_printf_log(phba, KERN_ERR,
5519 					LOG_SLI | LOG_VPORT,
5520 					"1805 Adapter failed to init. "
5521 					"Data: x%x x%x x%x\n",
5522 					pmbox->mbxCommand,
5523 					pmbox->mbxStatus, hbqno);
5524 
5525 			phba->link_state = LPFC_HBA_ERROR;
5526 			mempool_free(pmb, phba->mbox_mem_pool);
5527 			return -ENXIO;
5528 		}
5529 	}
5530 	phba->hbq_count = hbq_count;
5531 
5532 	mempool_free(pmb, phba->mbox_mem_pool);
5533 
5534 	/* Initially populate or replenish the HBQs */
5535 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5536 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5537 	return 0;
5538 }
5539 
5540 /**
5541  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5542  * @phba: Pointer to HBA context object.
5543  *
5544  * This function is called during the SLI initialization to configure
5545  * all the HBQs and post buffers to the HBQ. The caller is not
5546  * required to hold any locks. This function will return zero if successful
5547  * else it will return negative error code.
5548  **/
5549 static int
5550 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5551 {
5552 	phba->hbq_in_use = 1;
5553 	/**
5554 	 * Specific case when the MDS diagnostics is enabled and supported.
5555 	 * The receive buffer count is truncated to manage the incoming
5556 	 * traffic.
5557 	 **/
5558 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5559 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5560 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5561 	else
5562 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5563 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5564 	phba->hbq_count = 1;
5565 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5566 	/* Initially populate or replenish the HBQs */
5567 	return 0;
5568 }
5569 
5570 /**
5571  * lpfc_sli_config_port - Issue config port mailbox command
5572  * @phba: Pointer to HBA context object.
5573  * @sli_mode: sli mode - 2/3
5574  *
5575  * This function is called by the sli initialization code path
5576  * to issue config_port mailbox command. This function restarts the
5577  * HBA firmware and issues a config_port mailbox command to configure
5578  * the SLI interface in the sli mode specified by sli_mode
5579  * variable. The caller is not required to hold any locks.
5580  * The function returns 0 if successful, else returns negative error
5581  * code.
5582  **/
5583 int
5584 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5585 {
5586 	LPFC_MBOXQ_t *pmb;
5587 	uint32_t resetcount = 0, rc = 0, done = 0;
5588 
5589 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5590 	if (!pmb) {
5591 		phba->link_state = LPFC_HBA_ERROR;
5592 		return -ENOMEM;
5593 	}
5594 
5595 	phba->sli_rev = sli_mode;
5596 	while (resetcount < 2 && !done) {
5597 		spin_lock_irq(&phba->hbalock);
5598 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5599 		spin_unlock_irq(&phba->hbalock);
5600 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5601 		lpfc_sli_brdrestart(phba);
5602 		rc = lpfc_sli_chipset_init(phba);
5603 		if (rc)
5604 			break;
5605 
5606 		spin_lock_irq(&phba->hbalock);
5607 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5608 		spin_unlock_irq(&phba->hbalock);
5609 		resetcount++;
5610 
5611 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5612 		 * value of 0 means the call was successful.  Any other
5613 		 * nonzero value is a failure, but if ERESTART is returned,
5614 		 * the driver may reset the HBA and try again.
5615 		 */
5616 		rc = lpfc_config_port_prep(phba);
5617 		if (rc == -ERESTART) {
5618 			phba->link_state = LPFC_LINK_UNKNOWN;
5619 			continue;
5620 		} else if (rc)
5621 			break;
5622 
5623 		phba->link_state = LPFC_INIT_MBX_CMDS;
5624 		lpfc_config_port(phba, pmb);
5625 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5626 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5627 					LPFC_SLI3_HBQ_ENABLED |
5628 					LPFC_SLI3_CRP_ENABLED |
5629 					LPFC_SLI3_DSS_ENABLED);
5630 		if (rc != MBX_SUCCESS) {
5631 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5632 				"0442 Adapter failed to init, mbxCmd x%x "
5633 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5634 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5635 			spin_lock_irq(&phba->hbalock);
5636 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5637 			spin_unlock_irq(&phba->hbalock);
5638 			rc = -ENXIO;
5639 		} else {
5640 			/* Allow asynchronous mailbox command to go through */
5641 			spin_lock_irq(&phba->hbalock);
5642 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5643 			spin_unlock_irq(&phba->hbalock);
5644 			done = 1;
5645 
5646 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5647 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5648 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5649 					"3110 Port did not grant ASABT\n");
5650 		}
5651 	}
5652 	if (!done) {
5653 		rc = -EINVAL;
5654 		goto do_prep_failed;
5655 	}
5656 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5657 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5658 			rc = -ENXIO;
5659 			goto do_prep_failed;
5660 		}
5661 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5662 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5663 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5664 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5665 				phba->max_vpi : phba->max_vports;
5666 
5667 		} else
5668 			phba->max_vpi = 0;
5669 		if (pmb->u.mb.un.varCfgPort.gerbm)
5670 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5671 		if (pmb->u.mb.un.varCfgPort.gcrp)
5672 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5673 
5674 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5675 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5676 
5677 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5678 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5679 				phba->cfg_enable_bg = 0;
5680 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5681 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5682 						"0443 Adapter did not grant "
5683 						"BlockGuard\n");
5684 			}
5685 		}
5686 	} else {
5687 		phba->hbq_get = NULL;
5688 		phba->port_gp = phba->mbox->us.s2.port;
5689 		phba->max_vpi = 0;
5690 	}
5691 do_prep_failed:
5692 	mempool_free(pmb, phba->mbox_mem_pool);
5693 	return rc;
5694 }
5695 
5696 
5697 /**
5698  * lpfc_sli_hba_setup - SLI initialization function
5699  * @phba: Pointer to HBA context object.
5700  *
5701  * This function is the main SLI initialization function. This function
5702  * is called by the HBA initialization code, HBA reset code and HBA
5703  * error attention handler code. Caller is not required to hold any
5704  * locks. This function issues config_port mailbox command to configure
5705  * the SLI, setup iocb rings and HBQ rings. In the end the function
5706  * calls the config_port_post function to issue init_link mailbox
5707  * command and to start the discovery. The function will return zero
5708  * if successful, else it will return negative error code.
5709  **/
5710 int
5711 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5712 {
5713 	uint32_t rc;
5714 	int  i;
5715 	int longs;
5716 
5717 	/* Enable ISR already does config_port because of config_msi mbx */
5718 	if (test_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag)) {
5719 		rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5720 		if (rc)
5721 			return -EIO;
5722 		clear_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
5723 	}
5724 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
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 = 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 		rc = -EIO;
5855 		goto out_free_mboxq;
5856 	}
5857 	data_length = mqe->un.mb_words[5];
5858 	if (data_length > DMP_RGN23_SIZE) {
5859 		rc = -EIO;
5860 		goto out_free_mboxq;
5861 	}
5862 
5863 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5864 	rc = 0;
5865 
5866 out_free_mboxq:
5867 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
5868 	return rc;
5869 }
5870 
5871 /**
5872  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5873  * @phba: pointer to lpfc hba data structure.
5874  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5875  * @vpd: pointer to the memory to hold resulting port vpd data.
5876  * @vpd_size: On input, the number of bytes allocated to @vpd.
5877  *	      On output, the number of data bytes in @vpd.
5878  *
5879  * This routine executes a READ_REV SLI4 mailbox command.  In
5880  * addition, this routine gets the port vpd data.
5881  *
5882  * Return codes
5883  * 	0 - successful
5884  * 	-ENOMEM - could not allocated memory.
5885  **/
5886 static int
5887 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5888 		    uint8_t *vpd, uint32_t *vpd_size)
5889 {
5890 	int rc = 0;
5891 	uint32_t dma_size;
5892 	struct lpfc_dmabuf *dmabuf;
5893 	struct lpfc_mqe *mqe;
5894 
5895 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5896 	if (!dmabuf)
5897 		return -ENOMEM;
5898 
5899 	/*
5900 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5901 	 * mailbox command.
5902 	 */
5903 	dma_size = *vpd_size;
5904 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5905 					  &dmabuf->phys, GFP_KERNEL);
5906 	if (!dmabuf->virt) {
5907 		kfree(dmabuf);
5908 		return -ENOMEM;
5909 	}
5910 
5911 	/*
5912 	 * The SLI4 implementation of READ_REV conflicts at word1,
5913 	 * bits 31:16 and SLI4 adds vpd functionality not present
5914 	 * in SLI3.  This code corrects the conflicts.
5915 	 */
5916 	lpfc_read_rev(phba, mboxq);
5917 	mqe = &mboxq->u.mqe;
5918 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5919 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5920 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5921 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5922 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5923 
5924 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5925 	if (rc) {
5926 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5927 				  dmabuf->virt, dmabuf->phys);
5928 		kfree(dmabuf);
5929 		return -EIO;
5930 	}
5931 
5932 	/*
5933 	 * The available vpd length cannot be bigger than the
5934 	 * DMA buffer passed to the port.  Catch the less than
5935 	 * case and update the caller's size.
5936 	 */
5937 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5938 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5939 
5940 	memcpy(vpd, dmabuf->virt, *vpd_size);
5941 
5942 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5943 			  dmabuf->virt, dmabuf->phys);
5944 	kfree(dmabuf);
5945 	return 0;
5946 }
5947 
5948 /**
5949  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5950  * @phba: pointer to lpfc hba data structure.
5951  *
5952  * This routine retrieves SLI4 device physical port name this PCI function
5953  * is attached to.
5954  *
5955  * Return codes
5956  *      0 - successful
5957  *      otherwise - failed to retrieve controller attributes
5958  **/
5959 static int
5960 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5961 {
5962 	LPFC_MBOXQ_t *mboxq;
5963 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5964 	struct lpfc_controller_attribute *cntl_attr;
5965 	void *virtaddr = NULL;
5966 	uint32_t alloclen, reqlen;
5967 	uint32_t shdr_status, shdr_add_status;
5968 	union lpfc_sli4_cfg_shdr *shdr;
5969 	int rc;
5970 
5971 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5972 	if (!mboxq)
5973 		return -ENOMEM;
5974 
5975 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5976 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5977 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5978 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5979 			LPFC_SLI4_MBX_NEMBED);
5980 
5981 	if (alloclen < reqlen) {
5982 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5983 				"3084 Allocated DMA memory size (%d) is "
5984 				"less than the requested DMA memory size "
5985 				"(%d)\n", alloclen, reqlen);
5986 		rc = -ENOMEM;
5987 		goto out_free_mboxq;
5988 	}
5989 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5990 	virtaddr = mboxq->sge_array->addr[0];
5991 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5992 	shdr = &mbx_cntl_attr->cfg_shdr;
5993 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5994 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5995 	if (shdr_status || shdr_add_status || rc) {
5996 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5997 				"3085 Mailbox x%x (x%x/x%x) failed, "
5998 				"rc:x%x, status:x%x, add_status:x%x\n",
5999 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6000 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6001 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6002 				rc, shdr_status, shdr_add_status);
6003 		rc = -ENXIO;
6004 		goto out_free_mboxq;
6005 	}
6006 
6007 	cntl_attr = &mbx_cntl_attr->cntl_attr;
6008 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
6009 	phba->sli4_hba.lnk_info.lnk_tp =
6010 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
6011 	phba->sli4_hba.lnk_info.lnk_no =
6012 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
6013 	phba->sli4_hba.flash_id = bf_get(lpfc_cntl_attr_flash_id, cntl_attr);
6014 	phba->sli4_hba.asic_rev = bf_get(lpfc_cntl_attr_asic_rev, cntl_attr);
6015 
6016 	memcpy(phba->BIOSVersion, cntl_attr->bios_ver_str,
6017 		sizeof(phba->BIOSVersion));
6018 	phba->BIOSVersion[sizeof(phba->BIOSVersion) - 1] = '\0';
6019 
6020 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6021 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s, "
6022 			"flash_id: x%02x, asic_rev: x%02x\n",
6023 			phba->sli4_hba.lnk_info.lnk_tp,
6024 			phba->sli4_hba.lnk_info.lnk_no,
6025 			phba->BIOSVersion, phba->sli4_hba.flash_id,
6026 			phba->sli4_hba.asic_rev);
6027 out_free_mboxq:
6028 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6029 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6030 	else
6031 		mempool_free(mboxq, phba->mbox_mem_pool);
6032 	return rc;
6033 }
6034 
6035 /**
6036  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
6037  * @phba: pointer to lpfc hba data structure.
6038  *
6039  * This routine retrieves SLI4 device physical port name this PCI function
6040  * is attached to.
6041  *
6042  * Return codes
6043  *      0 - successful
6044  *      otherwise - failed to retrieve physical port name
6045  **/
6046 static int
6047 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
6048 {
6049 	LPFC_MBOXQ_t *mboxq;
6050 	struct lpfc_mbx_get_port_name *get_port_name;
6051 	uint32_t shdr_status, shdr_add_status;
6052 	union lpfc_sli4_cfg_shdr *shdr;
6053 	char cport_name = 0;
6054 	int rc;
6055 
6056 	/* We assume nothing at this point */
6057 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6058 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
6059 
6060 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6061 	if (!mboxq)
6062 		return -ENOMEM;
6063 	/* obtain link type and link number via READ_CONFIG */
6064 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6065 	lpfc_sli4_read_config(phba);
6066 
6067 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG)
6068 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
6069 
6070 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
6071 		goto retrieve_ppname;
6072 
6073 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
6074 	rc = lpfc_sli4_get_ctl_attr(phba);
6075 	if (rc)
6076 		goto out_free_mboxq;
6077 
6078 retrieve_ppname:
6079 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
6080 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
6081 		sizeof(struct lpfc_mbx_get_port_name) -
6082 		sizeof(struct lpfc_sli4_cfg_mhdr),
6083 		LPFC_SLI4_MBX_EMBED);
6084 	get_port_name = &mboxq->u.mqe.un.get_port_name;
6085 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
6086 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
6087 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
6088 		phba->sli4_hba.lnk_info.lnk_tp);
6089 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6090 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6091 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6092 	if (shdr_status || shdr_add_status || rc) {
6093 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6094 				"3087 Mailbox x%x (x%x/x%x) failed: "
6095 				"rc:x%x, status:x%x, add_status:x%x\n",
6096 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6097 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6098 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6099 				rc, shdr_status, shdr_add_status);
6100 		rc = -ENXIO;
6101 		goto out_free_mboxq;
6102 	}
6103 	switch (phba->sli4_hba.lnk_info.lnk_no) {
6104 	case LPFC_LINK_NUMBER_0:
6105 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
6106 				&get_port_name->u.response);
6107 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6108 		break;
6109 	case LPFC_LINK_NUMBER_1:
6110 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
6111 				&get_port_name->u.response);
6112 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6113 		break;
6114 	case LPFC_LINK_NUMBER_2:
6115 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
6116 				&get_port_name->u.response);
6117 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6118 		break;
6119 	case LPFC_LINK_NUMBER_3:
6120 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
6121 				&get_port_name->u.response);
6122 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6123 		break;
6124 	default:
6125 		break;
6126 	}
6127 
6128 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
6129 		phba->Port[0] = cport_name;
6130 		phba->Port[1] = '\0';
6131 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6132 				"3091 SLI get port name: %s\n", phba->Port);
6133 	}
6134 
6135 out_free_mboxq:
6136 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6137 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6138 	else
6139 		mempool_free(mboxq, phba->mbox_mem_pool);
6140 	return rc;
6141 }
6142 
6143 /**
6144  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
6145  * @phba: pointer to lpfc hba data structure.
6146  *
6147  * This routine is called to explicitly arm the SLI4 device's completion and
6148  * event queues
6149  **/
6150 static void
6151 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
6152 {
6153 	int qidx;
6154 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
6155 	struct lpfc_sli4_hdw_queue *qp;
6156 	struct lpfc_queue *eq;
6157 
6158 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
6159 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
6160 	if (sli4_hba->nvmels_cq)
6161 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
6162 					   LPFC_QUEUE_REARM);
6163 
6164 	if (sli4_hba->hdwq) {
6165 		/* Loop thru all Hardware Queues */
6166 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
6167 			qp = &sli4_hba->hdwq[qidx];
6168 			/* ARM the corresponding CQ */
6169 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
6170 						LPFC_QUEUE_REARM);
6171 		}
6172 
6173 		/* Loop thru all IRQ vectors */
6174 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
6175 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
6176 			/* ARM the corresponding EQ */
6177 			sli4_hba->sli4_write_eq_db(phba, eq,
6178 						   0, LPFC_QUEUE_REARM);
6179 		}
6180 	}
6181 
6182 	if (phba->nvmet_support) {
6183 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
6184 			sli4_hba->sli4_write_cq_db(phba,
6185 				sli4_hba->nvmet_cqset[qidx], 0,
6186 				LPFC_QUEUE_REARM);
6187 		}
6188 	}
6189 }
6190 
6191 /**
6192  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
6193  * @phba: Pointer to HBA context object.
6194  * @type: The resource extent type.
6195  * @extnt_count: buffer to hold port available extent count.
6196  * @extnt_size: buffer to hold element count per extent.
6197  *
6198  * This function calls the port and retrievs the number of available
6199  * extents and their size for a particular extent type.
6200  *
6201  * Returns: 0 if successful.  Nonzero otherwise.
6202  **/
6203 int
6204 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
6205 			       uint16_t *extnt_count, uint16_t *extnt_size)
6206 {
6207 	int rc = 0;
6208 	uint32_t length;
6209 	uint32_t mbox_tmo;
6210 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
6211 	LPFC_MBOXQ_t *mbox;
6212 
6213 	*extnt_count = 0;
6214 	*extnt_size = 0;
6215 
6216 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6217 	if (!mbox)
6218 		return -ENOMEM;
6219 
6220 	/* Find out how many extents are available for this resource type */
6221 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
6222 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6223 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6224 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
6225 			 length, LPFC_SLI4_MBX_EMBED);
6226 
6227 	/* Send an extents count of 0 - the GET doesn't use it. */
6228 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6229 					LPFC_SLI4_MBX_EMBED);
6230 	if (unlikely(rc)) {
6231 		rc = -EIO;
6232 		goto err_exit;
6233 	}
6234 
6235 	if (!phba->sli4_hba.intr_enable)
6236 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6237 	else {
6238 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6239 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6240 	}
6241 	if (unlikely(rc)) {
6242 		rc = -EIO;
6243 		goto err_exit;
6244 	}
6245 
6246 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
6247 	if (bf_get(lpfc_mbox_hdr_status,
6248 		   &rsrc_info->header.cfg_shdr.response)) {
6249 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6250 				"2930 Failed to get resource extents "
6251 				"Status 0x%x Add'l Status 0x%x\n",
6252 				bf_get(lpfc_mbox_hdr_status,
6253 				       &rsrc_info->header.cfg_shdr.response),
6254 				bf_get(lpfc_mbox_hdr_add_status,
6255 				       &rsrc_info->header.cfg_shdr.response));
6256 		rc = -EIO;
6257 		goto err_exit;
6258 	}
6259 
6260 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
6261 			      &rsrc_info->u.rsp);
6262 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
6263 			     &rsrc_info->u.rsp);
6264 
6265 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6266 			"3162 Retrieved extents type-%d from port: count:%d, "
6267 			"size:%d\n", type, *extnt_count, *extnt_size);
6268 
6269 err_exit:
6270 	mempool_free(mbox, phba->mbox_mem_pool);
6271 	return rc;
6272 }
6273 
6274 /**
6275  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
6276  * @phba: Pointer to HBA context object.
6277  * @type: The extent type to check.
6278  *
6279  * This function reads the current available extents from the port and checks
6280  * if the extent count or extent size has changed since the last access.
6281  * Callers use this routine post port reset to understand if there is a
6282  * extent reprovisioning requirement.
6283  *
6284  * Returns:
6285  *   -Error: error indicates problem.
6286  *   1: Extent count or size has changed.
6287  *   0: No changes.
6288  **/
6289 static int
6290 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
6291 {
6292 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
6293 	uint16_t size_diff, rsrc_ext_size;
6294 	int rc = 0;
6295 	struct lpfc_rsrc_blks *rsrc_entry;
6296 	struct list_head *rsrc_blk_list = NULL;
6297 
6298 	size_diff = 0;
6299 	curr_ext_cnt = 0;
6300 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6301 					    &rsrc_ext_cnt,
6302 					    &rsrc_ext_size);
6303 	if (unlikely(rc))
6304 		return -EIO;
6305 
6306 	switch (type) {
6307 	case LPFC_RSC_TYPE_FCOE_RPI:
6308 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6309 		break;
6310 	case LPFC_RSC_TYPE_FCOE_VPI:
6311 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
6312 		break;
6313 	case LPFC_RSC_TYPE_FCOE_XRI:
6314 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6315 		break;
6316 	case LPFC_RSC_TYPE_FCOE_VFI:
6317 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6318 		break;
6319 	default:
6320 		break;
6321 	}
6322 
6323 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
6324 		curr_ext_cnt++;
6325 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
6326 			size_diff++;
6327 	}
6328 
6329 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
6330 		rc = 1;
6331 
6332 	return rc;
6333 }
6334 
6335 /**
6336  * lpfc_sli4_cfg_post_extnts -
6337  * @phba: Pointer to HBA context object.
6338  * @extnt_cnt: number of available extents.
6339  * @type: the extent type (rpi, xri, vfi, vpi).
6340  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
6341  * @mbox: pointer to the caller's allocated mailbox structure.
6342  *
6343  * This function executes the extents allocation request.  It also
6344  * takes care of the amount of memory needed to allocate or get the
6345  * allocated extents. It is the caller's responsibility to evaluate
6346  * the response.
6347  *
6348  * Returns:
6349  *   -Error:  Error value describes the condition found.
6350  *   0: if successful
6351  **/
6352 static int
6353 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6354 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6355 {
6356 	int rc = 0;
6357 	uint32_t req_len;
6358 	uint32_t emb_len;
6359 	uint32_t alloc_len, mbox_tmo;
6360 
6361 	/* Calculate the total requested length of the dma memory */
6362 	req_len = extnt_cnt * sizeof(uint16_t);
6363 
6364 	/*
6365 	 * Calculate the size of an embedded mailbox.  The uint32_t
6366 	 * accounts for extents-specific word.
6367 	 */
6368 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6369 		sizeof(uint32_t);
6370 
6371 	/*
6372 	 * Presume the allocation and response will fit into an embedded
6373 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6374 	 */
6375 	*emb = LPFC_SLI4_MBX_EMBED;
6376 	if (req_len > emb_len) {
6377 		req_len = extnt_cnt * sizeof(uint16_t) +
6378 			sizeof(union lpfc_sli4_cfg_shdr) +
6379 			sizeof(uint32_t);
6380 		*emb = LPFC_SLI4_MBX_NEMBED;
6381 	}
6382 
6383 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6384 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6385 				     req_len, *emb);
6386 	if (alloc_len < req_len) {
6387 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6388 			"2982 Allocated DMA memory size (x%x) is "
6389 			"less than the requested DMA memory "
6390 			"size (x%x)\n", alloc_len, req_len);
6391 		return -ENOMEM;
6392 	}
6393 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6394 	if (unlikely(rc))
6395 		return -EIO;
6396 
6397 	if (!phba->sli4_hba.intr_enable)
6398 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6399 	else {
6400 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6401 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6402 	}
6403 
6404 	if (unlikely(rc))
6405 		rc = -EIO;
6406 	return rc;
6407 }
6408 
6409 /**
6410  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6411  * @phba: Pointer to HBA context object.
6412  * @type:  The resource extent type to allocate.
6413  *
6414  * This function allocates the number of elements for the specified
6415  * resource type.
6416  **/
6417 static int
6418 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6419 {
6420 	bool emb = false;
6421 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6422 	uint16_t rsrc_id, rsrc_start, j, k;
6423 	uint16_t *ids;
6424 	int i, rc;
6425 	unsigned long longs;
6426 	unsigned long *bmask;
6427 	struct lpfc_rsrc_blks *rsrc_blks;
6428 	LPFC_MBOXQ_t *mbox;
6429 	uint32_t length;
6430 	struct lpfc_id_range *id_array = NULL;
6431 	void *virtaddr = NULL;
6432 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6433 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6434 	struct list_head *ext_blk_list;
6435 
6436 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6437 					    &rsrc_cnt,
6438 					    &rsrc_size);
6439 	if (unlikely(rc))
6440 		return -EIO;
6441 
6442 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6443 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6444 			"3009 No available Resource Extents "
6445 			"for resource type 0x%x: Count: 0x%x, "
6446 			"Size 0x%x\n", type, rsrc_cnt,
6447 			rsrc_size);
6448 		return -ENOMEM;
6449 	}
6450 
6451 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6452 			"2903 Post resource extents type-0x%x: "
6453 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6454 
6455 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6456 	if (!mbox)
6457 		return -ENOMEM;
6458 
6459 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6460 	if (unlikely(rc)) {
6461 		rc = -EIO;
6462 		goto err_exit;
6463 	}
6464 
6465 	/*
6466 	 * Figure out where the response is located.  Then get local pointers
6467 	 * to the response data.  The port does not guarantee to respond to
6468 	 * all extents counts request so update the local variable with the
6469 	 * allocated count from the port.
6470 	 */
6471 	if (emb == LPFC_SLI4_MBX_EMBED) {
6472 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6473 		id_array = &rsrc_ext->u.rsp.id[0];
6474 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6475 	} else {
6476 		virtaddr = mbox->sge_array->addr[0];
6477 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6478 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6479 		id_array = &n_rsrc->id;
6480 	}
6481 
6482 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6483 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6484 
6485 	/*
6486 	 * Based on the resource size and count, correct the base and max
6487 	 * resource values.
6488 	 */
6489 	length = sizeof(struct lpfc_rsrc_blks);
6490 	switch (type) {
6491 	case LPFC_RSC_TYPE_FCOE_RPI:
6492 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6493 						   sizeof(unsigned long),
6494 						   GFP_KERNEL);
6495 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6496 			rc = -ENOMEM;
6497 			goto err_exit;
6498 		}
6499 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6500 						 sizeof(uint16_t),
6501 						 GFP_KERNEL);
6502 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6503 			kfree(phba->sli4_hba.rpi_bmask);
6504 			rc = -ENOMEM;
6505 			goto err_exit;
6506 		}
6507 
6508 		/*
6509 		 * The next_rpi was initialized with the maximum available
6510 		 * count but the port may allocate a smaller number.  Catch
6511 		 * that case and update the next_rpi.
6512 		 */
6513 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6514 
6515 		/* Initialize local ptrs for common extent processing later. */
6516 		bmask = phba->sli4_hba.rpi_bmask;
6517 		ids = phba->sli4_hba.rpi_ids;
6518 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6519 		break;
6520 	case LPFC_RSC_TYPE_FCOE_VPI:
6521 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6522 					  GFP_KERNEL);
6523 		if (unlikely(!phba->vpi_bmask)) {
6524 			rc = -ENOMEM;
6525 			goto err_exit;
6526 		}
6527 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6528 					 GFP_KERNEL);
6529 		if (unlikely(!phba->vpi_ids)) {
6530 			kfree(phba->vpi_bmask);
6531 			rc = -ENOMEM;
6532 			goto err_exit;
6533 		}
6534 
6535 		/* Initialize local ptrs for common extent processing later. */
6536 		bmask = phba->vpi_bmask;
6537 		ids = phba->vpi_ids;
6538 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6539 		break;
6540 	case LPFC_RSC_TYPE_FCOE_XRI:
6541 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6542 						   sizeof(unsigned long),
6543 						   GFP_KERNEL);
6544 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6545 			rc = -ENOMEM;
6546 			goto err_exit;
6547 		}
6548 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6549 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6550 						 sizeof(uint16_t),
6551 						 GFP_KERNEL);
6552 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6553 			kfree(phba->sli4_hba.xri_bmask);
6554 			rc = -ENOMEM;
6555 			goto err_exit;
6556 		}
6557 
6558 		/* Initialize local ptrs for common extent processing later. */
6559 		bmask = phba->sli4_hba.xri_bmask;
6560 		ids = phba->sli4_hba.xri_ids;
6561 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6562 		break;
6563 	case LPFC_RSC_TYPE_FCOE_VFI:
6564 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6565 						   sizeof(unsigned long),
6566 						   GFP_KERNEL);
6567 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6568 			rc = -ENOMEM;
6569 			goto err_exit;
6570 		}
6571 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6572 						 sizeof(uint16_t),
6573 						 GFP_KERNEL);
6574 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6575 			kfree(phba->sli4_hba.vfi_bmask);
6576 			rc = -ENOMEM;
6577 			goto err_exit;
6578 		}
6579 
6580 		/* Initialize local ptrs for common extent processing later. */
6581 		bmask = phba->sli4_hba.vfi_bmask;
6582 		ids = phba->sli4_hba.vfi_ids;
6583 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6584 		break;
6585 	default:
6586 		/* Unsupported Opcode.  Fail call. */
6587 		id_array = NULL;
6588 		bmask = NULL;
6589 		ids = NULL;
6590 		ext_blk_list = NULL;
6591 		goto err_exit;
6592 	}
6593 
6594 	/*
6595 	 * Complete initializing the extent configuration with the
6596 	 * allocated ids assigned to this function.  The bitmask serves
6597 	 * as an index into the array and manages the available ids.  The
6598 	 * array just stores the ids communicated to the port via the wqes.
6599 	 */
6600 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6601 		if ((i % 2) == 0)
6602 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6603 					 &id_array[k]);
6604 		else
6605 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6606 					 &id_array[k]);
6607 
6608 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6609 		if (unlikely(!rsrc_blks)) {
6610 			rc = -ENOMEM;
6611 			kfree(bmask);
6612 			kfree(ids);
6613 			goto err_exit;
6614 		}
6615 		rsrc_blks->rsrc_start = rsrc_id;
6616 		rsrc_blks->rsrc_size = rsrc_size;
6617 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6618 		rsrc_start = rsrc_id;
6619 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6620 			phba->sli4_hba.io_xri_start = rsrc_start +
6621 				lpfc_sli4_get_iocb_cnt(phba);
6622 		}
6623 
6624 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6625 			ids[j] = rsrc_id;
6626 			rsrc_id++;
6627 			j++;
6628 		}
6629 		/* Entire word processed.  Get next word.*/
6630 		if ((i % 2) == 1)
6631 			k++;
6632 	}
6633  err_exit:
6634 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6635 	return rc;
6636 }
6637 
6638 
6639 
6640 /**
6641  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6642  * @phba: Pointer to HBA context object.
6643  * @type: the extent's type.
6644  *
6645  * This function deallocates all extents of a particular resource type.
6646  * SLI4 does not allow for deallocating a particular extent range.  It
6647  * is the caller's responsibility to release all kernel memory resources.
6648  **/
6649 static int
6650 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6651 {
6652 	int rc;
6653 	uint32_t length, mbox_tmo = 0;
6654 	LPFC_MBOXQ_t *mbox;
6655 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6656 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6657 
6658 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6659 	if (!mbox)
6660 		return -ENOMEM;
6661 
6662 	/*
6663 	 * This function sends an embedded mailbox because it only sends the
6664 	 * the resource type.  All extents of this type are released by the
6665 	 * port.
6666 	 */
6667 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6668 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6669 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6670 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6671 			 length, LPFC_SLI4_MBX_EMBED);
6672 
6673 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6674 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6675 					LPFC_SLI4_MBX_EMBED);
6676 	if (unlikely(rc)) {
6677 		rc = -EIO;
6678 		goto out_free_mbox;
6679 	}
6680 	if (!phba->sli4_hba.intr_enable)
6681 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6682 	else {
6683 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6684 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6685 	}
6686 	if (unlikely(rc)) {
6687 		rc = -EIO;
6688 		goto out_free_mbox;
6689 	}
6690 
6691 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6692 	if (bf_get(lpfc_mbox_hdr_status,
6693 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6694 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6695 				"2919 Failed to release resource extents "
6696 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6697 				"Resource memory not released.\n",
6698 				type,
6699 				bf_get(lpfc_mbox_hdr_status,
6700 				    &dealloc_rsrc->header.cfg_shdr.response),
6701 				bf_get(lpfc_mbox_hdr_add_status,
6702 				    &dealloc_rsrc->header.cfg_shdr.response));
6703 		rc = -EIO;
6704 		goto out_free_mbox;
6705 	}
6706 
6707 	/* Release kernel memory resources for the specific type. */
6708 	switch (type) {
6709 	case LPFC_RSC_TYPE_FCOE_VPI:
6710 		kfree(phba->vpi_bmask);
6711 		kfree(phba->vpi_ids);
6712 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6713 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6714 				    &phba->lpfc_vpi_blk_list, list) {
6715 			list_del_init(&rsrc_blk->list);
6716 			kfree(rsrc_blk);
6717 		}
6718 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6719 		break;
6720 	case LPFC_RSC_TYPE_FCOE_XRI:
6721 		kfree(phba->sli4_hba.xri_bmask);
6722 		kfree(phba->sli4_hba.xri_ids);
6723 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6724 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6725 			list_del_init(&rsrc_blk->list);
6726 			kfree(rsrc_blk);
6727 		}
6728 		break;
6729 	case LPFC_RSC_TYPE_FCOE_VFI:
6730 		kfree(phba->sli4_hba.vfi_bmask);
6731 		kfree(phba->sli4_hba.vfi_ids);
6732 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6733 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6734 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6735 			list_del_init(&rsrc_blk->list);
6736 			kfree(rsrc_blk);
6737 		}
6738 		break;
6739 	case LPFC_RSC_TYPE_FCOE_RPI:
6740 		/* RPI bitmask and physical id array are cleaned up earlier. */
6741 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6742 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6743 			list_del_init(&rsrc_blk->list);
6744 			kfree(rsrc_blk);
6745 		}
6746 		break;
6747 	default:
6748 		break;
6749 	}
6750 
6751 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6752 
6753  out_free_mbox:
6754 	mempool_free(mbox, phba->mbox_mem_pool);
6755 	return rc;
6756 }
6757 
6758 static void
6759 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6760 		  uint32_t feature)
6761 {
6762 	uint32_t len;
6763 	u32 sig_freq = 0;
6764 
6765 	len = sizeof(struct lpfc_mbx_set_feature) -
6766 		sizeof(struct lpfc_sli4_cfg_mhdr);
6767 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6768 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6769 			 LPFC_SLI4_MBX_EMBED);
6770 
6771 	switch (feature) {
6772 	case LPFC_SET_UE_RECOVERY:
6773 		bf_set(lpfc_mbx_set_feature_UER,
6774 		       &mbox->u.mqe.un.set_feature, 1);
6775 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6776 		mbox->u.mqe.un.set_feature.param_len = 8;
6777 		break;
6778 	case LPFC_SET_MDS_DIAGS:
6779 		bf_set(lpfc_mbx_set_feature_mds,
6780 		       &mbox->u.mqe.un.set_feature, 1);
6781 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6782 		       &mbox->u.mqe.un.set_feature, 1);
6783 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6784 		mbox->u.mqe.un.set_feature.param_len = 8;
6785 		break;
6786 	case LPFC_SET_CGN_SIGNAL:
6787 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6788 			sig_freq = 0;
6789 		else
6790 			sig_freq = phba->cgn_sig_freq;
6791 
6792 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6793 			bf_set(lpfc_mbx_set_feature_CGN_alarm_freq,
6794 			       &mbox->u.mqe.un.set_feature, sig_freq);
6795 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6796 			       &mbox->u.mqe.un.set_feature, sig_freq);
6797 		}
6798 
6799 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY)
6800 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6801 			       &mbox->u.mqe.un.set_feature, sig_freq);
6802 
6803 		if (phba->cmf_active_mode == LPFC_CFG_OFF ||
6804 		    phba->cgn_reg_signal == EDC_CG_SIG_NOTSUPPORTED)
6805 			sig_freq = 0;
6806 		else
6807 			sig_freq = lpfc_acqe_cgn_frequency;
6808 
6809 		bf_set(lpfc_mbx_set_feature_CGN_acqe_freq,
6810 		       &mbox->u.mqe.un.set_feature, sig_freq);
6811 
6812 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_CGN_SIGNAL;
6813 		mbox->u.mqe.un.set_feature.param_len = 12;
6814 		break;
6815 	case LPFC_SET_DUAL_DUMP:
6816 		bf_set(lpfc_mbx_set_feature_dd,
6817 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6818 		bf_set(lpfc_mbx_set_feature_ddquery,
6819 		       &mbox->u.mqe.un.set_feature, 0);
6820 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6821 		mbox->u.mqe.un.set_feature.param_len = 4;
6822 		break;
6823 	case LPFC_SET_ENABLE_MI:
6824 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_MI;
6825 		mbox->u.mqe.un.set_feature.param_len = 4;
6826 		bf_set(lpfc_mbx_set_feature_milunq, &mbox->u.mqe.un.set_feature,
6827 		       phba->pport->cfg_lun_queue_depth);
6828 		bf_set(lpfc_mbx_set_feature_mi, &mbox->u.mqe.un.set_feature,
6829 		       phba->sli4_hba.pc_sli4_params.mi_ver);
6830 		break;
6831 	case LPFC_SET_LD_SIGNAL:
6832 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_LD_SIGNAL;
6833 		mbox->u.mqe.un.set_feature.param_len = 16;
6834 		bf_set(lpfc_mbx_set_feature_lds_qry,
6835 		       &mbox->u.mqe.un.set_feature, LPFC_QUERY_LDS_OP);
6836 		break;
6837 	case LPFC_SET_ENABLE_CMF:
6838 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_CMF;
6839 		mbox->u.mqe.un.set_feature.param_len = 4;
6840 		bf_set(lpfc_mbx_set_feature_cmf,
6841 		       &mbox->u.mqe.un.set_feature, 1);
6842 		break;
6843 	}
6844 	return;
6845 }
6846 
6847 /**
6848  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6849  * @phba: Pointer to HBA context object.
6850  *
6851  * Disable FW logging into host memory on the adapter. To
6852  * be done before reading logs from the host memory.
6853  **/
6854 void
6855 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6856 {
6857 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6858 
6859 	spin_lock_irq(&phba->ras_fwlog_lock);
6860 	ras_fwlog->state = INACTIVE;
6861 	spin_unlock_irq(&phba->ras_fwlog_lock);
6862 
6863 	/* Disable FW logging to host memory */
6864 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6865 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6866 
6867 	/* Wait 10ms for firmware to stop using DMA buffer */
6868 	usleep_range(10 * 1000, 20 * 1000);
6869 }
6870 
6871 /**
6872  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6873  * @phba: Pointer to HBA context object.
6874  *
6875  * This function is called to free memory allocated for RAS FW logging
6876  * support in the driver.
6877  **/
6878 void
6879 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6880 {
6881 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6882 	struct lpfc_dmabuf *dmabuf, *next;
6883 
6884 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6885 		list_for_each_entry_safe(dmabuf, next,
6886 				    &ras_fwlog->fwlog_buff_list,
6887 				    list) {
6888 			list_del(&dmabuf->list);
6889 			dma_free_coherent(&phba->pcidev->dev,
6890 					  LPFC_RAS_MAX_ENTRY_SIZE,
6891 					  dmabuf->virt, dmabuf->phys);
6892 			kfree(dmabuf);
6893 		}
6894 	}
6895 
6896 	if (ras_fwlog->lwpd.virt) {
6897 		dma_free_coherent(&phba->pcidev->dev,
6898 				  sizeof(uint32_t) * 2,
6899 				  ras_fwlog->lwpd.virt,
6900 				  ras_fwlog->lwpd.phys);
6901 		ras_fwlog->lwpd.virt = NULL;
6902 	}
6903 
6904 	spin_lock_irq(&phba->ras_fwlog_lock);
6905 	ras_fwlog->state = INACTIVE;
6906 	spin_unlock_irq(&phba->ras_fwlog_lock);
6907 }
6908 
6909 /**
6910  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6911  * @phba: Pointer to HBA context object.
6912  * @fwlog_buff_count: Count of buffers to be created.
6913  *
6914  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6915  * to update FW log is posted to the adapter.
6916  * Buffer count is calculated based on module param ras_fwlog_buffsize
6917  * Size of each buffer posted to FW is 64K.
6918  **/
6919 
6920 static int
6921 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6922 			uint32_t fwlog_buff_count)
6923 {
6924 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6925 	struct lpfc_dmabuf *dmabuf;
6926 	int rc = 0, i = 0;
6927 
6928 	/* Initialize List */
6929 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6930 
6931 	/* Allocate memory for the LWPD */
6932 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6933 					    sizeof(uint32_t) * 2,
6934 					    &ras_fwlog->lwpd.phys,
6935 					    GFP_KERNEL);
6936 	if (!ras_fwlog->lwpd.virt) {
6937 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6938 				"6185 LWPD Memory Alloc Failed\n");
6939 
6940 		return -ENOMEM;
6941 	}
6942 
6943 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6944 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6945 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6946 				 GFP_KERNEL);
6947 		if (!dmabuf) {
6948 			rc = -ENOMEM;
6949 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6950 					"6186 Memory Alloc failed FW logging");
6951 			goto free_mem;
6952 		}
6953 
6954 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6955 						  LPFC_RAS_MAX_ENTRY_SIZE,
6956 						  &dmabuf->phys, GFP_KERNEL);
6957 		if (!dmabuf->virt) {
6958 			kfree(dmabuf);
6959 			rc = -ENOMEM;
6960 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6961 					"6187 DMA Alloc Failed FW logging");
6962 			goto free_mem;
6963 		}
6964 		dmabuf->buffer_tag = i;
6965 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6966 	}
6967 
6968 free_mem:
6969 	if (rc)
6970 		lpfc_sli4_ras_dma_free(phba);
6971 
6972 	return rc;
6973 }
6974 
6975 /**
6976  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6977  * @phba: pointer to lpfc hba data structure.
6978  * @pmb: pointer to the driver internal queue element for mailbox command.
6979  *
6980  * Completion handler for driver's RAS MBX command to the device.
6981  **/
6982 static void
6983 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6984 {
6985 	MAILBOX_t *mb;
6986 	union lpfc_sli4_cfg_shdr *shdr;
6987 	uint32_t shdr_status, shdr_add_status;
6988 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6989 
6990 	mb = &pmb->u.mb;
6991 
6992 	shdr = (union lpfc_sli4_cfg_shdr *)
6993 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6994 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6995 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6996 
6997 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6998 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6999 				"6188 FW LOG mailbox "
7000 				"completed with status x%x add_status x%x,"
7001 				" mbx status x%x\n",
7002 				shdr_status, shdr_add_status, mb->mbxStatus);
7003 
7004 		ras_fwlog->ras_hwsupport = false;
7005 		goto disable_ras;
7006 	}
7007 
7008 	spin_lock_irq(&phba->ras_fwlog_lock);
7009 	ras_fwlog->state = ACTIVE;
7010 	spin_unlock_irq(&phba->ras_fwlog_lock);
7011 	mempool_free(pmb, phba->mbox_mem_pool);
7012 
7013 	return;
7014 
7015 disable_ras:
7016 	/* Free RAS DMA memory */
7017 	lpfc_sli4_ras_dma_free(phba);
7018 	mempool_free(pmb, phba->mbox_mem_pool);
7019 }
7020 
7021 /**
7022  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
7023  * @phba: pointer to lpfc hba data structure.
7024  * @fwlog_level: Logging verbosity level.
7025  * @fwlog_enable: Enable/Disable logging.
7026  *
7027  * Initialize memory and post mailbox command to enable FW logging in host
7028  * memory.
7029  **/
7030 int
7031 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
7032 			 uint32_t fwlog_level,
7033 			 uint32_t fwlog_enable)
7034 {
7035 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
7036 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
7037 	struct lpfc_dmabuf *dmabuf;
7038 	LPFC_MBOXQ_t *mbox;
7039 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
7040 	int rc = 0;
7041 
7042 	spin_lock_irq(&phba->ras_fwlog_lock);
7043 	ras_fwlog->state = INACTIVE;
7044 	spin_unlock_irq(&phba->ras_fwlog_lock);
7045 
7046 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
7047 			  phba->cfg_ras_fwlog_buffsize);
7048 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
7049 
7050 	/*
7051 	 * If re-enabling FW logging support use earlier allocated
7052 	 * DMA buffers while posting MBX command.
7053 	 **/
7054 	if (!ras_fwlog->lwpd.virt) {
7055 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
7056 		if (rc) {
7057 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7058 					"6189 FW Log Memory Allocation Failed");
7059 			return rc;
7060 		}
7061 	}
7062 
7063 	/* Setup Mailbox command */
7064 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7065 	if (!mbox) {
7066 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7067 				"6190 RAS MBX Alloc Failed");
7068 		rc = -ENOMEM;
7069 		goto mem_free;
7070 	}
7071 
7072 	ras_fwlog->fw_loglevel = fwlog_level;
7073 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
7074 		sizeof(struct lpfc_sli4_cfg_mhdr));
7075 
7076 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
7077 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
7078 			 len, LPFC_SLI4_MBX_EMBED);
7079 
7080 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
7081 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
7082 	       fwlog_enable);
7083 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
7084 	       ras_fwlog->fw_loglevel);
7085 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
7086 	       ras_fwlog->fw_buffcount);
7087 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
7088 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
7089 
7090 	/* Update DMA buffer address */
7091 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
7092 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
7093 
7094 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
7095 			putPaddrLow(dmabuf->phys);
7096 
7097 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
7098 			putPaddrHigh(dmabuf->phys);
7099 	}
7100 
7101 	/* Update LPWD address */
7102 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
7103 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
7104 
7105 	spin_lock_irq(&phba->ras_fwlog_lock);
7106 	ras_fwlog->state = REG_INPROGRESS;
7107 	spin_unlock_irq(&phba->ras_fwlog_lock);
7108 	mbox->vport = phba->pport;
7109 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
7110 
7111 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
7112 
7113 	if (rc == MBX_NOT_FINISHED) {
7114 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7115 				"6191 FW-Log Mailbox failed. "
7116 				"status %d mbxStatus : x%x", rc,
7117 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
7118 		mempool_free(mbox, phba->mbox_mem_pool);
7119 		rc = -EIO;
7120 		goto mem_free;
7121 	} else
7122 		rc = 0;
7123 mem_free:
7124 	if (rc)
7125 		lpfc_sli4_ras_dma_free(phba);
7126 
7127 	return rc;
7128 }
7129 
7130 /**
7131  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
7132  * @phba: Pointer to HBA context object.
7133  *
7134  * Check if RAS is supported on the adapter and initialize it.
7135  **/
7136 void
7137 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
7138 {
7139 	/* Check RAS FW Log needs to be enabled or not */
7140 	if (lpfc_check_fwlog_support(phba))
7141 		return;
7142 
7143 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
7144 				 LPFC_RAS_ENABLE_LOGGING);
7145 }
7146 
7147 /**
7148  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
7149  * @phba: Pointer to HBA context object.
7150  *
7151  * This function allocates all SLI4 resource identifiers.
7152  **/
7153 int
7154 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
7155 {
7156 	int i, rc, error = 0;
7157 	uint16_t count, base;
7158 	unsigned long longs;
7159 
7160 	if (!phba->sli4_hba.rpi_hdrs_in_use)
7161 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
7162 	if (phba->sli4_hba.extents_in_use) {
7163 		/*
7164 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
7165 		 * resource extent count must be read and allocated before
7166 		 * provisioning the resource id arrays.
7167 		 */
7168 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7169 		    LPFC_IDX_RSRC_RDY) {
7170 			/*
7171 			 * Extent-based resources are set - the driver could
7172 			 * be in a port reset. Figure out if any corrective
7173 			 * actions need to be taken.
7174 			 */
7175 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7176 						 LPFC_RSC_TYPE_FCOE_VFI);
7177 			if (rc != 0)
7178 				error++;
7179 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7180 						 LPFC_RSC_TYPE_FCOE_VPI);
7181 			if (rc != 0)
7182 				error++;
7183 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7184 						 LPFC_RSC_TYPE_FCOE_XRI);
7185 			if (rc != 0)
7186 				error++;
7187 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7188 						 LPFC_RSC_TYPE_FCOE_RPI);
7189 			if (rc != 0)
7190 				error++;
7191 
7192 			/*
7193 			 * It's possible that the number of resources
7194 			 * provided to this port instance changed between
7195 			 * resets.  Detect this condition and reallocate
7196 			 * resources.  Otherwise, there is no action.
7197 			 */
7198 			if (error) {
7199 				lpfc_printf_log(phba, KERN_INFO,
7200 						LOG_MBOX | LOG_INIT,
7201 						"2931 Detected extent resource "
7202 						"change.  Reallocating all "
7203 						"extents.\n");
7204 				rc = lpfc_sli4_dealloc_extent(phba,
7205 						 LPFC_RSC_TYPE_FCOE_VFI);
7206 				rc = lpfc_sli4_dealloc_extent(phba,
7207 						 LPFC_RSC_TYPE_FCOE_VPI);
7208 				rc = lpfc_sli4_dealloc_extent(phba,
7209 						 LPFC_RSC_TYPE_FCOE_XRI);
7210 				rc = lpfc_sli4_dealloc_extent(phba,
7211 						 LPFC_RSC_TYPE_FCOE_RPI);
7212 			} else
7213 				return 0;
7214 		}
7215 
7216 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7217 		if (unlikely(rc))
7218 			goto err_exit;
7219 
7220 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7221 		if (unlikely(rc))
7222 			goto err_exit;
7223 
7224 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7225 		if (unlikely(rc))
7226 			goto err_exit;
7227 
7228 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7229 		if (unlikely(rc))
7230 			goto err_exit;
7231 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7232 		       LPFC_IDX_RSRC_RDY);
7233 		return rc;
7234 	} else {
7235 		/*
7236 		 * The port does not support resource extents.  The XRI, VPI,
7237 		 * VFI, RPI resource ids were determined from READ_CONFIG.
7238 		 * Just allocate the bitmasks and provision the resource id
7239 		 * arrays.  If a port reset is active, the resources don't
7240 		 * need any action - just exit.
7241 		 */
7242 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7243 		    LPFC_IDX_RSRC_RDY) {
7244 			lpfc_sli4_dealloc_resource_identifiers(phba);
7245 			lpfc_sli4_remove_rpis(phba);
7246 		}
7247 		/* RPIs. */
7248 		count = phba->sli4_hba.max_cfg_param.max_rpi;
7249 		if (count <= 0) {
7250 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7251 					"3279 Invalid provisioning of "
7252 					"rpi:%d\n", count);
7253 			rc = -EINVAL;
7254 			goto err_exit;
7255 		}
7256 		base = phba->sli4_hba.max_cfg_param.rpi_base;
7257 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7258 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
7259 						   sizeof(unsigned long),
7260 						   GFP_KERNEL);
7261 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
7262 			rc = -ENOMEM;
7263 			goto err_exit;
7264 		}
7265 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
7266 						 GFP_KERNEL);
7267 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
7268 			rc = -ENOMEM;
7269 			goto free_rpi_bmask;
7270 		}
7271 
7272 		for (i = 0; i < count; i++)
7273 			phba->sli4_hba.rpi_ids[i] = base + i;
7274 
7275 		/* VPIs. */
7276 		count = phba->sli4_hba.max_cfg_param.max_vpi;
7277 		if (count <= 0) {
7278 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7279 					"3280 Invalid provisioning of "
7280 					"vpi:%d\n", count);
7281 			rc = -EINVAL;
7282 			goto free_rpi_ids;
7283 		}
7284 		base = phba->sli4_hba.max_cfg_param.vpi_base;
7285 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7286 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
7287 					  GFP_KERNEL);
7288 		if (unlikely(!phba->vpi_bmask)) {
7289 			rc = -ENOMEM;
7290 			goto free_rpi_ids;
7291 		}
7292 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
7293 					GFP_KERNEL);
7294 		if (unlikely(!phba->vpi_ids)) {
7295 			rc = -ENOMEM;
7296 			goto free_vpi_bmask;
7297 		}
7298 
7299 		for (i = 0; i < count; i++)
7300 			phba->vpi_ids[i] = base + i;
7301 
7302 		/* XRIs. */
7303 		count = phba->sli4_hba.max_cfg_param.max_xri;
7304 		if (count <= 0) {
7305 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7306 					"3281 Invalid provisioning of "
7307 					"xri:%d\n", count);
7308 			rc = -EINVAL;
7309 			goto free_vpi_ids;
7310 		}
7311 		base = phba->sli4_hba.max_cfg_param.xri_base;
7312 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7313 		phba->sli4_hba.xri_bmask = kcalloc(longs,
7314 						   sizeof(unsigned long),
7315 						   GFP_KERNEL);
7316 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
7317 			rc = -ENOMEM;
7318 			goto free_vpi_ids;
7319 		}
7320 		phba->sli4_hba.max_cfg_param.xri_used = 0;
7321 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
7322 						 GFP_KERNEL);
7323 		if (unlikely(!phba->sli4_hba.xri_ids)) {
7324 			rc = -ENOMEM;
7325 			goto free_xri_bmask;
7326 		}
7327 
7328 		for (i = 0; i < count; i++)
7329 			phba->sli4_hba.xri_ids[i] = base + i;
7330 
7331 		/* VFIs. */
7332 		count = phba->sli4_hba.max_cfg_param.max_vfi;
7333 		if (count <= 0) {
7334 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7335 					"3282 Invalid provisioning of "
7336 					"vfi:%d\n", count);
7337 			rc = -EINVAL;
7338 			goto free_xri_ids;
7339 		}
7340 		base = phba->sli4_hba.max_cfg_param.vfi_base;
7341 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7342 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
7343 						   sizeof(unsigned long),
7344 						   GFP_KERNEL);
7345 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
7346 			rc = -ENOMEM;
7347 			goto free_xri_ids;
7348 		}
7349 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
7350 						 GFP_KERNEL);
7351 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
7352 			rc = -ENOMEM;
7353 			goto free_vfi_bmask;
7354 		}
7355 
7356 		for (i = 0; i < count; i++)
7357 			phba->sli4_hba.vfi_ids[i] = base + i;
7358 
7359 		/*
7360 		 * Mark all resources ready.  An HBA reset doesn't need
7361 		 * to reset the initialization.
7362 		 */
7363 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7364 		       LPFC_IDX_RSRC_RDY);
7365 		return 0;
7366 	}
7367 
7368  free_vfi_bmask:
7369 	kfree(phba->sli4_hba.vfi_bmask);
7370 	phba->sli4_hba.vfi_bmask = NULL;
7371  free_xri_ids:
7372 	kfree(phba->sli4_hba.xri_ids);
7373 	phba->sli4_hba.xri_ids = NULL;
7374  free_xri_bmask:
7375 	kfree(phba->sli4_hba.xri_bmask);
7376 	phba->sli4_hba.xri_bmask = NULL;
7377  free_vpi_ids:
7378 	kfree(phba->vpi_ids);
7379 	phba->vpi_ids = NULL;
7380  free_vpi_bmask:
7381 	kfree(phba->vpi_bmask);
7382 	phba->vpi_bmask = NULL;
7383  free_rpi_ids:
7384 	kfree(phba->sli4_hba.rpi_ids);
7385 	phba->sli4_hba.rpi_ids = NULL;
7386  free_rpi_bmask:
7387 	kfree(phba->sli4_hba.rpi_bmask);
7388 	phba->sli4_hba.rpi_bmask = NULL;
7389  err_exit:
7390 	return rc;
7391 }
7392 
7393 /**
7394  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
7395  * @phba: Pointer to HBA context object.
7396  *
7397  * This function allocates the number of elements for the specified
7398  * resource type.
7399  **/
7400 int
7401 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7402 {
7403 	if (phba->sli4_hba.extents_in_use) {
7404 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7405 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7406 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7407 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7408 	} else {
7409 		kfree(phba->vpi_bmask);
7410 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
7411 		kfree(phba->vpi_ids);
7412 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7413 		kfree(phba->sli4_hba.xri_bmask);
7414 		kfree(phba->sli4_hba.xri_ids);
7415 		kfree(phba->sli4_hba.vfi_bmask);
7416 		kfree(phba->sli4_hba.vfi_ids);
7417 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7418 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7419 	}
7420 
7421 	return 0;
7422 }
7423 
7424 /**
7425  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7426  * @phba: Pointer to HBA context object.
7427  * @type: The resource extent type.
7428  * @extnt_cnt: buffer to hold port extent count response
7429  * @extnt_size: buffer to hold port extent size response.
7430  *
7431  * This function calls the port to read the host allocated extents
7432  * for a particular type.
7433  **/
7434 int
7435 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7436 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
7437 {
7438 	bool emb;
7439 	int rc = 0;
7440 	uint16_t curr_blks = 0;
7441 	uint32_t req_len, emb_len;
7442 	uint32_t alloc_len, mbox_tmo;
7443 	struct list_head *blk_list_head;
7444 	struct lpfc_rsrc_blks *rsrc_blk;
7445 	LPFC_MBOXQ_t *mbox;
7446 	void *virtaddr = NULL;
7447 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7448 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7449 	union  lpfc_sli4_cfg_shdr *shdr;
7450 
7451 	switch (type) {
7452 	case LPFC_RSC_TYPE_FCOE_VPI:
7453 		blk_list_head = &phba->lpfc_vpi_blk_list;
7454 		break;
7455 	case LPFC_RSC_TYPE_FCOE_XRI:
7456 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7457 		break;
7458 	case LPFC_RSC_TYPE_FCOE_VFI:
7459 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7460 		break;
7461 	case LPFC_RSC_TYPE_FCOE_RPI:
7462 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7463 		break;
7464 	default:
7465 		return -EIO;
7466 	}
7467 
7468 	/* Count the number of extents currently allocatd for this type. */
7469 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
7470 		if (curr_blks == 0) {
7471 			/*
7472 			 * The GET_ALLOCATED mailbox does not return the size,
7473 			 * just the count.  The size should be just the size
7474 			 * stored in the current allocated block and all sizes
7475 			 * for an extent type are the same so set the return
7476 			 * value now.
7477 			 */
7478 			*extnt_size = rsrc_blk->rsrc_size;
7479 		}
7480 		curr_blks++;
7481 	}
7482 
7483 	/*
7484 	 * Calculate the size of an embedded mailbox.  The uint32_t
7485 	 * accounts for extents-specific word.
7486 	 */
7487 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7488 		sizeof(uint32_t);
7489 
7490 	/*
7491 	 * Presume the allocation and response will fit into an embedded
7492 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7493 	 */
7494 	emb = LPFC_SLI4_MBX_EMBED;
7495 	req_len = emb_len;
7496 	if (req_len > emb_len) {
7497 		req_len = curr_blks * sizeof(uint16_t) +
7498 			sizeof(union lpfc_sli4_cfg_shdr) +
7499 			sizeof(uint32_t);
7500 		emb = LPFC_SLI4_MBX_NEMBED;
7501 	}
7502 
7503 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7504 	if (!mbox)
7505 		return -ENOMEM;
7506 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7507 
7508 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7509 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7510 				     req_len, emb);
7511 	if (alloc_len < req_len) {
7512 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7513 			"2983 Allocated DMA memory size (x%x) is "
7514 			"less than the requested DMA memory "
7515 			"size (x%x)\n", alloc_len, req_len);
7516 		rc = -ENOMEM;
7517 		goto err_exit;
7518 	}
7519 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7520 	if (unlikely(rc)) {
7521 		rc = -EIO;
7522 		goto err_exit;
7523 	}
7524 
7525 	if (!phba->sli4_hba.intr_enable)
7526 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7527 	else {
7528 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7529 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7530 	}
7531 
7532 	if (unlikely(rc)) {
7533 		rc = -EIO;
7534 		goto err_exit;
7535 	}
7536 
7537 	/*
7538 	 * Figure out where the response is located.  Then get local pointers
7539 	 * to the response data.  The port does not guarantee to respond to
7540 	 * all extents counts request so update the local variable with the
7541 	 * allocated count from the port.
7542 	 */
7543 	if (emb == LPFC_SLI4_MBX_EMBED) {
7544 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7545 		shdr = &rsrc_ext->header.cfg_shdr;
7546 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7547 	} else {
7548 		virtaddr = mbox->sge_array->addr[0];
7549 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7550 		shdr = &n_rsrc->cfg_shdr;
7551 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7552 	}
7553 
7554 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7555 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7556 			"2984 Failed to read allocated resources "
7557 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7558 			type,
7559 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7560 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7561 		rc = -EIO;
7562 		goto err_exit;
7563 	}
7564  err_exit:
7565 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7566 	return rc;
7567 }
7568 
7569 /**
7570  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7571  * @phba: pointer to lpfc hba data structure.
7572  * @sgl_list: linked link of sgl buffers to post
7573  * @cnt: number of linked list buffers
7574  *
7575  * This routine walks the list of buffers that have been allocated and
7576  * repost them to the port by using SGL block post. This is needed after a
7577  * pci_function_reset/warm_start or start. It attempts to construct blocks
7578  * of buffer sgls which contains contiguous xris and uses the non-embedded
7579  * SGL block post mailbox commands to post them to the port. For single
7580  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7581  * mailbox command for posting.
7582  *
7583  * Returns: 0 = success, non-zero failure.
7584  **/
7585 static int
7586 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7587 			  struct list_head *sgl_list, int cnt)
7588 {
7589 	struct lpfc_sglq *sglq_entry = NULL;
7590 	struct lpfc_sglq *sglq_entry_next = NULL;
7591 	struct lpfc_sglq *sglq_entry_first = NULL;
7592 	int status = 0, total_cnt;
7593 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7594 	int last_xritag = NO_XRI;
7595 	LIST_HEAD(prep_sgl_list);
7596 	LIST_HEAD(blck_sgl_list);
7597 	LIST_HEAD(allc_sgl_list);
7598 	LIST_HEAD(post_sgl_list);
7599 	LIST_HEAD(free_sgl_list);
7600 
7601 	spin_lock_irq(&phba->hbalock);
7602 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7603 	list_splice_init(sgl_list, &allc_sgl_list);
7604 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7605 	spin_unlock_irq(&phba->hbalock);
7606 
7607 	total_cnt = cnt;
7608 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7609 				 &allc_sgl_list, list) {
7610 		list_del_init(&sglq_entry->list);
7611 		block_cnt++;
7612 		if ((last_xritag != NO_XRI) &&
7613 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7614 			/* a hole in xri block, form a sgl posting block */
7615 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7616 			post_cnt = block_cnt - 1;
7617 			/* prepare list for next posting block */
7618 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7619 			block_cnt = 1;
7620 		} else {
7621 			/* prepare list for next posting block */
7622 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7623 			/* enough sgls for non-embed sgl mbox command */
7624 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7625 				list_splice_init(&prep_sgl_list,
7626 						 &blck_sgl_list);
7627 				post_cnt = block_cnt;
7628 				block_cnt = 0;
7629 			}
7630 		}
7631 		num_posted++;
7632 
7633 		/* keep track of last sgl's xritag */
7634 		last_xritag = sglq_entry->sli4_xritag;
7635 
7636 		/* end of repost sgl list condition for buffers */
7637 		if (num_posted == total_cnt) {
7638 			if (post_cnt == 0) {
7639 				list_splice_init(&prep_sgl_list,
7640 						 &blck_sgl_list);
7641 				post_cnt = block_cnt;
7642 			} else if (block_cnt == 1) {
7643 				status = lpfc_sli4_post_sgl(phba,
7644 						sglq_entry->phys, 0,
7645 						sglq_entry->sli4_xritag);
7646 				if (!status) {
7647 					/* successful, put sgl to posted list */
7648 					list_add_tail(&sglq_entry->list,
7649 						      &post_sgl_list);
7650 				} else {
7651 					/* Failure, put sgl to free list */
7652 					lpfc_printf_log(phba, KERN_WARNING,
7653 						LOG_SLI,
7654 						"3159 Failed to post "
7655 						"sgl, xritag:x%x\n",
7656 						sglq_entry->sli4_xritag);
7657 					list_add_tail(&sglq_entry->list,
7658 						      &free_sgl_list);
7659 					total_cnt--;
7660 				}
7661 			}
7662 		}
7663 
7664 		/* continue until a nembed page worth of sgls */
7665 		if (post_cnt == 0)
7666 			continue;
7667 
7668 		/* post the buffer list sgls as a block */
7669 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7670 						 post_cnt);
7671 
7672 		if (!status) {
7673 			/* success, put sgl list to posted sgl list */
7674 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7675 		} else {
7676 			/* Failure, put sgl list to free sgl list */
7677 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7678 							    struct lpfc_sglq,
7679 							    list);
7680 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7681 					"3160 Failed to post sgl-list, "
7682 					"xritag:x%x-x%x\n",
7683 					sglq_entry_first->sli4_xritag,
7684 					(sglq_entry_first->sli4_xritag +
7685 					 post_cnt - 1));
7686 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7687 			total_cnt -= post_cnt;
7688 		}
7689 
7690 		/* don't reset xirtag due to hole in xri block */
7691 		if (block_cnt == 0)
7692 			last_xritag = NO_XRI;
7693 
7694 		/* reset sgl post count for next round of posting */
7695 		post_cnt = 0;
7696 	}
7697 
7698 	/* free the sgls failed to post */
7699 	lpfc_free_sgl_list(phba, &free_sgl_list);
7700 
7701 	/* push sgls posted to the available list */
7702 	if (!list_empty(&post_sgl_list)) {
7703 		spin_lock_irq(&phba->hbalock);
7704 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7705 		list_splice_init(&post_sgl_list, sgl_list);
7706 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7707 		spin_unlock_irq(&phba->hbalock);
7708 	} else {
7709 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7710 				"3161 Failure to post sgl to port,status %x "
7711 				"blkcnt %d totalcnt %d postcnt %d\n",
7712 				status, block_cnt, total_cnt, post_cnt);
7713 		return -EIO;
7714 	}
7715 
7716 	/* return the number of XRIs actually posted */
7717 	return total_cnt;
7718 }
7719 
7720 /**
7721  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7722  * @phba: pointer to lpfc hba data structure.
7723  *
7724  * This routine walks the list of nvme buffers that have been allocated and
7725  * repost them to the port by using SGL block post. This is needed after a
7726  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7727  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7728  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7729  *
7730  * Returns: 0 = success, non-zero failure.
7731  **/
7732 static int
7733 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7734 {
7735 	LIST_HEAD(post_nblist);
7736 	int num_posted, rc = 0;
7737 
7738 	/* get all NVME buffers need to repost to a local list */
7739 	lpfc_io_buf_flush(phba, &post_nblist);
7740 
7741 	/* post the list of nvme buffer sgls to port if available */
7742 	if (!list_empty(&post_nblist)) {
7743 		num_posted = lpfc_sli4_post_io_sgl_list(
7744 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7745 		/* failed to post any nvme buffer, return error */
7746 		if (num_posted == 0)
7747 			rc = -EIO;
7748 	}
7749 	return rc;
7750 }
7751 
7752 static void
7753 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7754 {
7755 	uint32_t len;
7756 
7757 	len = sizeof(struct lpfc_mbx_set_host_data) -
7758 		sizeof(struct lpfc_sli4_cfg_mhdr);
7759 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7760 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7761 			 LPFC_SLI4_MBX_EMBED);
7762 
7763 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7764 	mbox->u.mqe.un.set_host_data.param_len =
7765 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7766 	snprintf(mbox->u.mqe.un.set_host_data.un.data,
7767 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7768 		 "Linux %s v"LPFC_DRIVER_VERSION,
7769 		 test_bit(HBA_FCOE_MODE, &phba->hba_flag) ? "FCoE" : "FC");
7770 }
7771 
7772 int
7773 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7774 		    struct lpfc_queue *drq, int count, int idx)
7775 {
7776 	int rc, i;
7777 	struct lpfc_rqe hrqe;
7778 	struct lpfc_rqe drqe;
7779 	struct lpfc_rqb *rqbp;
7780 	unsigned long flags;
7781 	struct rqb_dmabuf *rqb_buffer;
7782 	LIST_HEAD(rqb_buf_list);
7783 
7784 	rqbp = hrq->rqbp;
7785 	for (i = 0; i < count; i++) {
7786 		spin_lock_irqsave(&phba->hbalock, flags);
7787 		/* IF RQ is already full, don't bother */
7788 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7789 			spin_unlock_irqrestore(&phba->hbalock, flags);
7790 			break;
7791 		}
7792 		spin_unlock_irqrestore(&phba->hbalock, flags);
7793 
7794 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7795 		if (!rqb_buffer)
7796 			break;
7797 		rqb_buffer->hrq = hrq;
7798 		rqb_buffer->drq = drq;
7799 		rqb_buffer->idx = idx;
7800 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7801 	}
7802 
7803 	spin_lock_irqsave(&phba->hbalock, flags);
7804 	while (!list_empty(&rqb_buf_list)) {
7805 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7806 				 hbuf.list);
7807 
7808 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7809 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7810 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7811 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7812 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7813 		if (rc < 0) {
7814 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7815 					"6421 Cannot post to HRQ %d: %x %x %x "
7816 					"DRQ %x %x\n",
7817 					hrq->queue_id,
7818 					hrq->host_index,
7819 					hrq->hba_index,
7820 					hrq->entry_count,
7821 					drq->host_index,
7822 					drq->hba_index);
7823 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7824 		} else {
7825 			list_add_tail(&rqb_buffer->hbuf.list,
7826 				      &rqbp->rqb_buffer_list);
7827 			rqbp->buffer_count++;
7828 		}
7829 	}
7830 	spin_unlock_irqrestore(&phba->hbalock, flags);
7831 	return 1;
7832 }
7833 
7834 static void
7835 lpfc_mbx_cmpl_read_lds_params(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7836 {
7837 	union lpfc_sli4_cfg_shdr *shdr;
7838 	u32 shdr_status, shdr_add_status;
7839 
7840 	shdr = (union lpfc_sli4_cfg_shdr *)
7841 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7842 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7843 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7844 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7845 		lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT | LOG_MBOX,
7846 				"4622 SET_FEATURE (x%x) mbox failed, "
7847 				"status x%x add_status x%x, mbx status x%x\n",
7848 				LPFC_SET_LD_SIGNAL, shdr_status,
7849 				shdr_add_status, pmb->u.mb.mbxStatus);
7850 		phba->degrade_activate_threshold = 0;
7851 		phba->degrade_deactivate_threshold = 0;
7852 		phba->fec_degrade_interval = 0;
7853 		goto out;
7854 	}
7855 
7856 	phba->degrade_activate_threshold = pmb->u.mqe.un.set_feature.word7;
7857 	phba->degrade_deactivate_threshold = pmb->u.mqe.un.set_feature.word8;
7858 	phba->fec_degrade_interval = pmb->u.mqe.un.set_feature.word10;
7859 
7860 	lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT,
7861 			"4624 Success: da x%x dd x%x interval x%x\n",
7862 			phba->degrade_activate_threshold,
7863 			phba->degrade_deactivate_threshold,
7864 			phba->fec_degrade_interval);
7865 out:
7866 	mempool_free(pmb, phba->mbox_mem_pool);
7867 }
7868 
7869 int
7870 lpfc_read_lds_params(struct lpfc_hba *phba)
7871 {
7872 	LPFC_MBOXQ_t *mboxq;
7873 	int rc;
7874 
7875 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7876 	if (!mboxq)
7877 		return -ENOMEM;
7878 
7879 	lpfc_set_features(phba, mboxq, LPFC_SET_LD_SIGNAL);
7880 	mboxq->vport = phba->pport;
7881 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_lds_params;
7882 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7883 	if (rc == MBX_NOT_FINISHED) {
7884 		mempool_free(mboxq, phba->mbox_mem_pool);
7885 		return -EIO;
7886 	}
7887 	return 0;
7888 }
7889 
7890 static void
7891 lpfc_mbx_cmpl_cgn_set_ftrs(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7892 {
7893 	struct lpfc_vport *vport = pmb->vport;
7894 	union lpfc_sli4_cfg_shdr *shdr;
7895 	u32 shdr_status, shdr_add_status;
7896 	u32 sig, acqe;
7897 
7898 	/* Two outcomes. (1) Set featurs was successul and EDC negotiation
7899 	 * is done. (2) Mailbox failed and send FPIN support only.
7900 	 */
7901 	shdr = (union lpfc_sli4_cfg_shdr *)
7902 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7903 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7904 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7905 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7906 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
7907 				"2516 CGN SET_FEATURE mbox failed with "
7908 				"status x%x add_status x%x, mbx status x%x "
7909 				"Reset Congestion to FPINs only\n",
7910 				shdr_status, shdr_add_status,
7911 				pmb->u.mb.mbxStatus);
7912 		/* If there is a mbox error, move on to RDF */
7913 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7914 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7915 		goto out;
7916 	}
7917 
7918 	/* Zero out Congestion Signal ACQE counter */
7919 	phba->cgn_acqe_cnt = 0;
7920 
7921 	acqe = bf_get(lpfc_mbx_set_feature_CGN_acqe_freq,
7922 		      &pmb->u.mqe.un.set_feature);
7923 	sig = bf_get(lpfc_mbx_set_feature_CGN_warn_freq,
7924 		     &pmb->u.mqe.un.set_feature);
7925 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7926 			"4620 SET_FEATURES Success: Freq: %ds %dms "
7927 			" Reg: x%x x%x\n", acqe, sig,
7928 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7929 out:
7930 	mempool_free(pmb, phba->mbox_mem_pool);
7931 
7932 	/* Register for FPIN events from the fabric now that the
7933 	 * EDC common_set_features has completed.
7934 	 */
7935 	lpfc_issue_els_rdf(vport, 0);
7936 }
7937 
7938 int
7939 lpfc_config_cgn_signal(struct lpfc_hba *phba)
7940 {
7941 	LPFC_MBOXQ_t *mboxq;
7942 	u32 rc;
7943 
7944 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7945 	if (!mboxq)
7946 		goto out_rdf;
7947 
7948 	lpfc_set_features(phba, mboxq, LPFC_SET_CGN_SIGNAL);
7949 	mboxq->vport = phba->pport;
7950 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_cgn_set_ftrs;
7951 
7952 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7953 			"4621 SET_FEATURES: FREQ sig x%x acqe x%x: "
7954 			"Reg: x%x x%x\n",
7955 			phba->cgn_sig_freq, lpfc_acqe_cgn_frequency,
7956 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7957 
7958 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7959 	if (rc == MBX_NOT_FINISHED)
7960 		goto out;
7961 	return 0;
7962 
7963 out:
7964 	mempool_free(mboxq, phba->mbox_mem_pool);
7965 out_rdf:
7966 	/* If there is a mbox error, move on to RDF */
7967 	phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7968 	phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7969 	lpfc_issue_els_rdf(phba->pport, 0);
7970 	return -EIO;
7971 }
7972 
7973 /**
7974  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7975  * @phba: pointer to lpfc hba data structure.
7976  *
7977  * This routine initializes the per-eq idle_stat to dynamically dictate
7978  * polling decisions.
7979  *
7980  * Return codes:
7981  *   None
7982  **/
7983 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
7984 {
7985 	int i;
7986 	struct lpfc_sli4_hdw_queue *hdwq;
7987 	struct lpfc_queue *eq;
7988 	struct lpfc_idle_stat *idle_stat;
7989 	u64 wall;
7990 
7991 	for_each_present_cpu(i) {
7992 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
7993 		eq = hdwq->hba_eq;
7994 
7995 		/* Skip if we've already handled this eq's primary CPU */
7996 		if (eq->chann != i)
7997 			continue;
7998 
7999 		idle_stat = &phba->sli4_hba.idle_stat[i];
8000 
8001 		idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
8002 		idle_stat->prev_wall = wall;
8003 
8004 		if (phba->nvmet_support ||
8005 		    phba->cmf_active_mode != LPFC_CFG_OFF ||
8006 		    phba->intr_type != MSIX)
8007 			eq->poll_mode = LPFC_QUEUE_WORK;
8008 		else
8009 			eq->poll_mode = LPFC_THREADED_IRQ;
8010 	}
8011 
8012 	if (!phba->nvmet_support && phba->intr_type == MSIX)
8013 		schedule_delayed_work(&phba->idle_stat_delay_work,
8014 				      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
8015 }
8016 
8017 static void lpfc_sli4_dip(struct lpfc_hba *phba)
8018 {
8019 	uint32_t if_type;
8020 
8021 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
8022 	if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
8023 	    if_type == LPFC_SLI_INTF_IF_TYPE_6) {
8024 		struct lpfc_register reg_data;
8025 
8026 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
8027 			       &reg_data.word0))
8028 			return;
8029 
8030 		if (bf_get(lpfc_sliport_status_dip, &reg_data))
8031 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8032 					"2904 Firmware Dump Image Present"
8033 					" on Adapter");
8034 	}
8035 }
8036 
8037 /**
8038  * lpfc_rx_monitor_create_ring - Initialize ring buffer for rx_monitor
8039  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8040  * @entries: Number of rx_info_entry objects to allocate in ring
8041  *
8042  * Return:
8043  * 0 - Success
8044  * ENOMEM - Failure to kmalloc
8045  **/
8046 int lpfc_rx_monitor_create_ring(struct lpfc_rx_info_monitor *rx_monitor,
8047 				u32 entries)
8048 {
8049 	rx_monitor->ring = kmalloc_array(entries, sizeof(struct rx_info_entry),
8050 					 GFP_KERNEL);
8051 	if (!rx_monitor->ring)
8052 		return -ENOMEM;
8053 
8054 	rx_monitor->head_idx = 0;
8055 	rx_monitor->tail_idx = 0;
8056 	spin_lock_init(&rx_monitor->lock);
8057 	rx_monitor->entries = entries;
8058 
8059 	return 0;
8060 }
8061 
8062 /**
8063  * lpfc_rx_monitor_destroy_ring - Free ring buffer for rx_monitor
8064  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8065  *
8066  * Called after cancellation of cmf_timer.
8067  **/
8068 void lpfc_rx_monitor_destroy_ring(struct lpfc_rx_info_monitor *rx_monitor)
8069 {
8070 	kfree(rx_monitor->ring);
8071 	rx_monitor->ring = NULL;
8072 	rx_monitor->entries = 0;
8073 	rx_monitor->head_idx = 0;
8074 	rx_monitor->tail_idx = 0;
8075 }
8076 
8077 /**
8078  * lpfc_rx_monitor_record - Insert an entry into rx_monitor's ring
8079  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8080  * @entry: Pointer to rx_info_entry
8081  *
8082  * Used to insert an rx_info_entry into rx_monitor's ring.  Note that this is a
8083  * deep copy of rx_info_entry not a shallow copy of the rx_info_entry ptr.
8084  *
8085  * This is called from lpfc_cmf_timer, which is in timer/softirq context.
8086  *
8087  * In cases of old data overflow, we do a best effort of FIFO order.
8088  **/
8089 void lpfc_rx_monitor_record(struct lpfc_rx_info_monitor *rx_monitor,
8090 			    struct rx_info_entry *entry)
8091 {
8092 	struct rx_info_entry *ring = rx_monitor->ring;
8093 	u32 *head_idx = &rx_monitor->head_idx;
8094 	u32 *tail_idx = &rx_monitor->tail_idx;
8095 	spinlock_t *ring_lock = &rx_monitor->lock;
8096 	u32 ring_size = rx_monitor->entries;
8097 
8098 	spin_lock(ring_lock);
8099 	memcpy(&ring[*tail_idx], entry, sizeof(*entry));
8100 	*tail_idx = (*tail_idx + 1) % ring_size;
8101 
8102 	/* Best effort of FIFO saved data */
8103 	if (*tail_idx == *head_idx)
8104 		*head_idx = (*head_idx + 1) % ring_size;
8105 
8106 	spin_unlock(ring_lock);
8107 }
8108 
8109 /**
8110  * lpfc_rx_monitor_report - Read out rx_monitor's ring
8111  * @phba: Pointer to lpfc_hba object
8112  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8113  * @buf: Pointer to char buffer that will contain rx monitor info data
8114  * @buf_len: Length buf including null char
8115  * @max_read_entries: Maximum number of entries to read out of ring
8116  *
8117  * Used to dump/read what's in rx_monitor's ring buffer.
8118  *
8119  * If buf is NULL || buf_len == 0, then it is implied that we want to log the
8120  * information to kmsg instead of filling out buf.
8121  *
8122  * Return:
8123  * Number of entries read out of the ring
8124  **/
8125 u32 lpfc_rx_monitor_report(struct lpfc_hba *phba,
8126 			   struct lpfc_rx_info_monitor *rx_monitor, char *buf,
8127 			   u32 buf_len, u32 max_read_entries)
8128 {
8129 	struct rx_info_entry *ring = rx_monitor->ring;
8130 	struct rx_info_entry *entry;
8131 	u32 *head_idx = &rx_monitor->head_idx;
8132 	u32 *tail_idx = &rx_monitor->tail_idx;
8133 	spinlock_t *ring_lock = &rx_monitor->lock;
8134 	u32 ring_size = rx_monitor->entries;
8135 	u32 cnt = 0;
8136 	char tmp[DBG_LOG_STR_SZ] = {0};
8137 	bool log_to_kmsg = (!buf || !buf_len) ? true : false;
8138 
8139 	if (!log_to_kmsg) {
8140 		/* clear the buffer to be sure */
8141 		memset(buf, 0, buf_len);
8142 
8143 		scnprintf(buf, buf_len, "\t%-16s%-16s%-16s%-16s%-8s%-8s%-8s"
8144 					"%-8s%-8s%-8s%-16s\n",
8145 					"MaxBPI", "Tot_Data_CMF",
8146 					"Tot_Data_Cmd", "Tot_Data_Cmpl",
8147 					"Lat(us)", "Avg_IO", "Max_IO", "Bsy",
8148 					"IO_cnt", "Info", "BWutil(ms)");
8149 	}
8150 
8151 	/* Needs to be _irq because record is called from timer interrupt
8152 	 * context
8153 	 */
8154 	spin_lock_irq(ring_lock);
8155 	while (*head_idx != *tail_idx) {
8156 		entry = &ring[*head_idx];
8157 
8158 		/* Read out this entry's data. */
8159 		if (!log_to_kmsg) {
8160 			/* If !log_to_kmsg, then store to buf. */
8161 			scnprintf(tmp, sizeof(tmp),
8162 				  "%03d:\t%-16llu%-16llu%-16llu%-16llu%-8llu"
8163 				  "%-8llu%-8llu%-8u%-8u%-8u%u(%u)\n",
8164 				  *head_idx, entry->max_bytes_per_interval,
8165 				  entry->cmf_bytes, entry->total_bytes,
8166 				  entry->rcv_bytes, entry->avg_io_latency,
8167 				  entry->avg_io_size, entry->max_read_cnt,
8168 				  entry->cmf_busy, entry->io_cnt,
8169 				  entry->cmf_info, entry->timer_utilization,
8170 				  entry->timer_interval);
8171 
8172 			/* Check for buffer overflow */
8173 			if ((strlen(buf) + strlen(tmp)) >= buf_len)
8174 				break;
8175 
8176 			/* Append entry's data to buffer */
8177 			strlcat(buf, tmp, buf_len);
8178 		} else {
8179 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
8180 					"4410 %02u: MBPI %llu Xmit %llu "
8181 					"Cmpl %llu Lat %llu ASz %llu Info %02u "
8182 					"BWUtil %u Int %u slot %u\n",
8183 					cnt, entry->max_bytes_per_interval,
8184 					entry->total_bytes, entry->rcv_bytes,
8185 					entry->avg_io_latency,
8186 					entry->avg_io_size, entry->cmf_info,
8187 					entry->timer_utilization,
8188 					entry->timer_interval, *head_idx);
8189 		}
8190 
8191 		*head_idx = (*head_idx + 1) % ring_size;
8192 
8193 		/* Don't feed more than max_read_entries */
8194 		cnt++;
8195 		if (cnt >= max_read_entries)
8196 			break;
8197 	}
8198 	spin_unlock_irq(ring_lock);
8199 
8200 	return cnt;
8201 }
8202 
8203 /**
8204  * lpfc_cmf_setup - Initialize idle_stat tracking
8205  * @phba: Pointer to HBA context object.
8206  *
8207  * This is called from HBA setup during driver load or when the HBA
8208  * comes online. this does all the initialization to support CMF and MI.
8209  **/
8210 static int
8211 lpfc_cmf_setup(struct lpfc_hba *phba)
8212 {
8213 	LPFC_MBOXQ_t *mboxq;
8214 	struct lpfc_dmabuf *mp;
8215 	struct lpfc_pc_sli4_params *sli4_params;
8216 	int rc, cmf, mi_ver;
8217 
8218 	rc = lpfc_sli4_refresh_params(phba);
8219 	if (unlikely(rc))
8220 		return rc;
8221 
8222 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8223 	if (!mboxq)
8224 		return -ENOMEM;
8225 
8226 	sli4_params = &phba->sli4_hba.pc_sli4_params;
8227 
8228 	/* Always try to enable MI feature if we can */
8229 	if (sli4_params->mi_ver) {
8230 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_MI);
8231 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8232 		mi_ver = bf_get(lpfc_mbx_set_feature_mi,
8233 				 &mboxq->u.mqe.un.set_feature);
8234 
8235 		if (rc == MBX_SUCCESS) {
8236 			if (mi_ver) {
8237 				lpfc_printf_log(phba,
8238 						KERN_WARNING, LOG_CGN_MGMT,
8239 						"6215 MI is enabled\n");
8240 				sli4_params->mi_ver = mi_ver;
8241 			} else {
8242 				lpfc_printf_log(phba,
8243 						KERN_WARNING, LOG_CGN_MGMT,
8244 						"6338 MI is disabled\n");
8245 				sli4_params->mi_ver = 0;
8246 			}
8247 		} else {
8248 			/* mi_ver is already set from GET_SLI4_PARAMETERS */
8249 			lpfc_printf_log(phba, KERN_INFO,
8250 					LOG_CGN_MGMT | LOG_INIT,
8251 					"6245 Enable MI Mailbox x%x (x%x/x%x) "
8252 					"failed, rc:x%x mi:x%x\n",
8253 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8254 					lpfc_sli_config_mbox_subsys_get
8255 						(phba, mboxq),
8256 					lpfc_sli_config_mbox_opcode_get
8257 						(phba, mboxq),
8258 					rc, sli4_params->mi_ver);
8259 		}
8260 	} else {
8261 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8262 				"6217 MI is disabled\n");
8263 	}
8264 
8265 	/* Ensure FDMI is enabled for MI if enable_mi is set */
8266 	if (sli4_params->mi_ver)
8267 		phba->cfg_fdmi_on = LPFC_FDMI_SUPPORT;
8268 
8269 	/* Always try to enable CMF feature if we can */
8270 	if (sli4_params->cmf) {
8271 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_CMF);
8272 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8273 		cmf = bf_get(lpfc_mbx_set_feature_cmf,
8274 			     &mboxq->u.mqe.un.set_feature);
8275 		if (rc == MBX_SUCCESS && cmf) {
8276 			lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8277 					"6218 CMF is enabled: mode %d\n",
8278 					phba->cmf_active_mode);
8279 		} else {
8280 			lpfc_printf_log(phba, KERN_WARNING,
8281 					LOG_CGN_MGMT | LOG_INIT,
8282 					"6219 Enable CMF Mailbox x%x (x%x/x%x) "
8283 					"failed, rc:x%x dd:x%x\n",
8284 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8285 					lpfc_sli_config_mbox_subsys_get
8286 						(phba, mboxq),
8287 					lpfc_sli_config_mbox_opcode_get
8288 						(phba, mboxq),
8289 					rc, cmf);
8290 			sli4_params->cmf = 0;
8291 			phba->cmf_active_mode = LPFC_CFG_OFF;
8292 			goto no_cmf;
8293 		}
8294 
8295 		/* Allocate Congestion Information Buffer */
8296 		if (!phba->cgn_i) {
8297 			mp = kmalloc(sizeof(*mp), GFP_KERNEL);
8298 			if (mp)
8299 				mp->virt = dma_alloc_coherent
8300 						(&phba->pcidev->dev,
8301 						sizeof(struct lpfc_cgn_info),
8302 						&mp->phys, GFP_KERNEL);
8303 			if (!mp || !mp->virt) {
8304 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8305 						"2640 Failed to alloc memory "
8306 						"for Congestion Info\n");
8307 				kfree(mp);
8308 				sli4_params->cmf = 0;
8309 				phba->cmf_active_mode = LPFC_CFG_OFF;
8310 				goto no_cmf;
8311 			}
8312 			phba->cgn_i = mp;
8313 
8314 			/* initialize congestion buffer info */
8315 			lpfc_init_congestion_buf(phba);
8316 			lpfc_init_congestion_stat(phba);
8317 
8318 			/* Zero out Congestion Signal counters */
8319 			atomic64_set(&phba->cgn_acqe_stat.alarm, 0);
8320 			atomic64_set(&phba->cgn_acqe_stat.warn, 0);
8321 		}
8322 
8323 		rc = lpfc_sli4_cgn_params_read(phba);
8324 		if (rc < 0) {
8325 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8326 					"6242 Error reading Cgn Params (%d)\n",
8327 					rc);
8328 			/* Ensure CGN Mode is off */
8329 			sli4_params->cmf = 0;
8330 		} else if (!rc) {
8331 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8332 					"6243 CGN Event empty object.\n");
8333 			/* Ensure CGN Mode is off */
8334 			sli4_params->cmf = 0;
8335 		}
8336 	} else {
8337 no_cmf:
8338 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8339 				"6220 CMF is disabled\n");
8340 	}
8341 
8342 	/* Only register congestion buffer with firmware if BOTH
8343 	 * CMF and E2E are enabled.
8344 	 */
8345 	if (sli4_params->cmf && sli4_params->mi_ver) {
8346 		rc = lpfc_reg_congestion_buf(phba);
8347 		if (rc) {
8348 			dma_free_coherent(&phba->pcidev->dev,
8349 					  sizeof(struct lpfc_cgn_info),
8350 					  phba->cgn_i->virt, phba->cgn_i->phys);
8351 			kfree(phba->cgn_i);
8352 			phba->cgn_i = NULL;
8353 			/* Ensure CGN Mode is off */
8354 			phba->cmf_active_mode = LPFC_CFG_OFF;
8355 			sli4_params->cmf = 0;
8356 			return 0;
8357 		}
8358 	}
8359 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8360 			"6470 Setup MI version %d CMF %d mode %d\n",
8361 			sli4_params->mi_ver, sli4_params->cmf,
8362 			phba->cmf_active_mode);
8363 
8364 	mempool_free(mboxq, phba->mbox_mem_pool);
8365 
8366 	/* Initialize atomic counters */
8367 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
8368 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
8369 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
8370 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
8371 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
8372 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
8373 	atomic64_set(&phba->cgn_latency_evt, 0);
8374 
8375 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
8376 
8377 	/* Allocate RX Monitor Buffer */
8378 	if (!phba->rx_monitor) {
8379 		phba->rx_monitor = kzalloc(sizeof(*phba->rx_monitor),
8380 					   GFP_KERNEL);
8381 
8382 		if (!phba->rx_monitor) {
8383 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8384 					"2644 Failed to alloc memory "
8385 					"for RX Monitor Buffer\n");
8386 			return -ENOMEM;
8387 		}
8388 
8389 		/* Instruct the rx_monitor object to instantiate its ring */
8390 		if (lpfc_rx_monitor_create_ring(phba->rx_monitor,
8391 						LPFC_MAX_RXMONITOR_ENTRY)) {
8392 			kfree(phba->rx_monitor);
8393 			phba->rx_monitor = NULL;
8394 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8395 					"2645 Failed to alloc memory "
8396 					"for RX Monitor's Ring\n");
8397 			return -ENOMEM;
8398 		}
8399 	}
8400 
8401 	return 0;
8402 }
8403 
8404 static int
8405 lpfc_set_host_tm(struct lpfc_hba *phba)
8406 {
8407 	LPFC_MBOXQ_t *mboxq;
8408 	uint32_t len, rc;
8409 	struct timespec64 cur_time;
8410 	struct tm broken;
8411 	uint32_t month, day, year;
8412 	uint32_t hour, minute, second;
8413 	struct lpfc_mbx_set_host_date_time *tm;
8414 
8415 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8416 	if (!mboxq)
8417 		return -ENOMEM;
8418 
8419 	len = sizeof(struct lpfc_mbx_set_host_data) -
8420 		sizeof(struct lpfc_sli4_cfg_mhdr);
8421 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
8422 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
8423 			 LPFC_SLI4_MBX_EMBED);
8424 
8425 	mboxq->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_DATE_TIME;
8426 	mboxq->u.mqe.un.set_host_data.param_len =
8427 			sizeof(struct lpfc_mbx_set_host_date_time);
8428 	tm = &mboxq->u.mqe.un.set_host_data.un.tm;
8429 	ktime_get_real_ts64(&cur_time);
8430 	time64_to_tm(cur_time.tv_sec, 0, &broken);
8431 	month = broken.tm_mon + 1;
8432 	day = broken.tm_mday;
8433 	year = broken.tm_year - 100;
8434 	hour = broken.tm_hour;
8435 	minute = broken.tm_min;
8436 	second = broken.tm_sec;
8437 	bf_set(lpfc_mbx_set_host_month, tm, month);
8438 	bf_set(lpfc_mbx_set_host_day, tm, day);
8439 	bf_set(lpfc_mbx_set_host_year, tm, year);
8440 	bf_set(lpfc_mbx_set_host_hour, tm, hour);
8441 	bf_set(lpfc_mbx_set_host_min, tm, minute);
8442 	bf_set(lpfc_mbx_set_host_sec, tm, second);
8443 
8444 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8445 	mempool_free(mboxq, phba->mbox_mem_pool);
8446 	return rc;
8447 }
8448 
8449 /**
8450  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
8451  * @phba: Pointer to HBA context object.
8452  *
8453  * This function is the main SLI4 device initialization PCI function. This
8454  * function is called by the HBA initialization code, HBA reset code and
8455  * HBA error attention handler code. Caller is not required to hold any
8456  * locks.
8457  **/
8458 int
8459 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
8460 {
8461 	int rc, i, cnt, len, dd;
8462 	LPFC_MBOXQ_t *mboxq;
8463 	struct lpfc_mqe *mqe;
8464 	uint8_t *vpd;
8465 	uint32_t vpd_size;
8466 	uint32_t ftr_rsp = 0;
8467 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
8468 	struct lpfc_vport *vport = phba->pport;
8469 	struct lpfc_dmabuf *mp;
8470 	struct lpfc_rqb *rqbp;
8471 	u32 flg;
8472 
8473 	/* Perform a PCI function reset to start from clean */
8474 	rc = lpfc_pci_function_reset(phba);
8475 	if (unlikely(rc))
8476 		return -ENODEV;
8477 
8478 	/* Check the HBA Host Status Register for readyness */
8479 	rc = lpfc_sli4_post_status_check(phba);
8480 	if (unlikely(rc))
8481 		return -ENODEV;
8482 	else {
8483 		spin_lock_irq(&phba->hbalock);
8484 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
8485 		flg = phba->sli.sli_flag;
8486 		spin_unlock_irq(&phba->hbalock);
8487 		/* Allow a little time after setting SLI_ACTIVE for any polled
8488 		 * MBX commands to complete via BSG.
8489 		 */
8490 		for (i = 0; i < 50 && (flg & LPFC_SLI_MBOX_ACTIVE); i++) {
8491 			msleep(20);
8492 			spin_lock_irq(&phba->hbalock);
8493 			flg = phba->sli.sli_flag;
8494 			spin_unlock_irq(&phba->hbalock);
8495 		}
8496 	}
8497 	clear_bit(HBA_SETUP, &phba->hba_flag);
8498 
8499 	lpfc_sli4_dip(phba);
8500 
8501 	/*
8502 	 * Allocate a single mailbox container for initializing the
8503 	 * port.
8504 	 */
8505 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8506 	if (!mboxq)
8507 		return -ENOMEM;
8508 
8509 	/* Issue READ_REV to collect vpd and FW information. */
8510 	vpd_size = SLI4_PAGE_SIZE;
8511 	vpd = kzalloc(vpd_size, GFP_KERNEL);
8512 	if (!vpd) {
8513 		rc = -ENOMEM;
8514 		goto out_free_mbox;
8515 	}
8516 
8517 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
8518 	if (unlikely(rc)) {
8519 		kfree(vpd);
8520 		goto out_free_mbox;
8521 	}
8522 
8523 	mqe = &mboxq->u.mqe;
8524 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
8525 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
8526 		set_bit(HBA_FCOE_MODE, &phba->hba_flag);
8527 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
8528 	} else {
8529 		clear_bit(HBA_FCOE_MODE, &phba->hba_flag);
8530 	}
8531 
8532 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
8533 		LPFC_DCBX_CEE_MODE)
8534 		set_bit(HBA_FIP_SUPPORT, &phba->hba_flag);
8535 	else
8536 		clear_bit(HBA_FIP_SUPPORT, &phba->hba_flag);
8537 
8538 	clear_bit(HBA_IOQ_FLUSH, &phba->hba_flag);
8539 
8540 	if (phba->sli_rev != LPFC_SLI_REV4) {
8541 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8542 			"0376 READ_REV Error. SLI Level %d "
8543 			"FCoE enabled %d\n",
8544 			phba->sli_rev,
8545 			test_bit(HBA_FCOE_MODE, &phba->hba_flag) ? 1 : 0);
8546 		rc = -EIO;
8547 		kfree(vpd);
8548 		goto out_free_mbox;
8549 	}
8550 
8551 	rc = lpfc_set_host_tm(phba);
8552 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
8553 			"6468 Set host date / time: Status x%x:\n", rc);
8554 
8555 	/*
8556 	 * Continue initialization with default values even if driver failed
8557 	 * to read FCoE param config regions, only read parameters if the
8558 	 * board is FCoE
8559 	 */
8560 	if (test_bit(HBA_FCOE_MODE, &phba->hba_flag) &&
8561 	    lpfc_sli4_read_fcoe_params(phba))
8562 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
8563 			"2570 Failed to read FCoE parameters\n");
8564 
8565 	/*
8566 	 * Retrieve sli4 device physical port name, failure of doing it
8567 	 * is considered as non-fatal.
8568 	 */
8569 	rc = lpfc_sli4_retrieve_pport_name(phba);
8570 	if (!rc)
8571 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8572 				"3080 Successful retrieving SLI4 device "
8573 				"physical port name: %s.\n", phba->Port);
8574 
8575 	rc = lpfc_sli4_get_ctl_attr(phba);
8576 	if (!rc)
8577 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8578 				"8351 Successful retrieving SLI4 device "
8579 				"CTL ATTR\n");
8580 
8581 	/*
8582 	 * Evaluate the read rev and vpd data. Populate the driver
8583 	 * state with the results. If this routine fails, the failure
8584 	 * is not fatal as the driver will use generic values.
8585 	 */
8586 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
8587 	if (unlikely(!rc))
8588 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8589 				"0377 Error %d parsing vpd. "
8590 				"Using defaults.\n", rc);
8591 	kfree(vpd);
8592 
8593 	/* Save information as VPD data */
8594 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
8595 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
8596 
8597 	/*
8598 	 * This is because first G7 ASIC doesn't support the standard
8599 	 * 0x5a NVME cmd descriptor type/subtype
8600 	 */
8601 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8602 			LPFC_SLI_INTF_IF_TYPE_6) &&
8603 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
8604 	    (phba->vpd.rev.smRev == 0) &&
8605 	    (phba->cfg_nvme_embed_cmd == 1))
8606 		phba->cfg_nvme_embed_cmd = 0;
8607 
8608 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
8609 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
8610 					 &mqe->un.read_rev);
8611 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
8612 				       &mqe->un.read_rev);
8613 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
8614 					    &mqe->un.read_rev);
8615 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
8616 					   &mqe->un.read_rev);
8617 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
8618 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
8619 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
8620 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
8621 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
8622 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
8623 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8624 			"(%d):0380 READ_REV Status x%x "
8625 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
8626 			mboxq->vport ? mboxq->vport->vpi : 0,
8627 			bf_get(lpfc_mqe_status, mqe),
8628 			phba->vpd.rev.opFwName,
8629 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
8630 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
8631 
8632 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8633 	    LPFC_SLI_INTF_IF_TYPE_0) {
8634 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
8635 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8636 		if (rc == MBX_SUCCESS) {
8637 			set_bit(HBA_RECOVERABLE_UE, &phba->hba_flag);
8638 			/* Set 1Sec interval to detect UE */
8639 			phba->eratt_poll_interval = 1;
8640 			phba->sli4_hba.ue_to_sr = bf_get(
8641 					lpfc_mbx_set_feature_UESR,
8642 					&mboxq->u.mqe.un.set_feature);
8643 			phba->sli4_hba.ue_to_rp = bf_get(
8644 					lpfc_mbx_set_feature_UERP,
8645 					&mboxq->u.mqe.un.set_feature);
8646 		}
8647 	}
8648 
8649 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
8650 		/* Enable MDS Diagnostics only if the SLI Port supports it */
8651 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
8652 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8653 		if (rc != MBX_SUCCESS)
8654 			phba->mds_diags_support = 0;
8655 	}
8656 
8657 	/*
8658 	 * Discover the port's supported feature set and match it against the
8659 	 * hosts requests.
8660 	 */
8661 	lpfc_request_features(phba, mboxq);
8662 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8663 	if (unlikely(rc)) {
8664 		rc = -EIO;
8665 		goto out_free_mbox;
8666 	}
8667 
8668 	/* Disable VMID if app header is not supported */
8669 	if (phba->cfg_vmid_app_header && !(bf_get(lpfc_mbx_rq_ftr_rsp_ashdr,
8670 						  &mqe->un.req_ftrs))) {
8671 		bf_set(lpfc_ftr_ashdr, &phba->sli4_hba.sli4_flags, 0);
8672 		phba->cfg_vmid_app_header = 0;
8673 		lpfc_printf_log(phba, KERN_DEBUG, LOG_SLI,
8674 				"1242 vmid feature not supported\n");
8675 	}
8676 
8677 	/*
8678 	 * The port must support FCP initiator mode as this is the
8679 	 * only mode running in the host.
8680 	 */
8681 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
8682 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8683 				"0378 No support for fcpi mode.\n");
8684 		ftr_rsp++;
8685 	}
8686 
8687 	/* Performance Hints are ONLY for FCoE */
8688 	if (test_bit(HBA_FCOE_MODE, &phba->hba_flag)) {
8689 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
8690 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
8691 		else
8692 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
8693 	}
8694 
8695 	/*
8696 	 * If the port cannot support the host's requested features
8697 	 * then turn off the global config parameters to disable the
8698 	 * feature in the driver.  This is not a fatal error.
8699 	 */
8700 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8701 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
8702 			phba->cfg_enable_bg = 0;
8703 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
8704 			ftr_rsp++;
8705 		}
8706 	}
8707 
8708 	if (phba->max_vpi && phba->cfg_enable_npiv &&
8709 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8710 		ftr_rsp++;
8711 
8712 	if (ftr_rsp) {
8713 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8714 				"0379 Feature Mismatch Data: x%08x %08x "
8715 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
8716 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
8717 				phba->cfg_enable_npiv, phba->max_vpi);
8718 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
8719 			phba->cfg_enable_bg = 0;
8720 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8721 			phba->cfg_enable_npiv = 0;
8722 	}
8723 
8724 	/* These SLI3 features are assumed in SLI4 */
8725 	spin_lock_irq(&phba->hbalock);
8726 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
8727 	spin_unlock_irq(&phba->hbalock);
8728 
8729 	/* Always try to enable dual dump feature if we can */
8730 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
8731 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8732 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
8733 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
8734 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8735 				"6448 Dual Dump is enabled\n");
8736 	else
8737 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
8738 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
8739 				"rc:x%x dd:x%x\n",
8740 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8741 				lpfc_sli_config_mbox_subsys_get(
8742 					phba, mboxq),
8743 				lpfc_sli_config_mbox_opcode_get(
8744 					phba, mboxq),
8745 				rc, dd);
8746 
8747 	/*
8748 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
8749 	 * calls depends on these resources to complete port setup.
8750 	 */
8751 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
8752 	if (rc) {
8753 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8754 				"2920 Failed to alloc Resource IDs "
8755 				"rc = x%x\n", rc);
8756 		goto out_free_mbox;
8757 	}
8758 
8759 	lpfc_sli4_node_rpi_restore(phba);
8760 
8761 	lpfc_set_host_data(phba, mboxq);
8762 
8763 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8764 	if (rc) {
8765 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8766 				"2134 Failed to set host os driver version %x",
8767 				rc);
8768 	}
8769 
8770 	/* Read the port's service parameters. */
8771 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
8772 	if (rc) {
8773 		phba->link_state = LPFC_HBA_ERROR;
8774 		rc = -ENOMEM;
8775 		goto out_free_mbox;
8776 	}
8777 
8778 	mboxq->vport = vport;
8779 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8780 	mp = mboxq->ctx_buf;
8781 	if (rc == MBX_SUCCESS) {
8782 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
8783 		rc = 0;
8784 	}
8785 
8786 	/*
8787 	 * This memory was allocated by the lpfc_read_sparam routine but is
8788 	 * no longer needed.  It is released and ctx_buf NULLed to prevent
8789 	 * unintended pointer access as the mbox is reused.
8790 	 */
8791 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
8792 	kfree(mp);
8793 	mboxq->ctx_buf = NULL;
8794 	if (unlikely(rc)) {
8795 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8796 				"0382 READ_SPARAM command failed "
8797 				"status %d, mbxStatus x%x\n",
8798 				rc, bf_get(lpfc_mqe_status, mqe));
8799 		phba->link_state = LPFC_HBA_ERROR;
8800 		rc = -EIO;
8801 		goto out_free_mbox;
8802 	}
8803 
8804 	lpfc_update_vport_wwn(vport);
8805 
8806 	/* Update the fc_host data structures with new wwn. */
8807 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
8808 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
8809 
8810 	/* Create all the SLI4 queues */
8811 	rc = lpfc_sli4_queue_create(phba);
8812 	if (rc) {
8813 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8814 				"3089 Failed to allocate queues\n");
8815 		rc = -ENODEV;
8816 		goto out_free_mbox;
8817 	}
8818 	/* Set up all the queues to the device */
8819 	rc = lpfc_sli4_queue_setup(phba);
8820 	if (unlikely(rc)) {
8821 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8822 				"0381 Error %d during queue setup.\n", rc);
8823 		goto out_destroy_queue;
8824 	}
8825 	/* Initialize the driver internal SLI layer lists. */
8826 	lpfc_sli4_setup(phba);
8827 	lpfc_sli4_queue_init(phba);
8828 
8829 	/* update host els xri-sgl sizes and mappings */
8830 	rc = lpfc_sli4_els_sgl_update(phba);
8831 	if (unlikely(rc)) {
8832 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8833 				"1400 Failed to update xri-sgl size and "
8834 				"mapping: %d\n", rc);
8835 		goto out_destroy_queue;
8836 	}
8837 
8838 	/* register the els sgl pool to the port */
8839 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
8840 				       phba->sli4_hba.els_xri_cnt);
8841 	if (unlikely(rc < 0)) {
8842 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8843 				"0582 Error %d during els sgl post "
8844 				"operation\n", rc);
8845 		rc = -ENODEV;
8846 		goto out_destroy_queue;
8847 	}
8848 	phba->sli4_hba.els_xri_cnt = rc;
8849 
8850 	if (phba->nvmet_support) {
8851 		/* update host nvmet xri-sgl sizes and mappings */
8852 		rc = lpfc_sli4_nvmet_sgl_update(phba);
8853 		if (unlikely(rc)) {
8854 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8855 					"6308 Failed to update nvmet-sgl size "
8856 					"and mapping: %d\n", rc);
8857 			goto out_destroy_queue;
8858 		}
8859 
8860 		/* register the nvmet sgl pool to the port */
8861 		rc = lpfc_sli4_repost_sgl_list(
8862 			phba,
8863 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
8864 			phba->sli4_hba.nvmet_xri_cnt);
8865 		if (unlikely(rc < 0)) {
8866 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8867 					"3117 Error %d during nvmet "
8868 					"sgl post\n", rc);
8869 			rc = -ENODEV;
8870 			goto out_destroy_queue;
8871 		}
8872 		phba->sli4_hba.nvmet_xri_cnt = rc;
8873 
8874 		/* We allocate an iocbq for every receive context SGL.
8875 		 * The additional allocation is for abort and ls handling.
8876 		 */
8877 		cnt = phba->sli4_hba.nvmet_xri_cnt +
8878 			phba->sli4_hba.max_cfg_param.max_xri;
8879 	} else {
8880 		/* update host common xri-sgl sizes and mappings */
8881 		rc = lpfc_sli4_io_sgl_update(phba);
8882 		if (unlikely(rc)) {
8883 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8884 					"6082 Failed to update nvme-sgl size "
8885 					"and mapping: %d\n", rc);
8886 			goto out_destroy_queue;
8887 		}
8888 
8889 		/* register the allocated common sgl pool to the port */
8890 		rc = lpfc_sli4_repost_io_sgl_list(phba);
8891 		if (unlikely(rc)) {
8892 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8893 					"6116 Error %d during nvme sgl post "
8894 					"operation\n", rc);
8895 			/* Some NVME buffers were moved to abort nvme list */
8896 			/* A pci function reset will repost them */
8897 			rc = -ENODEV;
8898 			goto out_destroy_queue;
8899 		}
8900 		/* Each lpfc_io_buf job structure has an iocbq element.
8901 		 * This cnt provides for abort, els, ct and ls requests.
8902 		 */
8903 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
8904 	}
8905 
8906 	if (!phba->sli.iocbq_lookup) {
8907 		/* Initialize and populate the iocb list per host */
8908 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8909 				"2821 initialize iocb list with %d entries\n",
8910 				cnt);
8911 		rc = lpfc_init_iocb_list(phba, cnt);
8912 		if (rc) {
8913 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8914 					"1413 Failed to init iocb list.\n");
8915 			goto out_destroy_queue;
8916 		}
8917 	}
8918 
8919 	if (phba->nvmet_support)
8920 		lpfc_nvmet_create_targetport(phba);
8921 
8922 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
8923 		/* Post initial buffers to all RQs created */
8924 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
8925 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
8926 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
8927 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
8928 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
8929 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
8930 			rqbp->buffer_count = 0;
8931 
8932 			lpfc_post_rq_buffer(
8933 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
8934 				phba->sli4_hba.nvmet_mrq_data[i],
8935 				phba->cfg_nvmet_mrq_post, i);
8936 		}
8937 	}
8938 
8939 	/* Post the rpi header region to the device. */
8940 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
8941 	if (unlikely(rc)) {
8942 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8943 				"0393 Error %d during rpi post operation\n",
8944 				rc);
8945 		rc = -ENODEV;
8946 		goto out_free_iocblist;
8947 	}
8948 
8949 	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag)) {
8950 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
8951 			/*
8952 			 * The FC Port needs to register FCFI (index 0)
8953 			 */
8954 			lpfc_reg_fcfi(phba, mboxq);
8955 			mboxq->vport = phba->pport;
8956 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8957 			if (rc != MBX_SUCCESS)
8958 				goto out_unset_queue;
8959 			rc = 0;
8960 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
8961 						&mboxq->u.mqe.un.reg_fcfi);
8962 		} else {
8963 			/* We are a NVME Target mode with MRQ > 1 */
8964 
8965 			/* First register the FCFI */
8966 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
8967 			mboxq->vport = phba->pport;
8968 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8969 			if (rc != MBX_SUCCESS)
8970 				goto out_unset_queue;
8971 			rc = 0;
8972 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
8973 						&mboxq->u.mqe.un.reg_fcfi_mrq);
8974 
8975 			/* Next register the MRQs */
8976 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
8977 			mboxq->vport = phba->pport;
8978 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8979 			if (rc != MBX_SUCCESS)
8980 				goto out_unset_queue;
8981 			rc = 0;
8982 		}
8983 		/* Check if the port is configured to be disabled */
8984 		lpfc_sli_read_link_ste(phba);
8985 	}
8986 
8987 	/* Don't post more new bufs if repost already recovered
8988 	 * the nvme sgls.
8989 	 */
8990 	if (phba->nvmet_support == 0) {
8991 		if (phba->sli4_hba.io_xri_cnt == 0) {
8992 			len = lpfc_new_io_buf(
8993 					      phba, phba->sli4_hba.io_xri_max);
8994 			if (len == 0) {
8995 				rc = -ENOMEM;
8996 				goto out_unset_queue;
8997 			}
8998 
8999 			if (phba->cfg_xri_rebalancing)
9000 				lpfc_create_multixri_pools(phba);
9001 		}
9002 	} else {
9003 		phba->cfg_xri_rebalancing = 0;
9004 	}
9005 
9006 	/* Allow asynchronous mailbox command to go through */
9007 	spin_lock_irq(&phba->hbalock);
9008 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9009 	spin_unlock_irq(&phba->hbalock);
9010 
9011 	/* Post receive buffers to the device */
9012 	lpfc_sli4_rb_setup(phba);
9013 
9014 	/* Reset HBA FCF states after HBA reset */
9015 	phba->fcf.fcf_flag = 0;
9016 	phba->fcf.current_rec.flag = 0;
9017 
9018 	/* Start the ELS watchdog timer */
9019 	mod_timer(&vport->els_tmofunc,
9020 			jiffies + secs_to_jiffies(phba->fc_ratov * 2));
9021 
9022 	/* Start heart beat timer */
9023 	mod_timer(&phba->hb_tmofunc,
9024 		  jiffies + secs_to_jiffies(LPFC_HB_MBOX_INTERVAL));
9025 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
9026 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
9027 	phba->last_completion_time = jiffies;
9028 
9029 	/* start eq_delay heartbeat */
9030 	if (phba->cfg_auto_imax)
9031 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
9032 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
9033 
9034 	/* start per phba idle_stat_delay heartbeat */
9035 	lpfc_init_idle_stat_hb(phba);
9036 
9037 	/* Start error attention (ERATT) polling timer */
9038 	mod_timer(&phba->eratt_poll,
9039 		  jiffies + secs_to_jiffies(phba->eratt_poll_interval));
9040 
9041 	/*
9042 	 * The port is ready, set the host's link state to LINK_DOWN
9043 	 * in preparation for link interrupts.
9044 	 */
9045 	spin_lock_irq(&phba->hbalock);
9046 	phba->link_state = LPFC_LINK_DOWN;
9047 
9048 	/* Check if physical ports are trunked */
9049 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
9050 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
9051 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
9052 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
9053 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
9054 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
9055 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
9056 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
9057 	spin_unlock_irq(&phba->hbalock);
9058 
9059 	/* Arm the CQs and then EQs on device */
9060 	lpfc_sli4_arm_cqeq_intr(phba);
9061 
9062 	/* Indicate device interrupt mode */
9063 	phba->sli4_hba.intr_enable = 1;
9064 
9065 	/* Setup CMF after HBA is initialized */
9066 	lpfc_cmf_setup(phba);
9067 
9068 	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag) &&
9069 	    test_bit(LINK_DISABLED, &phba->hba_flag)) {
9070 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9071 				"3103 Adapter Link is disabled.\n");
9072 		lpfc_down_link(phba, mboxq);
9073 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9074 		if (rc != MBX_SUCCESS) {
9075 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9076 					"3104 Adapter failed to issue "
9077 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
9078 			goto out_io_buff_free;
9079 		}
9080 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
9081 		/* don't perform init_link on SLI4 FC port loopback test */
9082 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
9083 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
9084 			if (rc)
9085 				goto out_io_buff_free;
9086 		}
9087 	}
9088 	mempool_free(mboxq, phba->mbox_mem_pool);
9089 
9090 	/* Enable RAS FW log support */
9091 	lpfc_sli4_ras_setup(phba);
9092 
9093 	set_bit(HBA_SETUP, &phba->hba_flag);
9094 	return rc;
9095 
9096 out_io_buff_free:
9097 	/* Free allocated IO Buffers */
9098 	lpfc_io_free(phba);
9099 out_unset_queue:
9100 	/* Unset all the queues set up in this routine when error out */
9101 	lpfc_sli4_queue_unset(phba);
9102 out_free_iocblist:
9103 	lpfc_free_iocb_list(phba);
9104 out_destroy_queue:
9105 	lpfc_sli4_queue_destroy(phba);
9106 	lpfc_stop_hba_timers(phba);
9107 out_free_mbox:
9108 	mempool_free(mboxq, phba->mbox_mem_pool);
9109 	return rc;
9110 }
9111 
9112 /**
9113  * lpfc_mbox_timeout - Timeout call back function for mbox timer
9114  * @t: Context to fetch pointer to hba structure from.
9115  *
9116  * This is the callback function for mailbox timer. The mailbox
9117  * timer is armed when a new mailbox command is issued and the timer
9118  * is deleted when the mailbox complete. The function is called by
9119  * the kernel timer code when a mailbox does not complete within
9120  * expected time. This function wakes up the worker thread to
9121  * process the mailbox timeout and returns. All the processing is
9122  * done by the worker thread function lpfc_mbox_timeout_handler.
9123  **/
9124 void
9125 lpfc_mbox_timeout(struct timer_list *t)
9126 {
9127 	struct lpfc_hba  *phba = timer_container_of(phba, t, sli.mbox_tmo);
9128 	unsigned long iflag;
9129 	uint32_t tmo_posted;
9130 
9131 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
9132 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
9133 	if (!tmo_posted)
9134 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
9135 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
9136 
9137 	if (!tmo_posted)
9138 		lpfc_worker_wake_up(phba);
9139 	return;
9140 }
9141 
9142 /**
9143  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
9144  *                                    are pending
9145  * @phba: Pointer to HBA context object.
9146  *
9147  * This function checks if any mailbox completions are present on the mailbox
9148  * completion queue.
9149  **/
9150 static bool
9151 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
9152 {
9153 
9154 	uint32_t idx;
9155 	struct lpfc_queue *mcq;
9156 	struct lpfc_mcqe *mcqe;
9157 	bool pending_completions = false;
9158 	uint8_t	qe_valid;
9159 
9160 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9161 		return false;
9162 
9163 	/* Check for completions on mailbox completion queue */
9164 
9165 	mcq = phba->sli4_hba.mbx_cq;
9166 	idx = mcq->hba_index;
9167 	qe_valid = mcq->qe_valid;
9168 	while (bf_get_le32(lpfc_cqe_valid,
9169 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
9170 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
9171 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
9172 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
9173 			pending_completions = true;
9174 			break;
9175 		}
9176 		idx = (idx + 1) % mcq->entry_count;
9177 		if (mcq->hba_index == idx)
9178 			break;
9179 
9180 		/* if the index wrapped around, toggle the valid bit */
9181 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
9182 			qe_valid = (qe_valid) ? 0 : 1;
9183 	}
9184 	return pending_completions;
9185 
9186 }
9187 
9188 /**
9189  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
9190  *					      that were missed.
9191  * @phba: Pointer to HBA context object.
9192  *
9193  * For sli4, it is possible to miss an interrupt. As such mbox completions
9194  * maybe missed causing erroneous mailbox timeouts to occur. This function
9195  * checks to see if mbox completions are on the mailbox completion queue
9196  * and will process all the completions associated with the eq for the
9197  * mailbox completion queue.
9198  **/
9199 static bool
9200 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
9201 {
9202 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
9203 	uint32_t eqidx;
9204 	struct lpfc_queue *fpeq = NULL;
9205 	struct lpfc_queue *eq;
9206 	bool mbox_pending;
9207 
9208 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9209 		return false;
9210 
9211 	/* Find the EQ associated with the mbox CQ */
9212 	if (sli4_hba->hdwq) {
9213 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
9214 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
9215 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
9216 				fpeq = eq;
9217 				break;
9218 			}
9219 		}
9220 	}
9221 	if (!fpeq)
9222 		return false;
9223 
9224 	/* Turn off interrupts from this EQ */
9225 
9226 	sli4_hba->sli4_eq_clr_intr(fpeq);
9227 
9228 	/* Check to see if a mbox completion is pending */
9229 
9230 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
9231 
9232 	/*
9233 	 * If a mbox completion is pending, process all the events on EQ
9234 	 * associated with the mbox completion queue (this could include
9235 	 * mailbox commands, async events, els commands, receive queue data
9236 	 * and fcp commands)
9237 	 */
9238 
9239 	if (mbox_pending)
9240 		/* process and rearm the EQ */
9241 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
9242 				     LPFC_QUEUE_WORK);
9243 	else
9244 		/* Always clear and re-arm the EQ */
9245 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
9246 
9247 	return mbox_pending;
9248 
9249 }
9250 
9251 /**
9252  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
9253  * @phba: Pointer to HBA context object.
9254  *
9255  * This function is called from worker thread when a mailbox command times out.
9256  * The caller is not required to hold any locks. This function will reset the
9257  * HBA and recover all the pending commands.
9258  **/
9259 void
9260 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
9261 {
9262 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
9263 	MAILBOX_t *mb = NULL;
9264 
9265 	struct lpfc_sli *psli = &phba->sli;
9266 
9267 	/* If the mailbox completed, process the completion */
9268 	lpfc_sli4_process_missed_mbox_completions(phba);
9269 
9270 	if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
9271 		return;
9272 
9273 	if (pmbox != NULL)
9274 		mb = &pmbox->u.mb;
9275 	/* Check the pmbox pointer first.  There is a race condition
9276 	 * between the mbox timeout handler getting executed in the
9277 	 * worklist and the mailbox actually completing. When this
9278 	 * race condition occurs, the mbox_active will be NULL.
9279 	 */
9280 	spin_lock_irq(&phba->hbalock);
9281 	if (pmbox == NULL) {
9282 		lpfc_printf_log(phba, KERN_WARNING,
9283 				LOG_MBOX | LOG_SLI,
9284 				"0353 Active Mailbox cleared - mailbox timeout "
9285 				"exiting\n");
9286 		spin_unlock_irq(&phba->hbalock);
9287 		return;
9288 	}
9289 
9290 	/* Mbox cmd <mbxCommand> timeout */
9291 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9292 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
9293 			mb->mbxCommand,
9294 			phba->pport->port_state,
9295 			phba->sli.sli_flag,
9296 			phba->sli.mbox_active);
9297 	spin_unlock_irq(&phba->hbalock);
9298 
9299 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
9300 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
9301 	 * it to fail all outstanding SCSI IO.
9302 	 */
9303 	set_bit(MBX_TMO_ERR, &phba->bit_flags);
9304 	spin_lock_irq(&phba->pport->work_port_lock);
9305 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9306 	spin_unlock_irq(&phba->pport->work_port_lock);
9307 	spin_lock_irq(&phba->hbalock);
9308 	phba->link_state = LPFC_LINK_UNKNOWN;
9309 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
9310 	spin_unlock_irq(&phba->hbalock);
9311 
9312 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9313 			"0345 Resetting board due to mailbox timeout\n");
9314 
9315 	/* Reset the HBA device */
9316 	lpfc_reset_hba(phba);
9317 }
9318 
9319 /**
9320  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
9321  * @phba: Pointer to HBA context object.
9322  * @pmbox: Pointer to mailbox object.
9323  * @flag: Flag indicating how the mailbox need to be processed.
9324  *
9325  * This function is called by discovery code and HBA management code
9326  * to submit a mailbox command to firmware with SLI-3 interface spec. This
9327  * function gets the hbalock to protect the data structures.
9328  * The mailbox command can be submitted in polling mode, in which case
9329  * this function will wait in a polling loop for the completion of the
9330  * mailbox.
9331  * If the mailbox is submitted in no_wait mode (not polling) the
9332  * function will submit the command and returns immediately without waiting
9333  * for the mailbox completion. The no_wait is supported only when HBA
9334  * is in SLI2/SLI3 mode - interrupts are enabled.
9335  * The SLI interface allows only one mailbox pending at a time. If the
9336  * mailbox is issued in polling mode and there is already a mailbox
9337  * pending, then the function will return an error. If the mailbox is issued
9338  * in NO_WAIT mode and there is a mailbox pending already, the function
9339  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
9340  * The sli layer owns the mailbox object until the completion of mailbox
9341  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
9342  * return codes the caller owns the mailbox command after the return of
9343  * the function.
9344  **/
9345 static int
9346 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
9347 		       uint32_t flag)
9348 {
9349 	MAILBOX_t *mbx;
9350 	struct lpfc_sli *psli = &phba->sli;
9351 	uint32_t status, evtctr;
9352 	uint32_t ha_copy, hc_copy;
9353 	int i;
9354 	unsigned long timeout;
9355 	unsigned long drvr_flag = 0;
9356 	uint32_t word0, ldata;
9357 	void __iomem *to_slim;
9358 	int processing_queue = 0;
9359 
9360 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
9361 	if (!pmbox) {
9362 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9363 		/* processing mbox queue from intr_handler */
9364 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9365 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9366 			return MBX_SUCCESS;
9367 		}
9368 		processing_queue = 1;
9369 		pmbox = lpfc_mbox_get(phba);
9370 		if (!pmbox) {
9371 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9372 			return MBX_SUCCESS;
9373 		}
9374 	}
9375 
9376 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
9377 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
9378 		if(!pmbox->vport) {
9379 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9380 			lpfc_printf_log(phba, KERN_ERR,
9381 					LOG_MBOX | LOG_VPORT,
9382 					"1806 Mbox x%x failed. No vport\n",
9383 					pmbox->u.mb.mbxCommand);
9384 			dump_stack();
9385 			goto out_not_finished;
9386 		}
9387 	}
9388 
9389 	/* If the PCI channel is in offline state, do not post mbox. */
9390 	if (unlikely(pci_channel_offline(phba->pcidev))) {
9391 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9392 		goto out_not_finished;
9393 	}
9394 
9395 	/* If HBA has a deferred error attention, fail the iocb. */
9396 	if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag))) {
9397 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9398 		goto out_not_finished;
9399 	}
9400 
9401 	psli = &phba->sli;
9402 
9403 	mbx = &pmbox->u.mb;
9404 	status = MBX_SUCCESS;
9405 
9406 	if (phba->link_state == LPFC_HBA_ERROR) {
9407 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9408 
9409 		/* Mbox command <mbxCommand> cannot issue */
9410 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9411 				"(%d):0311 Mailbox command x%x cannot "
9412 				"issue Data: x%x x%x\n",
9413 				pmbox->vport ? pmbox->vport->vpi : 0,
9414 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9415 		goto out_not_finished;
9416 	}
9417 
9418 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
9419 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
9420 			!(hc_copy & HC_MBINT_ENA)) {
9421 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9422 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9423 				"(%d):2528 Mailbox command x%x cannot "
9424 				"issue Data: x%x x%x\n",
9425 				pmbox->vport ? pmbox->vport->vpi : 0,
9426 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9427 			goto out_not_finished;
9428 		}
9429 	}
9430 
9431 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9432 		/* Polling for a mbox command when another one is already active
9433 		 * is not allowed in SLI. Also, the driver must have established
9434 		 * SLI2 mode to queue and process multiple mbox commands.
9435 		 */
9436 
9437 		if (flag & MBX_POLL) {
9438 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9439 
9440 			/* Mbox command <mbxCommand> cannot issue */
9441 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9442 					"(%d):2529 Mailbox command x%x "
9443 					"cannot issue Data: x%x x%x\n",
9444 					pmbox->vport ? pmbox->vport->vpi : 0,
9445 					pmbox->u.mb.mbxCommand,
9446 					psli->sli_flag, flag);
9447 			goto out_not_finished;
9448 		}
9449 
9450 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
9451 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9452 			/* Mbox command <mbxCommand> cannot issue */
9453 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9454 					"(%d):2530 Mailbox command x%x "
9455 					"cannot issue Data: x%x x%x\n",
9456 					pmbox->vport ? pmbox->vport->vpi : 0,
9457 					pmbox->u.mb.mbxCommand,
9458 					psli->sli_flag, flag);
9459 			goto out_not_finished;
9460 		}
9461 
9462 		/* Another mailbox command is still being processed, queue this
9463 		 * command to be processed later.
9464 		 */
9465 		lpfc_mbox_put(phba, pmbox);
9466 
9467 		/* Mbox cmd issue - BUSY */
9468 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9469 				"(%d):0308 Mbox cmd issue - BUSY Data: "
9470 				"x%x x%x x%x x%x\n",
9471 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
9472 				mbx->mbxCommand,
9473 				phba->pport ? phba->pport->port_state : 0xff,
9474 				psli->sli_flag, flag);
9475 
9476 		psli->slistat.mbox_busy++;
9477 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9478 
9479 		if (pmbox->vport) {
9480 			lpfc_debugfs_disc_trc(pmbox->vport,
9481 				LPFC_DISC_TRC_MBOX_VPORT,
9482 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
9483 				(uint32_t)mbx->mbxCommand,
9484 				mbx->un.varWords[0], mbx->un.varWords[1]);
9485 		}
9486 		else {
9487 			lpfc_debugfs_disc_trc(phba->pport,
9488 				LPFC_DISC_TRC_MBOX,
9489 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
9490 				(uint32_t)mbx->mbxCommand,
9491 				mbx->un.varWords[0], mbx->un.varWords[1]);
9492 		}
9493 
9494 		return MBX_BUSY;
9495 	}
9496 
9497 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9498 
9499 	/* If we are not polling, we MUST be in SLI2 mode */
9500 	if (flag != MBX_POLL) {
9501 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
9502 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
9503 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9504 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9505 			/* Mbox command <mbxCommand> cannot issue */
9506 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9507 					"(%d):2531 Mailbox command x%x "
9508 					"cannot issue Data: x%x x%x\n",
9509 					pmbox->vport ? pmbox->vport->vpi : 0,
9510 					pmbox->u.mb.mbxCommand,
9511 					psli->sli_flag, flag);
9512 			goto out_not_finished;
9513 		}
9514 		/* timeout active mbox command */
9515 		timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox));
9516 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
9517 	}
9518 
9519 	/* Mailbox cmd <cmd> issue */
9520 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9521 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
9522 			"x%x\n",
9523 			pmbox->vport ? pmbox->vport->vpi : 0,
9524 			mbx->mbxCommand,
9525 			phba->pport ? phba->pport->port_state : 0xff,
9526 			psli->sli_flag, flag);
9527 
9528 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
9529 		if (pmbox->vport) {
9530 			lpfc_debugfs_disc_trc(pmbox->vport,
9531 				LPFC_DISC_TRC_MBOX_VPORT,
9532 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9533 				(uint32_t)mbx->mbxCommand,
9534 				mbx->un.varWords[0], mbx->un.varWords[1]);
9535 		}
9536 		else {
9537 			lpfc_debugfs_disc_trc(phba->pport,
9538 				LPFC_DISC_TRC_MBOX,
9539 				"MBOX Send:       cmd:x%x mb:x%x x%x",
9540 				(uint32_t)mbx->mbxCommand,
9541 				mbx->un.varWords[0], mbx->un.varWords[1]);
9542 		}
9543 	}
9544 
9545 	psli->slistat.mbox_cmd++;
9546 	evtctr = psli->slistat.mbox_event;
9547 
9548 	/* next set own bit for the adapter and copy over command word */
9549 	mbx->mbxOwner = OWN_CHIP;
9550 
9551 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9552 		/* Populate mbox extension offset word. */
9553 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
9554 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9555 				= (uint8_t *)phba->mbox_ext
9556 				  - (uint8_t *)phba->mbox;
9557 		}
9558 
9559 		/* Copy the mailbox extension data */
9560 		if (pmbox->in_ext_byte_len && pmbox->ext_buf) {
9561 			lpfc_sli_pcimem_bcopy(pmbox->ext_buf,
9562 					      (uint8_t *)phba->mbox_ext,
9563 					      pmbox->in_ext_byte_len);
9564 		}
9565 		/* Copy command data to host SLIM area */
9566 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
9567 	} else {
9568 		/* Populate mbox extension offset word. */
9569 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
9570 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9571 				= MAILBOX_HBA_EXT_OFFSET;
9572 
9573 		/* Copy the mailbox extension data */
9574 		if (pmbox->in_ext_byte_len && pmbox->ext_buf)
9575 			lpfc_memcpy_to_slim(phba->MBslimaddr +
9576 				MAILBOX_HBA_EXT_OFFSET,
9577 				pmbox->ext_buf, pmbox->in_ext_byte_len);
9578 
9579 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9580 			/* copy command data into host mbox for cmpl */
9581 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
9582 					      MAILBOX_CMD_SIZE);
9583 
9584 		/* First copy mbox command data to HBA SLIM, skip past first
9585 		   word */
9586 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
9587 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
9588 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
9589 
9590 		/* Next copy over first word, with mbxOwner set */
9591 		ldata = *((uint32_t *)mbx);
9592 		to_slim = phba->MBslimaddr;
9593 		writel(ldata, to_slim);
9594 		readl(to_slim); /* flush */
9595 
9596 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9597 			/* switch over to host mailbox */
9598 			psli->sli_flag |= LPFC_SLI_ACTIVE;
9599 	}
9600 
9601 	wmb();
9602 
9603 	switch (flag) {
9604 	case MBX_NOWAIT:
9605 		/* Set up reference to mailbox command */
9606 		psli->mbox_active = pmbox;
9607 		/* Interrupt board to do it */
9608 		writel(CA_MBATT, phba->CAregaddr);
9609 		readl(phba->CAregaddr); /* flush */
9610 		/* Don't wait for it to finish, just return */
9611 		break;
9612 
9613 	case MBX_POLL:
9614 		/* Set up null reference to mailbox command */
9615 		psli->mbox_active = NULL;
9616 		/* Interrupt board to do it */
9617 		writel(CA_MBATT, phba->CAregaddr);
9618 		readl(phba->CAregaddr); /* flush */
9619 
9620 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9621 			/* First read mbox status word */
9622 			word0 = *((uint32_t *)phba->mbox);
9623 			word0 = le32_to_cpu(word0);
9624 		} else {
9625 			/* First read mbox status word */
9626 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
9627 				spin_unlock_irqrestore(&phba->hbalock,
9628 						       drvr_flag);
9629 				goto out_not_finished;
9630 			}
9631 		}
9632 
9633 		/* Read the HBA Host Attention Register */
9634 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9635 			spin_unlock_irqrestore(&phba->hbalock,
9636 						       drvr_flag);
9637 			goto out_not_finished;
9638 		}
9639 		timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox)) + jiffies;
9640 		i = 0;
9641 		/* Wait for command to complete */
9642 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
9643 		       (!(ha_copy & HA_MBATT) &&
9644 			(phba->link_state > LPFC_WARM_START))) {
9645 			if (time_after(jiffies, timeout)) {
9646 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9647 				spin_unlock_irqrestore(&phba->hbalock,
9648 						       drvr_flag);
9649 				goto out_not_finished;
9650 			}
9651 
9652 			/* Check if we took a mbox interrupt while we were
9653 			   polling */
9654 			if (((word0 & OWN_CHIP) != OWN_CHIP)
9655 			    && (evtctr != psli->slistat.mbox_event))
9656 				break;
9657 
9658 			if (i++ > 10) {
9659 				spin_unlock_irqrestore(&phba->hbalock,
9660 						       drvr_flag);
9661 				msleep(1);
9662 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
9663 			}
9664 
9665 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9666 				/* First copy command data */
9667 				word0 = *((uint32_t *)phba->mbox);
9668 				word0 = le32_to_cpu(word0);
9669 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
9670 					MAILBOX_t *slimmb;
9671 					uint32_t slimword0;
9672 					/* Check real SLIM for any errors */
9673 					slimword0 = readl(phba->MBslimaddr);
9674 					slimmb = (MAILBOX_t *) & slimword0;
9675 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
9676 					    && slimmb->mbxStatus) {
9677 						psli->sli_flag &=
9678 						    ~LPFC_SLI_ACTIVE;
9679 						word0 = slimword0;
9680 					}
9681 				}
9682 			} else {
9683 				/* First copy command data */
9684 				word0 = readl(phba->MBslimaddr);
9685 			}
9686 			/* Read the HBA Host Attention Register */
9687 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9688 				spin_unlock_irqrestore(&phba->hbalock,
9689 						       drvr_flag);
9690 				goto out_not_finished;
9691 			}
9692 		}
9693 
9694 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9695 			/* copy results back to user */
9696 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
9697 						MAILBOX_CMD_SIZE);
9698 			/* Copy the mailbox extension data */
9699 			if (pmbox->out_ext_byte_len && pmbox->ext_buf) {
9700 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
9701 						      pmbox->ext_buf,
9702 						      pmbox->out_ext_byte_len);
9703 			}
9704 		} else {
9705 			/* First copy command data */
9706 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
9707 						MAILBOX_CMD_SIZE);
9708 			/* Copy the mailbox extension data */
9709 			if (pmbox->out_ext_byte_len && pmbox->ext_buf) {
9710 				lpfc_memcpy_from_slim(
9711 					pmbox->ext_buf,
9712 					phba->MBslimaddr +
9713 					MAILBOX_HBA_EXT_OFFSET,
9714 					pmbox->out_ext_byte_len);
9715 			}
9716 		}
9717 
9718 		writel(HA_MBATT, phba->HAregaddr);
9719 		readl(phba->HAregaddr); /* flush */
9720 
9721 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9722 		status = mbx->mbxStatus;
9723 	}
9724 
9725 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9726 	return status;
9727 
9728 out_not_finished:
9729 	if (processing_queue) {
9730 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
9731 		lpfc_mbox_cmpl_put(phba, pmbox);
9732 	}
9733 	return MBX_NOT_FINISHED;
9734 }
9735 
9736 /**
9737  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
9738  * @phba: Pointer to HBA context object.
9739  *
9740  * The function blocks the posting of SLI4 asynchronous mailbox commands from
9741  * the driver internal pending mailbox queue. It will then try to wait out the
9742  * possible outstanding mailbox command before return.
9743  *
9744  * Returns:
9745  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
9746  * 	the outstanding mailbox command timed out.
9747  **/
9748 static int
9749 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
9750 {
9751 	struct lpfc_sli *psli = &phba->sli;
9752 	LPFC_MBOXQ_t *mboxq;
9753 	int rc = 0;
9754 	unsigned long timeout = 0;
9755 	u32 sli_flag;
9756 	u8 cmd, subsys, opcode;
9757 
9758 	/* Mark the asynchronous mailbox command posting as blocked */
9759 	spin_lock_irq(&phba->hbalock);
9760 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
9761 	/* Determine how long we might wait for the active mailbox
9762 	 * command to be gracefully completed by firmware.
9763 	 */
9764 	if (phba->sli.mbox_active)
9765 		timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba,
9766 						phba->sli.mbox_active)) + jiffies;
9767 	spin_unlock_irq(&phba->hbalock);
9768 
9769 	/* Make sure the mailbox is really active */
9770 	if (timeout)
9771 		lpfc_sli4_process_missed_mbox_completions(phba);
9772 
9773 	/* Wait for the outstanding mailbox command to complete */
9774 	while (phba->sli.mbox_active) {
9775 		/* Check active mailbox complete status every 2ms */
9776 		msleep(2);
9777 		if (time_after(jiffies, timeout)) {
9778 			/* Timeout, mark the outstanding cmd not complete */
9779 
9780 			/* Sanity check sli.mbox_active has not completed or
9781 			 * cancelled from another context during last 2ms sleep,
9782 			 * so take hbalock to be sure before logging.
9783 			 */
9784 			spin_lock_irq(&phba->hbalock);
9785 			if (phba->sli.mbox_active) {
9786 				mboxq = phba->sli.mbox_active;
9787 				cmd = mboxq->u.mb.mbxCommand;
9788 				subsys = lpfc_sli_config_mbox_subsys_get(phba,
9789 									 mboxq);
9790 				opcode = lpfc_sli_config_mbox_opcode_get(phba,
9791 									 mboxq);
9792 				sli_flag = psli->sli_flag;
9793 				spin_unlock_irq(&phba->hbalock);
9794 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9795 						"2352 Mailbox command x%x "
9796 						"(x%x/x%x) sli_flag x%x could "
9797 						"not complete\n",
9798 						cmd, subsys, opcode,
9799 						sli_flag);
9800 			} else {
9801 				spin_unlock_irq(&phba->hbalock);
9802 			}
9803 
9804 			rc = 1;
9805 			break;
9806 		}
9807 	}
9808 
9809 	/* Can not cleanly block async mailbox command, fails it */
9810 	if (rc) {
9811 		spin_lock_irq(&phba->hbalock);
9812 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9813 		spin_unlock_irq(&phba->hbalock);
9814 	}
9815 	return rc;
9816 }
9817 
9818 /**
9819  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
9820  * @phba: Pointer to HBA context object.
9821  *
9822  * The function unblocks and resume posting of SLI4 asynchronous mailbox
9823  * commands from the driver internal pending mailbox queue. It makes sure
9824  * that there is no outstanding mailbox command before resuming posting
9825  * asynchronous mailbox commands. If, for any reason, there is outstanding
9826  * mailbox command, it will try to wait it out before resuming asynchronous
9827  * mailbox command posting.
9828  **/
9829 static void
9830 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
9831 {
9832 	struct lpfc_sli *psli = &phba->sli;
9833 
9834 	spin_lock_irq(&phba->hbalock);
9835 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9836 		/* Asynchronous mailbox posting is not blocked, do nothing */
9837 		spin_unlock_irq(&phba->hbalock);
9838 		return;
9839 	}
9840 
9841 	/* Outstanding synchronous mailbox command is guaranteed to be done,
9842 	 * successful or timeout, after timing-out the outstanding mailbox
9843 	 * command shall always be removed, so just unblock posting async
9844 	 * mailbox command and resume
9845 	 */
9846 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9847 	spin_unlock_irq(&phba->hbalock);
9848 
9849 	/* wake up worker thread to post asynchronous mailbox command */
9850 	lpfc_worker_wake_up(phba);
9851 }
9852 
9853 /**
9854  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
9855  * @phba: Pointer to HBA context object.
9856  * @mboxq: Pointer to mailbox object.
9857  *
9858  * The function waits for the bootstrap mailbox register ready bit from
9859  * port for twice the regular mailbox command timeout value.
9860  *
9861  *      0 - no timeout on waiting for bootstrap mailbox register ready.
9862  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out or port
9863  *                     is in an unrecoverable state.
9864  **/
9865 static int
9866 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9867 {
9868 	uint32_t db_ready;
9869 	unsigned long timeout;
9870 	struct lpfc_register bmbx_reg;
9871 	struct lpfc_register portstat_reg = {-1};
9872 
9873 	/* Sanity check - there is no point to wait if the port is in an
9874 	 * unrecoverable state.
9875 	 */
9876 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
9877 	    LPFC_SLI_INTF_IF_TYPE_2) {
9878 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9879 			       &portstat_reg.word0) ||
9880 		    lpfc_sli4_unrecoverable_port(&portstat_reg)) {
9881 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9882 					"3858 Skipping bmbx ready because "
9883 					"Port Status x%x\n",
9884 					portstat_reg.word0);
9885 			return MBXERR_ERROR;
9886 		}
9887 	}
9888 
9889 	timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)) + jiffies;
9890 
9891 	do {
9892 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
9893 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
9894 		if (!db_ready)
9895 			mdelay(2);
9896 
9897 		if (time_after(jiffies, timeout))
9898 			return MBXERR_ERROR;
9899 	} while (!db_ready);
9900 
9901 	return 0;
9902 }
9903 
9904 /**
9905  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
9906  * @phba: Pointer to HBA context object.
9907  * @mboxq: Pointer to mailbox object.
9908  *
9909  * The function posts a mailbox to the port.  The mailbox is expected
9910  * to be comletely filled in and ready for the port to operate on it.
9911  * This routine executes a synchronous completion operation on the
9912  * mailbox by polling for its completion.
9913  *
9914  * The caller must not be holding any locks when calling this routine.
9915  *
9916  * Returns:
9917  *	MBX_SUCCESS - mailbox posted successfully
9918  *	Any of the MBX error values.
9919  **/
9920 static int
9921 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9922 {
9923 	int rc = MBX_SUCCESS;
9924 	unsigned long iflag;
9925 	uint32_t mcqe_status;
9926 	uint32_t mbx_cmnd;
9927 	struct lpfc_sli *psli = &phba->sli;
9928 	struct lpfc_mqe *mb = &mboxq->u.mqe;
9929 	struct lpfc_bmbx_create *mbox_rgn;
9930 	struct dma_address *dma_address;
9931 
9932 	/*
9933 	 * Only one mailbox can be active to the bootstrap mailbox region
9934 	 * at a time and there is no queueing provided.
9935 	 */
9936 	spin_lock_irqsave(&phba->hbalock, iflag);
9937 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9938 		spin_unlock_irqrestore(&phba->hbalock, iflag);
9939 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9940 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
9941 				"cannot issue Data: x%x x%x\n",
9942 				mboxq->vport ? mboxq->vport->vpi : 0,
9943 				mboxq->u.mb.mbxCommand,
9944 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9945 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9946 				psli->sli_flag, MBX_POLL);
9947 		return MBXERR_ERROR;
9948 	}
9949 	/* The server grabs the token and owns it until release */
9950 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9951 	phba->sli.mbox_active = mboxq;
9952 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9953 
9954 	/* wait for bootstrap mbox register for readyness */
9955 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9956 	if (rc)
9957 		goto exit;
9958 	/*
9959 	 * Initialize the bootstrap memory region to avoid stale data areas
9960 	 * in the mailbox post.  Then copy the caller's mailbox contents to
9961 	 * the bmbx mailbox region.
9962 	 */
9963 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
9964 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
9965 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
9966 			       sizeof(struct lpfc_mqe));
9967 
9968 	/* Post the high mailbox dma address to the port and wait for ready. */
9969 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9970 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
9971 
9972 	/* wait for bootstrap mbox register for hi-address write done */
9973 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9974 	if (rc)
9975 		goto exit;
9976 
9977 	/* Post the low mailbox dma address to the port. */
9978 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
9979 
9980 	/* wait for bootstrap mbox register for low address write done */
9981 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9982 	if (rc)
9983 		goto exit;
9984 
9985 	/*
9986 	 * Read the CQ to ensure the mailbox has completed.
9987 	 * If so, update the mailbox status so that the upper layers
9988 	 * can complete the request normally.
9989 	 */
9990 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
9991 			       sizeof(struct lpfc_mqe));
9992 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
9993 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
9994 			       sizeof(struct lpfc_mcqe));
9995 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
9996 	/*
9997 	 * When the CQE status indicates a failure and the mailbox status
9998 	 * indicates success then copy the CQE status into the mailbox status
9999 	 * (and prefix it with x4000).
10000 	 */
10001 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
10002 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
10003 			bf_set(lpfc_mqe_status, mb,
10004 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
10005 		rc = MBXERR_ERROR;
10006 	} else
10007 		lpfc_sli4_swap_str(phba, mboxq);
10008 
10009 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10010 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
10011 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
10012 			" x%x x%x CQ: x%x x%x x%x x%x\n",
10013 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10014 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10015 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10016 			bf_get(lpfc_mqe_status, mb),
10017 			mb->un.mb_words[0], mb->un.mb_words[1],
10018 			mb->un.mb_words[2], mb->un.mb_words[3],
10019 			mb->un.mb_words[4], mb->un.mb_words[5],
10020 			mb->un.mb_words[6], mb->un.mb_words[7],
10021 			mb->un.mb_words[8], mb->un.mb_words[9],
10022 			mb->un.mb_words[10], mb->un.mb_words[11],
10023 			mb->un.mb_words[12], mboxq->mcqe.word0,
10024 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
10025 			mboxq->mcqe.trailer);
10026 exit:
10027 	/* We are holding the token, no needed for lock when release */
10028 	spin_lock_irqsave(&phba->hbalock, iflag);
10029 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10030 	phba->sli.mbox_active = NULL;
10031 	spin_unlock_irqrestore(&phba->hbalock, iflag);
10032 	return rc;
10033 }
10034 
10035 /**
10036  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
10037  * @phba: Pointer to HBA context object.
10038  * @mboxq: Pointer to mailbox object.
10039  * @flag: Flag indicating how the mailbox need to be processed.
10040  *
10041  * This function is called by discovery code and HBA management code to submit
10042  * a mailbox command to firmware with SLI-4 interface spec.
10043  *
10044  * Return codes the caller owns the mailbox command after the return of the
10045  * function.
10046  **/
10047 static int
10048 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
10049 		       uint32_t flag)
10050 {
10051 	struct lpfc_sli *psli = &phba->sli;
10052 	unsigned long iflags;
10053 	int rc;
10054 
10055 	/* dump from issue mailbox command if setup */
10056 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
10057 
10058 	rc = lpfc_mbox_dev_check(phba);
10059 	if (unlikely(rc)) {
10060 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10061 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
10062 				"cannot issue Data: x%x x%x\n",
10063 				mboxq->vport ? mboxq->vport->vpi : 0,
10064 				mboxq->u.mb.mbxCommand,
10065 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10066 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10067 				psli->sli_flag, flag);
10068 		goto out_not_finished;
10069 	}
10070 
10071 	/* Detect polling mode and jump to a handler */
10072 	if (!phba->sli4_hba.intr_enable) {
10073 		if (flag == MBX_POLL)
10074 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10075 		else
10076 			rc = -EIO;
10077 		if (rc != MBX_SUCCESS)
10078 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10079 					"(%d):2541 Mailbox command x%x "
10080 					"(x%x/x%x) failure: "
10081 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
10082 					"Data: x%x x%x\n",
10083 					mboxq->vport ? mboxq->vport->vpi : 0,
10084 					mboxq->u.mb.mbxCommand,
10085 					lpfc_sli_config_mbox_subsys_get(phba,
10086 									mboxq),
10087 					lpfc_sli_config_mbox_opcode_get(phba,
10088 									mboxq),
10089 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10090 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10091 					bf_get(lpfc_mcqe_ext_status,
10092 					       &mboxq->mcqe),
10093 					psli->sli_flag, flag);
10094 		return rc;
10095 	} else if (flag == MBX_POLL) {
10096 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10097 				"(%d):2542 Try to issue mailbox command "
10098 				"x%x (x%x/x%x) synchronously ahead of async "
10099 				"mailbox command queue: x%x x%x\n",
10100 				mboxq->vport ? mboxq->vport->vpi : 0,
10101 				mboxq->u.mb.mbxCommand,
10102 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10103 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10104 				psli->sli_flag, flag);
10105 		/* Try to block the asynchronous mailbox posting */
10106 		rc = lpfc_sli4_async_mbox_block(phba);
10107 		if (!rc) {
10108 			/* Successfully blocked, now issue sync mbox cmd */
10109 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10110 			if (rc != MBX_SUCCESS)
10111 				lpfc_printf_log(phba, KERN_WARNING,
10112 					LOG_MBOX | LOG_SLI,
10113 					"(%d):2597 Sync Mailbox command "
10114 					"x%x (x%x/x%x) failure: "
10115 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
10116 					"Data: x%x x%x\n",
10117 					mboxq->vport ? mboxq->vport->vpi : 0,
10118 					mboxq->u.mb.mbxCommand,
10119 					lpfc_sli_config_mbox_subsys_get(phba,
10120 									mboxq),
10121 					lpfc_sli_config_mbox_opcode_get(phba,
10122 									mboxq),
10123 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10124 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10125 					bf_get(lpfc_mcqe_ext_status,
10126 					       &mboxq->mcqe),
10127 					psli->sli_flag, flag);
10128 			/* Unblock the async mailbox posting afterward */
10129 			lpfc_sli4_async_mbox_unblock(phba);
10130 		}
10131 		return rc;
10132 	}
10133 
10134 	/* Now, interrupt mode asynchronous mailbox command */
10135 	rc = lpfc_mbox_cmd_check(phba, mboxq);
10136 	if (rc) {
10137 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10138 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
10139 				"cannot issue Data: x%x x%x\n",
10140 				mboxq->vport ? mboxq->vport->vpi : 0,
10141 				mboxq->u.mb.mbxCommand,
10142 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10143 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10144 				psli->sli_flag, flag);
10145 		goto out_not_finished;
10146 	}
10147 
10148 	/* Put the mailbox command to the driver internal FIFO */
10149 	psli->slistat.mbox_busy++;
10150 	spin_lock_irqsave(&phba->hbalock, iflags);
10151 	lpfc_mbox_put(phba, mboxq);
10152 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10153 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10154 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
10155 			"x%x (x%x/x%x) x%x x%x x%x x%x\n",
10156 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
10157 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
10158 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10159 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10160 			mboxq->u.mb.un.varUnregLogin.rpi,
10161 			phba->pport->port_state,
10162 			psli->sli_flag, MBX_NOWAIT);
10163 	/* Wake up worker thread to transport mailbox command from head */
10164 	lpfc_worker_wake_up(phba);
10165 
10166 	return MBX_BUSY;
10167 
10168 out_not_finished:
10169 	return MBX_NOT_FINISHED;
10170 }
10171 
10172 /**
10173  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
10174  * @phba: Pointer to HBA context object.
10175  *
10176  * This function is called by worker thread to send a mailbox command to
10177  * SLI4 HBA firmware.
10178  *
10179  **/
10180 int
10181 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
10182 {
10183 	struct lpfc_sli *psli = &phba->sli;
10184 	LPFC_MBOXQ_t *mboxq;
10185 	int rc = MBX_SUCCESS;
10186 	unsigned long iflags;
10187 	struct lpfc_mqe *mqe;
10188 	uint32_t mbx_cmnd;
10189 
10190 	/* Check interrupt mode before post async mailbox command */
10191 	if (unlikely(!phba->sli4_hba.intr_enable))
10192 		return MBX_NOT_FINISHED;
10193 
10194 	/* Check for mailbox command service token */
10195 	spin_lock_irqsave(&phba->hbalock, iflags);
10196 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
10197 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10198 		return MBX_NOT_FINISHED;
10199 	}
10200 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
10201 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10202 		return MBX_NOT_FINISHED;
10203 	}
10204 	if (unlikely(phba->sli.mbox_active)) {
10205 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10206 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10207 				"0384 There is pending active mailbox cmd\n");
10208 		return MBX_NOT_FINISHED;
10209 	}
10210 	/* Take the mailbox command service token */
10211 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
10212 
10213 	/* Get the next mailbox command from head of queue */
10214 	mboxq = lpfc_mbox_get(phba);
10215 
10216 	/* If no more mailbox command waiting for post, we're done */
10217 	if (!mboxq) {
10218 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10219 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10220 		return MBX_SUCCESS;
10221 	}
10222 	phba->sli.mbox_active = mboxq;
10223 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10224 
10225 	/* Check device readiness for posting mailbox command */
10226 	rc = lpfc_mbox_dev_check(phba);
10227 	if (unlikely(rc))
10228 		/* Driver clean routine will clean up pending mailbox */
10229 		goto out_not_finished;
10230 
10231 	/* Prepare the mbox command to be posted */
10232 	mqe = &mboxq->u.mqe;
10233 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
10234 
10235 	/* Start timer for the mbox_tmo and log some mailbox post messages */
10236 	mod_timer(&psli->mbox_tmo, (jiffies +
10237 		  secs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq))));
10238 
10239 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10240 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
10241 			"x%x x%x\n",
10242 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10243 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10244 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10245 			phba->pport->port_state, psli->sli_flag);
10246 
10247 	if (mbx_cmnd != MBX_HEARTBEAT) {
10248 		if (mboxq->vport) {
10249 			lpfc_debugfs_disc_trc(mboxq->vport,
10250 				LPFC_DISC_TRC_MBOX_VPORT,
10251 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
10252 				mbx_cmnd, mqe->un.mb_words[0],
10253 				mqe->un.mb_words[1]);
10254 		} else {
10255 			lpfc_debugfs_disc_trc(phba->pport,
10256 				LPFC_DISC_TRC_MBOX,
10257 				"MBOX Send: cmd:x%x mb:x%x x%x",
10258 				mbx_cmnd, mqe->un.mb_words[0],
10259 				mqe->un.mb_words[1]);
10260 		}
10261 	}
10262 	psli->slistat.mbox_cmd++;
10263 
10264 	/* Post the mailbox command to the port */
10265 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
10266 	if (rc != MBX_SUCCESS) {
10267 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10268 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
10269 				"cannot issue Data: x%x x%x\n",
10270 				mboxq->vport ? mboxq->vport->vpi : 0,
10271 				mboxq->u.mb.mbxCommand,
10272 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10273 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10274 				psli->sli_flag, MBX_NOWAIT);
10275 		goto out_not_finished;
10276 	}
10277 
10278 	return rc;
10279 
10280 out_not_finished:
10281 	spin_lock_irqsave(&phba->hbalock, iflags);
10282 	if (phba->sli.mbox_active) {
10283 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
10284 		__lpfc_mbox_cmpl_put(phba, mboxq);
10285 		/* Release the token */
10286 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10287 		phba->sli.mbox_active = NULL;
10288 	}
10289 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10290 
10291 	return MBX_NOT_FINISHED;
10292 }
10293 
10294 /**
10295  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
10296  * @phba: Pointer to HBA context object.
10297  * @pmbox: Pointer to mailbox object.
10298  * @flag: Flag indicating how the mailbox need to be processed.
10299  *
10300  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
10301  * the API jump table function pointer from the lpfc_hba struct.
10302  *
10303  * Return codes the caller owns the mailbox command after the return of the
10304  * function.
10305  **/
10306 int
10307 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
10308 {
10309 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
10310 }
10311 
10312 /**
10313  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
10314  * @phba: The hba struct for which this call is being executed.
10315  * @dev_grp: The HBA PCI-Device group number.
10316  *
10317  * This routine sets up the mbox interface API function jump table in @phba
10318  * struct.
10319  * Returns: 0 - success, -ENODEV - failure.
10320  **/
10321 int
10322 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10323 {
10324 
10325 	switch (dev_grp) {
10326 	case LPFC_PCI_DEV_LP:
10327 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
10328 		phba->lpfc_sli_handle_slow_ring_event =
10329 				lpfc_sli_handle_slow_ring_event_s3;
10330 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
10331 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
10332 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
10333 		break;
10334 	case LPFC_PCI_DEV_OC:
10335 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
10336 		phba->lpfc_sli_handle_slow_ring_event =
10337 				lpfc_sli_handle_slow_ring_event_s4;
10338 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
10339 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
10340 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
10341 		break;
10342 	default:
10343 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10344 				"1420 Invalid HBA PCI-device group: 0x%x\n",
10345 				dev_grp);
10346 		return -ENODEV;
10347 	}
10348 	return 0;
10349 }
10350 
10351 /**
10352  * __lpfc_sli_ringtx_put - Add an iocb to the txq
10353  * @phba: Pointer to HBA context object.
10354  * @pring: Pointer to driver SLI ring object.
10355  * @piocb: Pointer to address of newly added command iocb.
10356  *
10357  * This function is called with hbalock held for SLI3 ports or
10358  * the ring lock held for SLI4 ports to add a command
10359  * iocb to the txq when SLI layer cannot submit the command iocb
10360  * to the ring.
10361  **/
10362 void
10363 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10364 		    struct lpfc_iocbq *piocb)
10365 {
10366 	if (phba->sli_rev == LPFC_SLI_REV4)
10367 		lockdep_assert_held(&pring->ring_lock);
10368 	else
10369 		lockdep_assert_held(&phba->hbalock);
10370 	/* Insert the caller's iocb in the txq tail for later processing. */
10371 	list_add_tail(&piocb->list, &pring->txq);
10372 }
10373 
10374 /**
10375  * lpfc_sli_next_iocb - Get the next iocb in the txq
10376  * @phba: Pointer to HBA context object.
10377  * @pring: Pointer to driver SLI ring object.
10378  * @piocb: Pointer to address of newly added command iocb.
10379  *
10380  * This function is called with hbalock held before a new
10381  * iocb is submitted to the firmware. This function checks
10382  * txq to flush the iocbs in txq to Firmware before
10383  * submitting new iocbs to the Firmware.
10384  * If there are iocbs in the txq which need to be submitted
10385  * to firmware, lpfc_sli_next_iocb returns the first element
10386  * of the txq after dequeuing it from txq.
10387  * If there is no iocb in the txq then the function will return
10388  * *piocb and *piocb is set to NULL. Caller needs to check
10389  * *piocb to find if there are more commands in the txq.
10390  **/
10391 static struct lpfc_iocbq *
10392 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10393 		   struct lpfc_iocbq **piocb)
10394 {
10395 	struct lpfc_iocbq * nextiocb;
10396 
10397 	lockdep_assert_held(&phba->hbalock);
10398 
10399 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
10400 	if (!nextiocb) {
10401 		nextiocb = *piocb;
10402 		*piocb = NULL;
10403 	}
10404 
10405 	return nextiocb;
10406 }
10407 
10408 /**
10409  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
10410  * @phba: Pointer to HBA context object.
10411  * @ring_number: SLI ring number to issue iocb on.
10412  * @piocb: Pointer to command iocb.
10413  * @flag: Flag indicating if this command can be put into txq.
10414  *
10415  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
10416  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
10417  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
10418  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
10419  * this function allows only iocbs for posting buffers. This function finds
10420  * next available slot in the command ring and posts the command to the
10421  * available slot and writes the port attention register to request HBA start
10422  * processing new iocb. If there is no slot available in the ring and
10423  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
10424  * the function returns IOCB_BUSY.
10425  *
10426  * This function is called with hbalock held. The function will return success
10427  * after it successfully submit the iocb to firmware or after adding to the
10428  * txq.
10429  **/
10430 static int
10431 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
10432 		    struct lpfc_iocbq *piocb, uint32_t flag)
10433 {
10434 	struct lpfc_iocbq *nextiocb;
10435 	IOCB_t *iocb;
10436 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
10437 
10438 	lockdep_assert_held(&phba->hbalock);
10439 
10440 	if (piocb->cmd_cmpl && (!piocb->vport) &&
10441 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
10442 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
10443 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10444 				"1807 IOCB x%x failed. No vport\n",
10445 				piocb->iocb.ulpCommand);
10446 		dump_stack();
10447 		return IOCB_ERROR;
10448 	}
10449 
10450 
10451 	/* If the PCI channel is in offline state, do not post iocbs. */
10452 	if (unlikely(pci_channel_offline(phba->pcidev)))
10453 		return IOCB_ERROR;
10454 
10455 	/* If HBA has a deferred error attention, fail the iocb. */
10456 	if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag)))
10457 		return IOCB_ERROR;
10458 
10459 	/*
10460 	 * We should never get an IOCB if we are in a < LINK_DOWN state
10461 	 */
10462 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
10463 		return IOCB_ERROR;
10464 
10465 	/*
10466 	 * Check to see if we are blocking IOCB processing because of a
10467 	 * outstanding event.
10468 	 */
10469 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
10470 		goto iocb_busy;
10471 
10472 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
10473 		/*
10474 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
10475 		 * can be issued if the link is not up.
10476 		 */
10477 		switch (piocb->iocb.ulpCommand) {
10478 		case CMD_QUE_RING_BUF_CN:
10479 		case CMD_QUE_RING_BUF64_CN:
10480 			/*
10481 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
10482 			 * completion, cmd_cmpl MUST be 0.
10483 			 */
10484 			if (piocb->cmd_cmpl)
10485 				piocb->cmd_cmpl = NULL;
10486 			fallthrough;
10487 		case CMD_CREATE_XRI_CR:
10488 		case CMD_CLOSE_XRI_CN:
10489 		case CMD_CLOSE_XRI_CX:
10490 			break;
10491 		default:
10492 			goto iocb_busy;
10493 		}
10494 
10495 	/*
10496 	 * For FCP commands, we must be in a state where we can process link
10497 	 * attention events.
10498 	 */
10499 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
10500 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
10501 		goto iocb_busy;
10502 	}
10503 
10504 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
10505 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
10506 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
10507 
10508 	if (iocb)
10509 		lpfc_sli_update_ring(phba, pring);
10510 	else
10511 		lpfc_sli_update_full_ring(phba, pring);
10512 
10513 	if (!piocb)
10514 		return IOCB_SUCCESS;
10515 
10516 	goto out_busy;
10517 
10518  iocb_busy:
10519 	pring->stats.iocb_cmd_delay++;
10520 
10521  out_busy:
10522 
10523 	if (!(flag & SLI_IOCB_RET_IOCB)) {
10524 		__lpfc_sli_ringtx_put(phba, pring, piocb);
10525 		return IOCB_SUCCESS;
10526 	}
10527 
10528 	return IOCB_BUSY;
10529 }
10530 
10531 /**
10532  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10533  * @phba: Pointer to HBA context object.
10534  * @ring_number: SLI ring number to issue wqe on.
10535  * @piocb: Pointer to command iocb.
10536  * @flag: Flag indicating if this command can be put into txq.
10537  *
10538  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10539  * send  an iocb command to an HBA with SLI-3 interface spec.
10540  *
10541  * This function takes the hbalock before invoking the lockless version.
10542  * The function will return success after it successfully submit the wqe to
10543  * firmware or after adding to the txq.
10544  **/
10545 static int
10546 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10547 			   struct lpfc_iocbq *piocb, uint32_t flag)
10548 {
10549 	unsigned long iflags;
10550 	int rc;
10551 
10552 	spin_lock_irqsave(&phba->hbalock, iflags);
10553 	rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10554 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10555 
10556 	return rc;
10557 }
10558 
10559 /**
10560  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10561  * @phba: Pointer to HBA context object.
10562  * @ring_number: SLI ring number to issue wqe on.
10563  * @piocb: Pointer to command iocb.
10564  * @flag: Flag indicating if this command can be put into txq.
10565  *
10566  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10567  * an wqe command to an HBA with SLI-4 interface spec.
10568  *
10569  * This function is a lockless version. The function will return success
10570  * after it successfully submit the wqe to firmware or after adding to the
10571  * txq.
10572  **/
10573 static int
10574 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10575 			   struct lpfc_iocbq *piocb, uint32_t flag)
10576 {
10577 	struct lpfc_io_buf *lpfc_cmd = piocb->io_buf;
10578 
10579 	lpfc_prep_embed_io(phba, lpfc_cmd);
10580 	return lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
10581 }
10582 
10583 void
10584 lpfc_prep_embed_io(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
10585 {
10586 	struct lpfc_iocbq *piocb = &lpfc_cmd->cur_iocbq;
10587 	union lpfc_wqe128 *wqe = &lpfc_cmd->cur_iocbq.wqe;
10588 	struct sli4_sge_le *sgl;
10589 	u32 type_size;
10590 
10591 	/* 128 byte wqe support here */
10592 	sgl = (struct sli4_sge_le *)lpfc_cmd->dma_sgl;
10593 
10594 	if (phba->fcp_embed_io) {
10595 		struct fcp_cmnd *fcp_cmnd;
10596 		u32 *ptr;
10597 
10598 		fcp_cmnd = lpfc_cmd->fcp_cmnd;
10599 
10600 		/* Word 0-2 - FCP_CMND */
10601 		type_size = le32_to_cpu(sgl->sge_len);
10602 		type_size |= ULP_BDE64_TYPE_BDE_IMMED;
10603 		wqe->generic.bde.tus.w = type_size;
10604 		wqe->generic.bde.addrHigh = 0;
10605 		wqe->generic.bde.addrLow =  72;  /* Word 18 */
10606 
10607 		bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10608 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10609 
10610 		/* Word 18-29  FCP CMND Payload */
10611 		ptr = &wqe->words[18];
10612 		lpfc_sli_pcimem_bcopy(fcp_cmnd, ptr, le32_to_cpu(sgl->sge_len));
10613 	} else {
10614 		/* Word 0-2 - Inline BDE */
10615 		wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
10616 		wqe->generic.bde.tus.f.bdeSize = le32_to_cpu(sgl->sge_len);
10617 		wqe->generic.bde.addrHigh = le32_to_cpu(sgl->addr_hi);
10618 		wqe->generic.bde.addrLow = le32_to_cpu(sgl->addr_lo);
10619 
10620 		/* Word 10 */
10621 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10622 		bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
10623 	}
10624 
10625 	/* add the VMID tags as per switch response */
10626 	if (unlikely(piocb->cmd_flag & LPFC_IO_VMID)) {
10627 		if (phba->pport->vmid_flag & LPFC_VMID_TYPE_PRIO) {
10628 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
10629 			bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10630 					(piocb->vmid_tag.cs_ctl_vmid));
10631 		} else if (phba->cfg_vmid_app_header) {
10632 			bf_set(wqe_appid, &wqe->fcp_iwrite.wqe_com, 1);
10633 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10634 			wqe->words[31] = piocb->vmid_tag.app_id;
10635 		}
10636 	}
10637 }
10638 
10639 /**
10640  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10641  * @phba: Pointer to HBA context object.
10642  * @ring_number: SLI ring number to issue iocb on.
10643  * @piocb: Pointer to command iocb.
10644  * @flag: Flag indicating if this command can be put into txq.
10645  *
10646  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10647  * an iocb command to an HBA with SLI-4 interface spec.
10648  *
10649  * This function is called with ringlock held. The function will return success
10650  * after it successfully submit the iocb to firmware or after adding to the
10651  * txq.
10652  **/
10653 static int
10654 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10655 			 struct lpfc_iocbq *piocb, uint32_t flag)
10656 {
10657 	struct lpfc_sglq *sglq;
10658 	union lpfc_wqe128 *wqe;
10659 	struct lpfc_queue *wq;
10660 	struct lpfc_sli_ring *pring;
10661 	u32 ulp_command = get_job_cmnd(phba, piocb);
10662 
10663 	/* Get the WQ */
10664 	if ((piocb->cmd_flag & LPFC_IO_FCP) ||
10665 	    (piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
10666 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10667 	} else {
10668 		wq = phba->sli4_hba.els_wq;
10669 	}
10670 
10671 	/* Get corresponding ring */
10672 	pring = wq->pring;
10673 
10674 	/*
10675 	 * The WQE can be either 64 or 128 bytes,
10676 	 */
10677 
10678 	lockdep_assert_held(&pring->ring_lock);
10679 	wqe = &piocb->wqe;
10680 	if (piocb->sli4_xritag == NO_XRI) {
10681 		if (ulp_command == CMD_ABORT_XRI_CX)
10682 			sglq = NULL;
10683 		else {
10684 			sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10685 			if (!sglq) {
10686 				if (!(flag & SLI_IOCB_RET_IOCB)) {
10687 					__lpfc_sli_ringtx_put(phba,
10688 							pring,
10689 							piocb);
10690 					return IOCB_SUCCESS;
10691 				} else {
10692 					return IOCB_BUSY;
10693 				}
10694 			}
10695 		}
10696 	} else if (piocb->cmd_flag &  LPFC_IO_FCP) {
10697 		/* These IO's already have an XRI and a mapped sgl. */
10698 		sglq = NULL;
10699 	}
10700 	else {
10701 		/*
10702 		 * This is a continuation of a commandi,(CX) so this
10703 		 * sglq is on the active list
10704 		 */
10705 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10706 		if (!sglq)
10707 			return IOCB_ERROR;
10708 	}
10709 
10710 	if (sglq) {
10711 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10712 		piocb->sli4_xritag = sglq->sli4_xritag;
10713 
10714 		/* ABTS sent by initiator to CT exchange, the
10715 		 * RX_ID field will be filled with the newly
10716 		 * allocated responder XRI.
10717 		 */
10718 		if (ulp_command == CMD_XMIT_BLS_RSP64_CX &&
10719 		    piocb->abort_bls == LPFC_ABTS_UNSOL_INT)
10720 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10721 			       piocb->sli4_xritag);
10722 
10723 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com,
10724 		       piocb->sli4_xritag);
10725 
10726 		if (lpfc_wqe_bpl2sgl(phba, piocb, sglq) == NO_XRI)
10727 			return IOCB_ERROR;
10728 	}
10729 
10730 	if (lpfc_sli4_wq_put(wq, wqe))
10731 		return IOCB_ERROR;
10732 
10733 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10734 
10735 	return 0;
10736 }
10737 
10738 /*
10739  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
10740  *
10741  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
10742  * or IOCB for sli-3  function.
10743  * pointer from the lpfc_hba struct.
10744  *
10745  * Return codes:
10746  * IOCB_ERROR - Error
10747  * IOCB_SUCCESS - Success
10748  * IOCB_BUSY - Busy
10749  **/
10750 int
10751 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
10752 		      struct lpfc_iocbq *piocb, uint32_t flag)
10753 {
10754 	return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
10755 }
10756 
10757 /*
10758  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10759  *
10760  * This routine wraps the actual lockless version for issusing IOCB function
10761  * pointer from the lpfc_hba struct.
10762  *
10763  * Return codes:
10764  * IOCB_ERROR - Error
10765  * IOCB_SUCCESS - Success
10766  * IOCB_BUSY - Busy
10767  **/
10768 int
10769 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10770 		struct lpfc_iocbq *piocb, uint32_t flag)
10771 {
10772 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10773 }
10774 
10775 static void
10776 __lpfc_sli_prep_els_req_rsp_s3(struct lpfc_iocbq *cmdiocbq,
10777 			       struct lpfc_vport *vport,
10778 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10779 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10780 {
10781 	struct lpfc_hba *phba = vport->phba;
10782 	IOCB_t *cmd;
10783 
10784 	cmd = &cmdiocbq->iocb;
10785 	memset(cmd, 0, sizeof(*cmd));
10786 
10787 	cmd->un.elsreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10788 	cmd->un.elsreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10789 	cmd->un.elsreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10790 
10791 	if (expect_rsp) {
10792 		cmd->un.elsreq64.bdl.bdeSize = (2 * sizeof(struct ulp_bde64));
10793 		cmd->un.elsreq64.remoteID = did; /* DID */
10794 		cmd->ulpCommand = CMD_ELS_REQUEST64_CR;
10795 		cmd->ulpTimeout = tmo;
10796 	} else {
10797 		cmd->un.elsreq64.bdl.bdeSize = sizeof(struct ulp_bde64);
10798 		cmd->un.genreq64.xmit_els_remoteID = did; /* DID */
10799 		cmd->ulpCommand = CMD_XMIT_ELS_RSP64_CX;
10800 		cmd->ulpPU = PARM_NPIV_DID;
10801 	}
10802 	cmd->ulpBdeCount = 1;
10803 	cmd->ulpLe = 1;
10804 	cmd->ulpClass = CLASS3;
10805 
10806 	/* If we have NPIV enabled, we want to send ELS traffic by VPI. */
10807 	if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) {
10808 		if (expect_rsp) {
10809 			cmd->un.elsreq64.myID = vport->fc_myDID;
10810 
10811 			/* For ELS_REQUEST64_CR, use the VPI by default */
10812 			cmd->ulpContext = phba->vpi_ids[vport->vpi];
10813 		}
10814 
10815 		cmd->ulpCt_h = 0;
10816 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10817 		if (elscmd == ELS_CMD_ECHO)
10818 			cmd->ulpCt_l = 0; /* context = invalid RPI */
10819 		else
10820 			cmd->ulpCt_l = 1; /* context = VPI */
10821 	}
10822 }
10823 
10824 static void
10825 __lpfc_sli_prep_els_req_rsp_s4(struct lpfc_iocbq *cmdiocbq,
10826 			       struct lpfc_vport *vport,
10827 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10828 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10829 {
10830 	struct lpfc_hba  *phba = vport->phba;
10831 	union lpfc_wqe128 *wqe;
10832 	struct ulp_bde64_le *bde;
10833 	u8 els_id;
10834 
10835 	wqe = &cmdiocbq->wqe;
10836 	memset(wqe, 0, sizeof(*wqe));
10837 
10838 	/* Word 0 - 2 BDE */
10839 	bde = (struct ulp_bde64_le *)&wqe->generic.bde;
10840 	bde->addr_low = cpu_to_le32(putPaddrLow(bmp->phys));
10841 	bde->addr_high = cpu_to_le32(putPaddrHigh(bmp->phys));
10842 	bde->type_size = cpu_to_le32(cmd_size);
10843 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10844 
10845 	if (expect_rsp) {
10846 		bf_set(wqe_cmnd, &wqe->els_req.wqe_com, CMD_ELS_REQUEST64_WQE);
10847 
10848 		/* Transfer length */
10849 		wqe->els_req.payload_len = cmd_size;
10850 		wqe->els_req.max_response_payload_len = FCELSSIZE;
10851 
10852 		/* DID */
10853 		bf_set(wqe_els_did, &wqe->els_req.wqe_dest, did);
10854 
10855 		/* Word 11 - ELS_ID */
10856 		switch (elscmd) {
10857 		case ELS_CMD_PLOGI:
10858 			els_id = LPFC_ELS_ID_PLOGI;
10859 			break;
10860 		case ELS_CMD_FLOGI:
10861 			els_id = LPFC_ELS_ID_FLOGI;
10862 			break;
10863 		case ELS_CMD_LOGO:
10864 			els_id = LPFC_ELS_ID_LOGO;
10865 			break;
10866 		case ELS_CMD_FDISC:
10867 			if (!vport->fc_myDID) {
10868 				els_id = LPFC_ELS_ID_FDISC;
10869 				break;
10870 			}
10871 			fallthrough;
10872 		default:
10873 			els_id = LPFC_ELS_ID_DEFAULT;
10874 			break;
10875 		}
10876 
10877 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
10878 	} else {
10879 		/* DID */
10880 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest, did);
10881 
10882 		/* Transfer length */
10883 		wqe->xmit_els_rsp.response_payload_len = cmd_size;
10884 
10885 		bf_set(wqe_cmnd, &wqe->xmit_els_rsp.wqe_com,
10886 		       CMD_XMIT_ELS_RSP64_WQE);
10887 	}
10888 
10889 	bf_set(wqe_tmo, &wqe->generic.wqe_com, tmo);
10890 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, cmdiocbq->iotag);
10891 	bf_set(wqe_class, &wqe->generic.wqe_com, CLASS3);
10892 
10893 	/* If we have NPIV enabled, we want to send ELS traffic by VPI.
10894 	 * For SLI4, since the driver controls VPIs we also want to include
10895 	 * all ELS pt2pt protocol traffic as well.
10896 	 */
10897 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) ||
10898 	    test_bit(FC_PT2PT, &vport->fc_flag)) {
10899 		if (expect_rsp) {
10900 			bf_set(els_req64_sid, &wqe->els_req, vport->fc_myDID);
10901 
10902 			/* For ELS_REQUEST64_WQE, use the VPI by default */
10903 			bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10904 			       phba->vpi_ids[vport->vpi]);
10905 		}
10906 
10907 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10908 		if (elscmd == ELS_CMD_ECHO)
10909 			bf_set(wqe_ct, &wqe->generic.wqe_com, 0);
10910 		else
10911 			bf_set(wqe_ct, &wqe->generic.wqe_com, 1);
10912 	}
10913 }
10914 
10915 void
10916 lpfc_sli_prep_els_req_rsp(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
10917 			  struct lpfc_vport *vport, struct lpfc_dmabuf *bmp,
10918 			  u16 cmd_size, u32 did, u32 elscmd, u8 tmo,
10919 			  u8 expect_rsp)
10920 {
10921 	phba->__lpfc_sli_prep_els_req_rsp(cmdiocbq, vport, bmp, cmd_size, did,
10922 					  elscmd, tmo, expect_rsp);
10923 }
10924 
10925 static void
10926 __lpfc_sli_prep_gen_req_s3(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10927 			   u16 rpi, u32 num_entry, u8 tmo)
10928 {
10929 	IOCB_t *cmd;
10930 
10931 	cmd = &cmdiocbq->iocb;
10932 	memset(cmd, 0, sizeof(*cmd));
10933 
10934 	cmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10935 	cmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10936 	cmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10937 	cmd->un.genreq64.bdl.bdeSize = num_entry * sizeof(struct ulp_bde64);
10938 
10939 	cmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
10940 	cmd->un.genreq64.w5.hcsw.Type = FC_TYPE_CT;
10941 	cmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
10942 
10943 	cmd->ulpContext = rpi;
10944 	cmd->ulpClass = CLASS3;
10945 	cmd->ulpCommand = CMD_GEN_REQUEST64_CR;
10946 	cmd->ulpBdeCount = 1;
10947 	cmd->ulpLe = 1;
10948 	cmd->ulpOwner = OWN_CHIP;
10949 	cmd->ulpTimeout = tmo;
10950 }
10951 
10952 static void
10953 __lpfc_sli_prep_gen_req_s4(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10954 			   u16 rpi, u32 num_entry, u8 tmo)
10955 {
10956 	union lpfc_wqe128 *cmdwqe;
10957 	struct ulp_bde64_le *bde, *bpl;
10958 	u32 xmit_len = 0, total_len = 0, size, type, i;
10959 
10960 	cmdwqe = &cmdiocbq->wqe;
10961 	memset(cmdwqe, 0, sizeof(*cmdwqe));
10962 
10963 	/* Calculate total_len and xmit_len */
10964 	bpl = (struct ulp_bde64_le *)bmp->virt;
10965 	for (i = 0; i < num_entry; i++) {
10966 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10967 		total_len += size;
10968 	}
10969 	for (i = 0; i < num_entry; i++) {
10970 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10971 		type = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_TYPE_MASK;
10972 		if (type != ULP_BDE64_TYPE_BDE_64)
10973 			break;
10974 		xmit_len += size;
10975 	}
10976 
10977 	/* Words 0 - 2 */
10978 	bde = (struct ulp_bde64_le *)&cmdwqe->generic.bde;
10979 	bde->addr_low = bpl->addr_low;
10980 	bde->addr_high = bpl->addr_high;
10981 	bde->type_size = cpu_to_le32(xmit_len);
10982 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10983 
10984 	/* Word 3 */
10985 	cmdwqe->gen_req.request_payload_len = xmit_len;
10986 
10987 	/* Word 5 */
10988 	bf_set(wqe_type, &cmdwqe->gen_req.wge_ctl, FC_TYPE_CT);
10989 	bf_set(wqe_rctl, &cmdwqe->gen_req.wge_ctl, FC_RCTL_DD_UNSOL_CTL);
10990 	bf_set(wqe_si, &cmdwqe->gen_req.wge_ctl, 1);
10991 	bf_set(wqe_la, &cmdwqe->gen_req.wge_ctl, 1);
10992 
10993 	/* Word 6 */
10994 	bf_set(wqe_ctxt_tag, &cmdwqe->gen_req.wqe_com, rpi);
10995 
10996 	/* Word 7 */
10997 	bf_set(wqe_tmo, &cmdwqe->gen_req.wqe_com, tmo);
10998 	bf_set(wqe_class, &cmdwqe->gen_req.wqe_com, CLASS3);
10999 	bf_set(wqe_cmnd, &cmdwqe->gen_req.wqe_com, CMD_GEN_REQUEST64_CR);
11000 	bf_set(wqe_ct, &cmdwqe->gen_req.wqe_com, SLI4_CT_RPI);
11001 
11002 	/* Word 12 */
11003 	cmdwqe->gen_req.max_response_payload_len = total_len - xmit_len;
11004 }
11005 
11006 void
11007 lpfc_sli_prep_gen_req(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11008 		      struct lpfc_dmabuf *bmp, u16 rpi, u32 num_entry, u8 tmo)
11009 {
11010 	phba->__lpfc_sli_prep_gen_req(cmdiocbq, bmp, rpi, num_entry, tmo);
11011 }
11012 
11013 static void
11014 __lpfc_sli_prep_xmit_seq64_s3(struct lpfc_iocbq *cmdiocbq,
11015 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11016 			      u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11017 {
11018 	IOCB_t *icmd;
11019 
11020 	icmd = &cmdiocbq->iocb;
11021 	memset(icmd, 0, sizeof(*icmd));
11022 
11023 	icmd->un.xseq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
11024 	icmd->un.xseq64.bdl.addrLow = putPaddrLow(bmp->phys);
11025 	icmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
11026 	icmd->un.xseq64.bdl.bdeSize = (num_entry * sizeof(struct ulp_bde64));
11027 	icmd->un.xseq64.w5.hcsw.Fctl = LA;
11028 	if (last_seq)
11029 		icmd->un.xseq64.w5.hcsw.Fctl |= LS;
11030 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
11031 	icmd->un.xseq64.w5.hcsw.Rctl = rctl;
11032 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
11033 
11034 	icmd->ulpBdeCount = 1;
11035 	icmd->ulpLe = 1;
11036 	icmd->ulpClass = CLASS3;
11037 
11038 	switch (cr_cx_cmd) {
11039 	case CMD_XMIT_SEQUENCE64_CR:
11040 		icmd->ulpContext = rpi;
11041 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CR;
11042 		break;
11043 	case CMD_XMIT_SEQUENCE64_CX:
11044 		icmd->ulpContext = ox_id;
11045 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CX;
11046 		break;
11047 	default:
11048 		break;
11049 	}
11050 }
11051 
11052 static void
11053 __lpfc_sli_prep_xmit_seq64_s4(struct lpfc_iocbq *cmdiocbq,
11054 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11055 			      u32 full_size, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11056 {
11057 	union lpfc_wqe128 *wqe;
11058 	struct ulp_bde64 *bpl;
11059 
11060 	wqe = &cmdiocbq->wqe;
11061 	memset(wqe, 0, sizeof(*wqe));
11062 
11063 	/* Words 0 - 2 */
11064 	bpl = (struct ulp_bde64 *)bmp->virt;
11065 	wqe->xmit_sequence.bde.addrHigh = bpl->addrHigh;
11066 	wqe->xmit_sequence.bde.addrLow = bpl->addrLow;
11067 	wqe->xmit_sequence.bde.tus.w = bpl->tus.w;
11068 
11069 	/* Word 5 */
11070 	bf_set(wqe_ls, &wqe->xmit_sequence.wge_ctl, last_seq);
11071 	bf_set(wqe_la, &wqe->xmit_sequence.wge_ctl, 1);
11072 	bf_set(wqe_dfctl, &wqe->xmit_sequence.wge_ctl, 0);
11073 	bf_set(wqe_rctl, &wqe->xmit_sequence.wge_ctl, rctl);
11074 	bf_set(wqe_type, &wqe->xmit_sequence.wge_ctl, FC_TYPE_CT);
11075 
11076 	/* Word 6 */
11077 	bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com, rpi);
11078 
11079 	bf_set(wqe_cmnd, &wqe->xmit_sequence.wqe_com,
11080 	       CMD_XMIT_SEQUENCE64_WQE);
11081 
11082 	/* Word 7 */
11083 	bf_set(wqe_class, &wqe->xmit_sequence.wqe_com, CLASS3);
11084 
11085 	/* Word 9 */
11086 	bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com, ox_id);
11087 
11088 	if (cmdiocbq->cmd_flag & (LPFC_IO_LIBDFC | LPFC_IO_LOOPBACK)) {
11089 		/* Word 10 */
11090 		if (cmdiocbq->cmd_flag & LPFC_IO_VMID) {
11091 			bf_set(wqe_appid, &wqe->xmit_sequence.wqe_com, 1);
11092 			bf_set(wqe_wqes, &wqe->xmit_sequence.wqe_com, 1);
11093 			wqe->words[31] = LOOPBACK_SRC_APPID;
11094 		}
11095 
11096 		/* Word 12 */
11097 		wqe->xmit_sequence.xmit_len = full_size;
11098 	}
11099 	else
11100 		wqe->xmit_sequence.xmit_len =
11101 			wqe->xmit_sequence.bde.tus.f.bdeSize;
11102 }
11103 
11104 void
11105 lpfc_sli_prep_xmit_seq64(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11106 			 struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11107 			 u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11108 {
11109 	phba->__lpfc_sli_prep_xmit_seq64(cmdiocbq, bmp, rpi, ox_id, num_entry,
11110 					 rctl, last_seq, cr_cx_cmd);
11111 }
11112 
11113 static void
11114 __lpfc_sli_prep_abort_xri_s3(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11115 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11116 			     bool wqec)
11117 {
11118 	IOCB_t *icmd = NULL;
11119 
11120 	icmd = &cmdiocbq->iocb;
11121 	memset(icmd, 0, sizeof(*icmd));
11122 
11123 	/* Word 5 */
11124 	icmd->un.acxri.abortContextTag = ulp_context;
11125 	icmd->un.acxri.abortIoTag = iotag;
11126 
11127 	if (ia) {
11128 		/* Word 7 */
11129 		icmd->ulpCommand = CMD_CLOSE_XRI_CN;
11130 	} else {
11131 		/* Word 3 */
11132 		icmd->un.acxri.abortType = ABORT_TYPE_ABTS;
11133 
11134 		/* Word 7 */
11135 		icmd->ulpClass = ulp_class;
11136 		icmd->ulpCommand = CMD_ABORT_XRI_CN;
11137 	}
11138 
11139 	/* Word 7 */
11140 	icmd->ulpLe = 1;
11141 }
11142 
11143 static void
11144 __lpfc_sli_prep_abort_xri_s4(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11145 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11146 			     bool wqec)
11147 {
11148 	union lpfc_wqe128 *wqe;
11149 
11150 	wqe = &cmdiocbq->wqe;
11151 	memset(wqe, 0, sizeof(*wqe));
11152 
11153 	/* Word 3 */
11154 	bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
11155 	if (ia)
11156 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
11157 	else
11158 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
11159 
11160 	/* Word 7 */
11161 	bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_WQE);
11162 
11163 	/* Word 8 */
11164 	wqe->abort_cmd.wqe_com.abort_tag = ulp_context;
11165 
11166 	/* Word 9 */
11167 	bf_set(wqe_reqtag, &wqe->abort_cmd.wqe_com, iotag);
11168 
11169 	/* Word 10 */
11170 	bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
11171 
11172 	/* Word 11 */
11173 	if (wqec)
11174 		bf_set(wqe_wqec, &wqe->abort_cmd.wqe_com, 1);
11175 	bf_set(wqe_cqid, &wqe->abort_cmd.wqe_com, cqid);
11176 	bf_set(wqe_cmd_type, &wqe->abort_cmd.wqe_com, OTHER_COMMAND);
11177 }
11178 
11179 void
11180 lpfc_sli_prep_abort_xri(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11181 			u16 ulp_context, u16 iotag, u8 ulp_class, u16 cqid,
11182 			bool ia, bool wqec)
11183 {
11184 	phba->__lpfc_sli_prep_abort_xri(cmdiocbq, ulp_context, iotag, ulp_class,
11185 					cqid, ia, wqec);
11186 }
11187 
11188 /**
11189  * lpfc_sli_api_table_setup - Set up sli api function jump table
11190  * @phba: The hba struct for which this call is being executed.
11191  * @dev_grp: The HBA PCI-Device group number.
11192  *
11193  * This routine sets up the SLI interface API function jump table in @phba
11194  * struct.
11195  * Returns: 0 - success, -ENODEV - failure.
11196  **/
11197 int
11198 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
11199 {
11200 
11201 	switch (dev_grp) {
11202 	case LPFC_PCI_DEV_LP:
11203 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
11204 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
11205 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
11206 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s3;
11207 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s3;
11208 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s3;
11209 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s3;
11210 		break;
11211 	case LPFC_PCI_DEV_OC:
11212 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
11213 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
11214 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
11215 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s4;
11216 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s4;
11217 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s4;
11218 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s4;
11219 		break;
11220 	default:
11221 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11222 				"1419 Invalid HBA PCI-device group: 0x%x\n",
11223 				dev_grp);
11224 		return -ENODEV;
11225 	}
11226 	return 0;
11227 }
11228 
11229 /**
11230  * lpfc_sli4_calc_ring - Calculates which ring to use
11231  * @phba: Pointer to HBA context object.
11232  * @piocb: Pointer to command iocb.
11233  *
11234  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
11235  * hba_wqidx, thus we need to calculate the corresponding ring.
11236  * Since ABORTS must go on the same WQ of the command they are
11237  * aborting, we use command's hba_wqidx.
11238  */
11239 struct lpfc_sli_ring *
11240 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
11241 {
11242 	struct lpfc_io_buf *lpfc_cmd;
11243 
11244 	if (piocb->cmd_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
11245 		if (unlikely(!phba->sli4_hba.hdwq))
11246 			return NULL;
11247 		/*
11248 		 * for abort iocb hba_wqidx should already
11249 		 * be setup based on what work queue we used.
11250 		 */
11251 		if (!(piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
11252 			lpfc_cmd = piocb->io_buf;
11253 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
11254 		}
11255 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
11256 	} else {
11257 		if (unlikely(!phba->sli4_hba.els_wq))
11258 			return NULL;
11259 		piocb->hba_wqidx = 0;
11260 		return phba->sli4_hba.els_wq->pring;
11261 	}
11262 }
11263 
11264 inline void lpfc_sli4_poll_eq(struct lpfc_queue *eq)
11265 {
11266 	struct lpfc_hba *phba = eq->phba;
11267 
11268 	/*
11269 	 * Unlocking an irq is one of the entry point to check
11270 	 * for re-schedule, but we are good for io submission
11271 	 * path as midlayer does a get_cpu to glue us in. Flush
11272 	 * out the invalidate queue so we can see the updated
11273 	 * value for flag.
11274 	 */
11275 	smp_rmb();
11276 
11277 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
11278 		/* We will not likely get the completion for the caller
11279 		 * during this iteration but i guess that's fine.
11280 		 * Future io's coming on this eq should be able to
11281 		 * pick it up.  As for the case of single io's, they
11282 		 * will be handled through a sched from polling timer
11283 		 * function which is currently triggered every 1msec.
11284 		 */
11285 		lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM,
11286 				     LPFC_QUEUE_WORK);
11287 }
11288 
11289 /**
11290  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
11291  * @phba: Pointer to HBA context object.
11292  * @ring_number: Ring number
11293  * @piocb: Pointer to command iocb.
11294  * @flag: Flag indicating if this command can be put into txq.
11295  *
11296  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
11297  * function. This function gets the hbalock and calls
11298  * __lpfc_sli_issue_iocb function and will return the error returned
11299  * by __lpfc_sli_issue_iocb function. This wrapper is used by
11300  * functions which do not hold hbalock.
11301  **/
11302 int
11303 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
11304 		    struct lpfc_iocbq *piocb, uint32_t flag)
11305 {
11306 	struct lpfc_sli_ring *pring;
11307 	struct lpfc_queue *eq;
11308 	unsigned long iflags;
11309 	int rc;
11310 
11311 	/* If the PCI channel is in offline state, do not post iocbs. */
11312 	if (unlikely(pci_channel_offline(phba->pcidev)))
11313 		return IOCB_ERROR;
11314 
11315 	if (phba->sli_rev == LPFC_SLI_REV4) {
11316 		lpfc_sli_prep_wqe(phba, piocb);
11317 
11318 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
11319 
11320 		pring = lpfc_sli4_calc_ring(phba, piocb);
11321 		if (unlikely(pring == NULL))
11322 			return IOCB_ERROR;
11323 
11324 		spin_lock_irqsave(&pring->ring_lock, iflags);
11325 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11326 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11327 
11328 		lpfc_sli4_poll_eq(eq);
11329 	} else {
11330 		/* For now, SLI2/3 will still use hbalock */
11331 		spin_lock_irqsave(&phba->hbalock, iflags);
11332 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11333 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11334 	}
11335 	return rc;
11336 }
11337 
11338 /**
11339  * lpfc_extra_ring_setup - Extra ring setup function
11340  * @phba: Pointer to HBA context object.
11341  *
11342  * This function is called while driver attaches with the
11343  * HBA to setup the extra ring. The extra ring is used
11344  * only when driver needs to support target mode functionality
11345  * or IP over FC functionalities.
11346  *
11347  * This function is called with no lock held. SLI3 only.
11348  **/
11349 static int
11350 lpfc_extra_ring_setup( struct lpfc_hba *phba)
11351 {
11352 	struct lpfc_sli *psli;
11353 	struct lpfc_sli_ring *pring;
11354 
11355 	psli = &phba->sli;
11356 
11357 	/* Adjust cmd/rsp ring iocb entries more evenly */
11358 
11359 	/* Take some away from the FCP ring */
11360 	pring = &psli->sli3_ring[LPFC_FCP_RING];
11361 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11362 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11363 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11364 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11365 
11366 	/* and give them to the extra ring */
11367 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
11368 
11369 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11370 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11371 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11372 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11373 
11374 	/* Setup default profile for this ring */
11375 	pring->iotag_max = 4096;
11376 	pring->num_mask = 1;
11377 	pring->prt[0].profile = 0;      /* Mask 0 */
11378 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
11379 	pring->prt[0].type = phba->cfg_multi_ring_type;
11380 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
11381 	return 0;
11382 }
11383 
11384 static void
11385 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
11386 			     struct lpfc_nodelist *ndlp)
11387 {
11388 	unsigned long iflags;
11389 	struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
11390 
11391 	/* Hold a node reference for outstanding queued work */
11392 	if (!lpfc_nlp_get(ndlp))
11393 		return;
11394 
11395 	spin_lock_irqsave(&phba->hbalock, iflags);
11396 	if (!list_empty(&evtp->evt_listp)) {
11397 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11398 		lpfc_nlp_put(ndlp);
11399 		return;
11400 	}
11401 
11402 	evtp->evt_arg1 = ndlp;
11403 	evtp->evt = LPFC_EVT_RECOVER_PORT;
11404 	list_add_tail(&evtp->evt_listp, &phba->work_list);
11405 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11406 
11407 	lpfc_worker_wake_up(phba);
11408 }
11409 
11410 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
11411  * @phba: Pointer to HBA context object.
11412  * @iocbq: Pointer to iocb object.
11413  *
11414  * The async_event handler calls this routine when it receives
11415  * an ASYNC_STATUS_CN event from the port.  The port generates
11416  * this event when an Abort Sequence request to an rport fails
11417  * twice in succession.  The abort could be originated by the
11418  * driver or by the port.  The ABTS could have been for an ELS
11419  * or FCP IO.  The port only generates this event when an ABTS
11420  * fails to complete after one retry.
11421  */
11422 static void
11423 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
11424 			  struct lpfc_iocbq *iocbq)
11425 {
11426 	struct lpfc_nodelist *ndlp = NULL;
11427 	uint16_t rpi = 0, vpi = 0;
11428 	struct lpfc_vport *vport = NULL;
11429 
11430 	/* The rpi in the ulpContext is vport-sensitive. */
11431 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
11432 	rpi = iocbq->iocb.ulpContext;
11433 
11434 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11435 			"3092 Port generated ABTS async event "
11436 			"on vpi %d rpi %d status 0x%x\n",
11437 			vpi, rpi, iocbq->iocb.ulpStatus);
11438 
11439 	vport = lpfc_find_vport_by_vpid(phba, vpi);
11440 	if (!vport)
11441 		goto err_exit;
11442 	ndlp = lpfc_findnode_rpi(vport, rpi);
11443 	if (!ndlp)
11444 		goto err_exit;
11445 
11446 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
11447 		lpfc_sli_abts_recover_port(vport, ndlp);
11448 	return;
11449 
11450  err_exit:
11451 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11452 			"3095 Event Context not found, no "
11453 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
11454 			vpi, rpi, iocbq->iocb.ulpStatus,
11455 			iocbq->iocb.ulpContext);
11456 }
11457 
11458 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
11459  * @phba: pointer to HBA context object.
11460  * @ndlp: nodelist pointer for the impacted rport.
11461  * @axri: pointer to the wcqe containing the failed exchange.
11462  *
11463  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
11464  * port.  The port generates this event when an abort exchange request to an
11465  * rport fails twice in succession with no reply.  The abort could be originated
11466  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
11467  */
11468 void
11469 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
11470 			   struct lpfc_nodelist *ndlp,
11471 			   struct sli4_wcqe_xri_aborted *axri)
11472 {
11473 	uint32_t ext_status = 0;
11474 
11475 	if (!ndlp) {
11476 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11477 				"3115 Node Context not found, driver "
11478 				"ignoring abts err event\n");
11479 		return;
11480 	}
11481 
11482 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11483 			"3116 Port generated FCP XRI ABORT event on "
11484 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
11485 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
11486 			bf_get(lpfc_wcqe_xa_xri, axri),
11487 			bf_get(lpfc_wcqe_xa_status, axri),
11488 			axri->parameter);
11489 
11490 	/*
11491 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
11492 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
11493 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
11494 	 */
11495 	ext_status = axri->parameter & IOERR_PARAM_MASK;
11496 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
11497 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
11498 		lpfc_sli_post_recovery_event(phba, ndlp);
11499 }
11500 
11501 /**
11502  * lpfc_sli_async_event_handler - ASYNC iocb handler function
11503  * @phba: Pointer to HBA context object.
11504  * @pring: Pointer to driver SLI ring object.
11505  * @iocbq: Pointer to iocb object.
11506  *
11507  * This function is called by the slow ring event handler
11508  * function when there is an ASYNC event iocb in the ring.
11509  * This function is called with no lock held.
11510  * Currently this function handles only temperature related
11511  * ASYNC events. The function decodes the temperature sensor
11512  * event message and posts events for the management applications.
11513  **/
11514 static void
11515 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
11516 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
11517 {
11518 	IOCB_t *icmd;
11519 	uint16_t evt_code;
11520 	struct temp_event temp_event_data;
11521 	struct Scsi_Host *shost;
11522 	uint32_t *iocb_w;
11523 
11524 	icmd = &iocbq->iocb;
11525 	evt_code = icmd->un.asyncstat.evt_code;
11526 
11527 	switch (evt_code) {
11528 	case ASYNC_TEMP_WARN:
11529 	case ASYNC_TEMP_SAFE:
11530 		temp_event_data.data = (uint32_t) icmd->ulpContext;
11531 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
11532 		if (evt_code == ASYNC_TEMP_WARN) {
11533 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
11534 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11535 				"0347 Adapter is very hot, please take "
11536 				"corrective action. temperature : %d Celsius\n",
11537 				(uint32_t) icmd->ulpContext);
11538 		} else {
11539 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
11540 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11541 				"0340 Adapter temperature is OK now. "
11542 				"temperature : %d Celsius\n",
11543 				(uint32_t) icmd->ulpContext);
11544 		}
11545 
11546 		/* Send temperature change event to applications */
11547 		shost = lpfc_shost_from_vport(phba->pport);
11548 		fc_host_post_vendor_event(shost, fc_get_event_number(),
11549 			sizeof(temp_event_data), (char *) &temp_event_data,
11550 			LPFC_NL_VENDOR_ID);
11551 		break;
11552 	case ASYNC_STATUS_CN:
11553 		lpfc_sli_abts_err_handler(phba, iocbq);
11554 		break;
11555 	default:
11556 		iocb_w = (uint32_t *) icmd;
11557 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11558 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
11559 			" evt_code 0x%x\n"
11560 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
11561 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
11562 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
11563 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
11564 			pring->ringno, icmd->un.asyncstat.evt_code,
11565 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
11566 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
11567 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
11568 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
11569 
11570 		break;
11571 	}
11572 }
11573 
11574 
11575 /**
11576  * lpfc_sli4_setup - SLI ring setup function
11577  * @phba: Pointer to HBA context object.
11578  *
11579  * lpfc_sli_setup sets up rings of the SLI interface with
11580  * number of iocbs per ring and iotags. This function is
11581  * called while driver attach to the HBA and before the
11582  * interrupts are enabled. So there is no need for locking.
11583  *
11584  * This function always returns 0.
11585  **/
11586 int
11587 lpfc_sli4_setup(struct lpfc_hba *phba)
11588 {
11589 	struct lpfc_sli_ring *pring;
11590 
11591 	pring = phba->sli4_hba.els_wq->pring;
11592 	pring->num_mask = LPFC_MAX_RING_MASK;
11593 	pring->prt[0].profile = 0;	/* Mask 0 */
11594 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11595 	pring->prt[0].type = FC_TYPE_ELS;
11596 	pring->prt[0].lpfc_sli_rcv_unsol_event =
11597 	    lpfc_els_unsol_event;
11598 	pring->prt[1].profile = 0;	/* Mask 1 */
11599 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
11600 	pring->prt[1].type = FC_TYPE_ELS;
11601 	pring->prt[1].lpfc_sli_rcv_unsol_event =
11602 	    lpfc_els_unsol_event;
11603 	pring->prt[2].profile = 0;	/* Mask 2 */
11604 	/* NameServer Inquiry */
11605 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11606 	/* NameServer */
11607 	pring->prt[2].type = FC_TYPE_CT;
11608 	pring->prt[2].lpfc_sli_rcv_unsol_event =
11609 	    lpfc_ct_unsol_event;
11610 	pring->prt[3].profile = 0;	/* Mask 3 */
11611 	/* NameServer response */
11612 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11613 	/* NameServer */
11614 	pring->prt[3].type = FC_TYPE_CT;
11615 	pring->prt[3].lpfc_sli_rcv_unsol_event =
11616 	    lpfc_ct_unsol_event;
11617 	return 0;
11618 }
11619 
11620 /**
11621  * lpfc_sli_setup - SLI ring setup function
11622  * @phba: Pointer to HBA context object.
11623  *
11624  * lpfc_sli_setup sets up rings of the SLI interface with
11625  * number of iocbs per ring and iotags. This function is
11626  * called while driver attach to the HBA and before the
11627  * interrupts are enabled. So there is no need for locking.
11628  *
11629  * This function always returns 0. SLI3 only.
11630  **/
11631 int
11632 lpfc_sli_setup(struct lpfc_hba *phba)
11633 {
11634 	int i, totiocbsize = 0;
11635 	struct lpfc_sli *psli = &phba->sli;
11636 	struct lpfc_sli_ring *pring;
11637 
11638 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
11639 	psli->sli_flag = 0;
11640 
11641 	psli->iocbq_lookup = NULL;
11642 	psli->iocbq_lookup_len = 0;
11643 	psli->last_iotag = 0;
11644 
11645 	for (i = 0; i < psli->num_rings; i++) {
11646 		pring = &psli->sli3_ring[i];
11647 		switch (i) {
11648 		case LPFC_FCP_RING:	/* ring 0 - FCP */
11649 			/* numCiocb and numRiocb are used in config_port */
11650 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
11651 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
11652 			pring->sli.sli3.numCiocb +=
11653 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11654 			pring->sli.sli3.numRiocb +=
11655 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11656 			pring->sli.sli3.numCiocb +=
11657 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11658 			pring->sli.sli3.numRiocb +=
11659 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11660 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11661 							SLI3_IOCB_CMD_SIZE :
11662 							SLI2_IOCB_CMD_SIZE;
11663 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11664 							SLI3_IOCB_RSP_SIZE :
11665 							SLI2_IOCB_RSP_SIZE;
11666 			pring->iotag_ctr = 0;
11667 			pring->iotag_max =
11668 			    (phba->cfg_hba_queue_depth * 2);
11669 			pring->fast_iotag = pring->iotag_max;
11670 			pring->num_mask = 0;
11671 			break;
11672 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
11673 			/* numCiocb and numRiocb are used in config_port */
11674 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
11675 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
11676 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11677 							SLI3_IOCB_CMD_SIZE :
11678 							SLI2_IOCB_CMD_SIZE;
11679 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11680 							SLI3_IOCB_RSP_SIZE :
11681 							SLI2_IOCB_RSP_SIZE;
11682 			pring->iotag_max = phba->cfg_hba_queue_depth;
11683 			pring->num_mask = 0;
11684 			break;
11685 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
11686 			/* numCiocb and numRiocb are used in config_port */
11687 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
11688 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
11689 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11690 							SLI3_IOCB_CMD_SIZE :
11691 							SLI2_IOCB_CMD_SIZE;
11692 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11693 							SLI3_IOCB_RSP_SIZE :
11694 							SLI2_IOCB_RSP_SIZE;
11695 			pring->fast_iotag = 0;
11696 			pring->iotag_ctr = 0;
11697 			pring->iotag_max = 4096;
11698 			pring->lpfc_sli_rcv_async_status =
11699 				lpfc_sli_async_event_handler;
11700 			pring->num_mask = LPFC_MAX_RING_MASK;
11701 			pring->prt[0].profile = 0;	/* Mask 0 */
11702 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11703 			pring->prt[0].type = FC_TYPE_ELS;
11704 			pring->prt[0].lpfc_sli_rcv_unsol_event =
11705 			    lpfc_els_unsol_event;
11706 			pring->prt[1].profile = 0;	/* Mask 1 */
11707 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
11708 			pring->prt[1].type = FC_TYPE_ELS;
11709 			pring->prt[1].lpfc_sli_rcv_unsol_event =
11710 			    lpfc_els_unsol_event;
11711 			pring->prt[2].profile = 0;	/* Mask 2 */
11712 			/* NameServer Inquiry */
11713 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11714 			/* NameServer */
11715 			pring->prt[2].type = FC_TYPE_CT;
11716 			pring->prt[2].lpfc_sli_rcv_unsol_event =
11717 			    lpfc_ct_unsol_event;
11718 			pring->prt[3].profile = 0;	/* Mask 3 */
11719 			/* NameServer response */
11720 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11721 			/* NameServer */
11722 			pring->prt[3].type = FC_TYPE_CT;
11723 			pring->prt[3].lpfc_sli_rcv_unsol_event =
11724 			    lpfc_ct_unsol_event;
11725 			break;
11726 		}
11727 		totiocbsize += (pring->sli.sli3.numCiocb *
11728 			pring->sli.sli3.sizeCiocb) +
11729 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
11730 	}
11731 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
11732 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
11733 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
11734 		       "SLI2 SLIM Data: x%x x%lx\n",
11735 		       phba->brd_no, totiocbsize,
11736 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
11737 	}
11738 	if (phba->cfg_multi_ring_support == 2)
11739 		lpfc_extra_ring_setup(phba);
11740 
11741 	return 0;
11742 }
11743 
11744 /**
11745  * lpfc_sli4_queue_init - Queue initialization function
11746  * @phba: Pointer to HBA context object.
11747  *
11748  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
11749  * ring. This function also initializes ring indices of each ring.
11750  * This function is called during the initialization of the SLI
11751  * interface of an HBA.
11752  * This function is called with no lock held and always returns
11753  * 1.
11754  **/
11755 void
11756 lpfc_sli4_queue_init(struct lpfc_hba *phba)
11757 {
11758 	struct lpfc_sli *psli;
11759 	struct lpfc_sli_ring *pring;
11760 	int i;
11761 
11762 	psli = &phba->sli;
11763 	spin_lock_irq(&phba->hbalock);
11764 	INIT_LIST_HEAD(&psli->mboxq);
11765 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11766 	/* Initialize list headers for txq and txcmplq as double linked lists */
11767 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
11768 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
11769 		pring->flag = 0;
11770 		pring->ringno = LPFC_FCP_RING;
11771 		pring->txcmplq_cnt = 0;
11772 		INIT_LIST_HEAD(&pring->txq);
11773 		INIT_LIST_HEAD(&pring->txcmplq);
11774 		INIT_LIST_HEAD(&pring->iocb_continueq);
11775 		spin_lock_init(&pring->ring_lock);
11776 	}
11777 	pring = phba->sli4_hba.els_wq->pring;
11778 	pring->flag = 0;
11779 	pring->ringno = LPFC_ELS_RING;
11780 	pring->txcmplq_cnt = 0;
11781 	INIT_LIST_HEAD(&pring->txq);
11782 	INIT_LIST_HEAD(&pring->txcmplq);
11783 	INIT_LIST_HEAD(&pring->iocb_continueq);
11784 	spin_lock_init(&pring->ring_lock);
11785 
11786 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11787 		pring = phba->sli4_hba.nvmels_wq->pring;
11788 		pring->flag = 0;
11789 		pring->ringno = LPFC_ELS_RING;
11790 		pring->txcmplq_cnt = 0;
11791 		INIT_LIST_HEAD(&pring->txq);
11792 		INIT_LIST_HEAD(&pring->txcmplq);
11793 		INIT_LIST_HEAD(&pring->iocb_continueq);
11794 		spin_lock_init(&pring->ring_lock);
11795 	}
11796 
11797 	spin_unlock_irq(&phba->hbalock);
11798 }
11799 
11800 /**
11801  * lpfc_sli_queue_init - Queue initialization function
11802  * @phba: Pointer to HBA context object.
11803  *
11804  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11805  * ring. This function also initializes ring indices of each ring.
11806  * This function is called during the initialization of the SLI
11807  * interface of an HBA.
11808  * This function is called with no lock held and always returns
11809  * 1.
11810  **/
11811 void
11812 lpfc_sli_queue_init(struct lpfc_hba *phba)
11813 {
11814 	struct lpfc_sli *psli;
11815 	struct lpfc_sli_ring *pring;
11816 	int i;
11817 
11818 	psli = &phba->sli;
11819 	spin_lock_irq(&phba->hbalock);
11820 	INIT_LIST_HEAD(&psli->mboxq);
11821 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11822 	/* Initialize list headers for txq and txcmplq as double linked lists */
11823 	for (i = 0; i < psli->num_rings; i++) {
11824 		pring = &psli->sli3_ring[i];
11825 		pring->ringno = i;
11826 		pring->sli.sli3.next_cmdidx  = 0;
11827 		pring->sli.sli3.local_getidx = 0;
11828 		pring->sli.sli3.cmdidx = 0;
11829 		INIT_LIST_HEAD(&pring->iocb_continueq);
11830 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11831 		INIT_LIST_HEAD(&pring->postbufq);
11832 		pring->flag = 0;
11833 		INIT_LIST_HEAD(&pring->txq);
11834 		INIT_LIST_HEAD(&pring->txcmplq);
11835 		spin_lock_init(&pring->ring_lock);
11836 	}
11837 	spin_unlock_irq(&phba->hbalock);
11838 }
11839 
11840 /**
11841  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11842  * @phba: Pointer to HBA context object.
11843  *
11844  * This routine flushes the mailbox command subsystem. It will unconditionally
11845  * flush all the mailbox commands in the three possible stages in the mailbox
11846  * command sub-system: pending mailbox command queue; the outstanding mailbox
11847  * command; and completed mailbox command queue. It is caller's responsibility
11848  * to make sure that the driver is in the proper state to flush the mailbox
11849  * command sub-system. Namely, the posting of mailbox commands into the
11850  * pending mailbox command queue from the various clients must be stopped;
11851  * either the HBA is in a state that it will never works on the outstanding
11852  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11853  * mailbox command has been completed.
11854  **/
11855 static void
11856 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11857 {
11858 	LIST_HEAD(completions);
11859 	struct lpfc_sli *psli = &phba->sli;
11860 	LPFC_MBOXQ_t *pmb;
11861 	unsigned long iflag;
11862 
11863 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11864 	local_bh_disable();
11865 
11866 	/* Flush all the mailbox commands in the mbox system */
11867 	spin_lock_irqsave(&phba->hbalock, iflag);
11868 
11869 	/* The pending mailbox command queue */
11870 	list_splice_init(&phba->sli.mboxq, &completions);
11871 	/* The outstanding active mailbox command */
11872 	if (psli->mbox_active) {
11873 		list_add_tail(&psli->mbox_active->list, &completions);
11874 		psli->mbox_active = NULL;
11875 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11876 	}
11877 	/* The completed mailbox command queue */
11878 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11879 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11880 
11881 	/* Enable softirqs again, done with phba->hbalock */
11882 	local_bh_enable();
11883 
11884 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11885 	while (!list_empty(&completions)) {
11886 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11887 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11888 		if (pmb->mbox_cmpl)
11889 			pmb->mbox_cmpl(phba, pmb);
11890 	}
11891 }
11892 
11893 /**
11894  * lpfc_sli_host_down - Vport cleanup function
11895  * @vport: Pointer to virtual port object.
11896  *
11897  * lpfc_sli_host_down is called to clean up the resources
11898  * associated with a vport before destroying virtual
11899  * port data structures.
11900  * This function does following operations:
11901  * - Free discovery resources associated with this virtual
11902  *   port.
11903  * - Free iocbs associated with this virtual port in
11904  *   the txq.
11905  * - Send abort for all iocb commands associated with this
11906  *   vport in txcmplq.
11907  *
11908  * This function is called with no lock held and always returns 1.
11909  **/
11910 int
11911 lpfc_sli_host_down(struct lpfc_vport *vport)
11912 {
11913 	LIST_HEAD(completions);
11914 	struct lpfc_hba *phba = vport->phba;
11915 	struct lpfc_sli *psli = &phba->sli;
11916 	struct lpfc_queue *qp = NULL;
11917 	struct lpfc_sli_ring *pring;
11918 	struct lpfc_iocbq *iocb, *next_iocb;
11919 	int i;
11920 	unsigned long flags = 0;
11921 	uint16_t prev_pring_flag;
11922 
11923 	lpfc_cleanup_discovery_resources(vport);
11924 
11925 	spin_lock_irqsave(&phba->hbalock, flags);
11926 
11927 	/*
11928 	 * Error everything on the txq since these iocbs
11929 	 * have not been given to the FW yet.
11930 	 * Also issue ABTS for everything on the txcmplq
11931 	 */
11932 	if (phba->sli_rev != LPFC_SLI_REV4) {
11933 		for (i = 0; i < psli->num_rings; i++) {
11934 			pring = &psli->sli3_ring[i];
11935 			prev_pring_flag = pring->flag;
11936 			/* Only slow rings */
11937 			if (pring->ringno == LPFC_ELS_RING) {
11938 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11939 				/* Set the lpfc data pending flag */
11940 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11941 			}
11942 			list_for_each_entry_safe(iocb, next_iocb,
11943 						 &pring->txq, list) {
11944 				if (iocb->vport != vport)
11945 					continue;
11946 				list_move_tail(&iocb->list, &completions);
11947 			}
11948 			list_for_each_entry_safe(iocb, next_iocb,
11949 						 &pring->txcmplq, list) {
11950 				if (iocb->vport != vport)
11951 					continue;
11952 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11953 							   NULL);
11954 			}
11955 			pring->flag = prev_pring_flag;
11956 		}
11957 	} else {
11958 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11959 			pring = qp->pring;
11960 			if (!pring)
11961 				continue;
11962 			if (pring == phba->sli4_hba.els_wq->pring) {
11963 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11964 				/* Set the lpfc data pending flag */
11965 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11966 			}
11967 			prev_pring_flag = pring->flag;
11968 			spin_lock(&pring->ring_lock);
11969 			list_for_each_entry_safe(iocb, next_iocb,
11970 						 &pring->txq, list) {
11971 				if (iocb->vport != vport)
11972 					continue;
11973 				list_move_tail(&iocb->list, &completions);
11974 			}
11975 			spin_unlock(&pring->ring_lock);
11976 			list_for_each_entry_safe(iocb, next_iocb,
11977 						 &pring->txcmplq, list) {
11978 				if (iocb->vport != vport)
11979 					continue;
11980 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11981 							   NULL);
11982 			}
11983 			pring->flag = prev_pring_flag;
11984 		}
11985 	}
11986 	spin_unlock_irqrestore(&phba->hbalock, flags);
11987 
11988 	/* Make sure HBA is alive */
11989 	lpfc_issue_hb_tmo(phba);
11990 
11991 	/* Cancel all the IOCBs from the completions list */
11992 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11993 			      IOERR_SLI_DOWN);
11994 	return 1;
11995 }
11996 
11997 /**
11998  * lpfc_sli_hba_down - Resource cleanup function for the HBA
11999  * @phba: Pointer to HBA context object.
12000  *
12001  * This function cleans up all iocb, buffers, mailbox commands
12002  * while shutting down the HBA. This function is called with no
12003  * lock held and always returns 1.
12004  * This function does the following to cleanup driver resources:
12005  * - Free discovery resources for each virtual port
12006  * - Cleanup any pending fabric iocbs
12007  * - Iterate through the iocb txq and free each entry
12008  *   in the list.
12009  * - Free up any buffer posted to the HBA
12010  * - Free mailbox commands in the mailbox queue.
12011  **/
12012 int
12013 lpfc_sli_hba_down(struct lpfc_hba *phba)
12014 {
12015 	LIST_HEAD(completions);
12016 	struct lpfc_sli *psli = &phba->sli;
12017 	struct lpfc_queue *qp = NULL;
12018 	struct lpfc_sli_ring *pring;
12019 	struct lpfc_dmabuf *buf_ptr;
12020 	unsigned long flags = 0;
12021 	int i;
12022 
12023 	/* Shutdown the mailbox command sub-system */
12024 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
12025 
12026 	lpfc_hba_down_prep(phba);
12027 
12028 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12029 	local_bh_disable();
12030 
12031 	lpfc_fabric_abort_hba(phba);
12032 
12033 	spin_lock_irqsave(&phba->hbalock, flags);
12034 
12035 	/*
12036 	 * Error everything on the txq since these iocbs
12037 	 * have not been given to the FW yet.
12038 	 */
12039 	if (phba->sli_rev != LPFC_SLI_REV4) {
12040 		for (i = 0; i < psli->num_rings; i++) {
12041 			pring = &psli->sli3_ring[i];
12042 			/* Only slow rings */
12043 			if (pring->ringno == LPFC_ELS_RING) {
12044 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12045 				/* Set the lpfc data pending flag */
12046 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12047 			}
12048 			list_splice_init(&pring->txq, &completions);
12049 		}
12050 	} else {
12051 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12052 			pring = qp->pring;
12053 			if (!pring)
12054 				continue;
12055 			spin_lock(&pring->ring_lock);
12056 			list_splice_init(&pring->txq, &completions);
12057 			spin_unlock(&pring->ring_lock);
12058 			if (pring == phba->sli4_hba.els_wq->pring) {
12059 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12060 				/* Set the lpfc data pending flag */
12061 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12062 			}
12063 		}
12064 	}
12065 	spin_unlock_irqrestore(&phba->hbalock, flags);
12066 
12067 	/* Cancel all the IOCBs from the completions list */
12068 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
12069 			      IOERR_SLI_DOWN);
12070 
12071 	spin_lock_irqsave(&phba->hbalock, flags);
12072 	list_splice_init(&phba->elsbuf, &completions);
12073 	phba->elsbuf_cnt = 0;
12074 	phba->elsbuf_prev_cnt = 0;
12075 	spin_unlock_irqrestore(&phba->hbalock, flags);
12076 
12077 	while (!list_empty(&completions)) {
12078 		list_remove_head(&completions, buf_ptr,
12079 			struct lpfc_dmabuf, list);
12080 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
12081 		kfree(buf_ptr);
12082 	}
12083 
12084 	/* Enable softirqs again, done with phba->hbalock */
12085 	local_bh_enable();
12086 
12087 	/* Return any active mbox cmds */
12088 	timer_delete_sync(&psli->mbox_tmo);
12089 
12090 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
12091 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
12092 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
12093 
12094 	return 1;
12095 }
12096 
12097 /**
12098  * lpfc_sli_pcimem_bcopy - SLI memory copy function
12099  * @srcp: Source memory pointer.
12100  * @destp: Destination memory pointer.
12101  * @cnt: Number of words required to be copied.
12102  *
12103  * This function is used for copying data between driver memory
12104  * and the SLI memory. This function also changes the endianness
12105  * of each word if native endianness is different from SLI
12106  * endianness. This function can be called with or without
12107  * lock.
12108  **/
12109 void
12110 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
12111 {
12112 	uint32_t *src = srcp;
12113 	uint32_t *dest = destp;
12114 	uint32_t ldata;
12115 	int i;
12116 
12117 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
12118 		ldata = *src;
12119 		ldata = le32_to_cpu(ldata);
12120 		*dest = ldata;
12121 		src++;
12122 		dest++;
12123 	}
12124 }
12125 
12126 
12127 /**
12128  * lpfc_sli_bemem_bcopy - SLI memory copy function
12129  * @srcp: Source memory pointer.
12130  * @destp: Destination memory pointer.
12131  * @cnt: Number of words required to be copied.
12132  *
12133  * This function is used for copying data between a data structure
12134  * with big endian representation to local endianness.
12135  * This function can be called with or without lock.
12136  **/
12137 void
12138 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
12139 {
12140 	uint32_t *src = srcp;
12141 	uint32_t *dest = destp;
12142 	uint32_t ldata;
12143 	int i;
12144 
12145 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
12146 		ldata = *src;
12147 		ldata = be32_to_cpu(ldata);
12148 		*dest = ldata;
12149 		src++;
12150 		dest++;
12151 	}
12152 }
12153 
12154 /**
12155  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
12156  * @phba: Pointer to HBA context object.
12157  * @pring: Pointer to driver SLI ring object.
12158  * @mp: Pointer to driver buffer object.
12159  *
12160  * This function is called with no lock held.
12161  * It always return zero after adding the buffer to the postbufq
12162  * buffer list.
12163  **/
12164 int
12165 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12166 			 struct lpfc_dmabuf *mp)
12167 {
12168 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
12169 	   later */
12170 	spin_lock_irq(&phba->hbalock);
12171 	list_add_tail(&mp->list, &pring->postbufq);
12172 	pring->postbufq_cnt++;
12173 	spin_unlock_irq(&phba->hbalock);
12174 	return 0;
12175 }
12176 
12177 /**
12178  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
12179  * @phba: Pointer to HBA context object.
12180  *
12181  * When HBQ is enabled, buffers are searched based on tags. This function
12182  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
12183  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
12184  * does not conflict with tags of buffer posted for unsolicited events.
12185  * The function returns the allocated tag. The function is called with
12186  * no locks held.
12187  **/
12188 uint32_t
12189 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
12190 {
12191 	spin_lock_irq(&phba->hbalock);
12192 	phba->buffer_tag_count++;
12193 	/*
12194 	 * Always set the QUE_BUFTAG_BIT to distiguish between
12195 	 * a tag assigned by HBQ.
12196 	 */
12197 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
12198 	spin_unlock_irq(&phba->hbalock);
12199 	return phba->buffer_tag_count;
12200 }
12201 
12202 /**
12203  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
12204  * @phba: Pointer to HBA context object.
12205  * @pring: Pointer to driver SLI ring object.
12206  * @tag: Buffer tag.
12207  *
12208  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
12209  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
12210  * iocb is posted to the response ring with the tag of the buffer.
12211  * This function searches the pring->postbufq list using the tag
12212  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
12213  * iocb. If the buffer is found then lpfc_dmabuf object of the
12214  * buffer is returned to the caller else NULL is returned.
12215  * This function is called with no lock held.
12216  **/
12217 struct lpfc_dmabuf *
12218 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12219 			uint32_t tag)
12220 {
12221 	struct lpfc_dmabuf *mp, *next_mp;
12222 	struct list_head *slp = &pring->postbufq;
12223 
12224 	/* Search postbufq, from the beginning, looking for a match on tag */
12225 	spin_lock_irq(&phba->hbalock);
12226 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12227 		if (mp->buffer_tag == tag) {
12228 			list_del_init(&mp->list);
12229 			pring->postbufq_cnt--;
12230 			spin_unlock_irq(&phba->hbalock);
12231 			return mp;
12232 		}
12233 	}
12234 
12235 	spin_unlock_irq(&phba->hbalock);
12236 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12237 			"0402 Cannot find virtual addr for buffer tag on "
12238 			"ring %d Data x%lx x%px x%px x%x\n",
12239 			pring->ringno, (unsigned long) tag,
12240 			slp->next, slp->prev, pring->postbufq_cnt);
12241 
12242 	return NULL;
12243 }
12244 
12245 /**
12246  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
12247  * @phba: Pointer to HBA context object.
12248  * @pring: Pointer to driver SLI ring object.
12249  * @phys: DMA address of the buffer.
12250  *
12251  * This function searches the buffer list using the dma_address
12252  * of unsolicited event to find the driver's lpfc_dmabuf object
12253  * corresponding to the dma_address. The function returns the
12254  * lpfc_dmabuf object if a buffer is found else it returns NULL.
12255  * This function is called by the ct and els unsolicited event
12256  * handlers to get the buffer associated with the unsolicited
12257  * event.
12258  *
12259  * This function is called with no lock held.
12260  **/
12261 struct lpfc_dmabuf *
12262 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12263 			 dma_addr_t phys)
12264 {
12265 	struct lpfc_dmabuf *mp, *next_mp;
12266 	struct list_head *slp = &pring->postbufq;
12267 
12268 	/* Search postbufq, from the beginning, looking for a match on phys */
12269 	spin_lock_irq(&phba->hbalock);
12270 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12271 		if (mp->phys == phys) {
12272 			list_del_init(&mp->list);
12273 			pring->postbufq_cnt--;
12274 			spin_unlock_irq(&phba->hbalock);
12275 			return mp;
12276 		}
12277 	}
12278 
12279 	spin_unlock_irq(&phba->hbalock);
12280 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12281 			"0410 Cannot find virtual addr for mapped buf on "
12282 			"ring %d Data x%llx x%px x%px x%x\n",
12283 			pring->ringno, (unsigned long long)phys,
12284 			slp->next, slp->prev, pring->postbufq_cnt);
12285 	return NULL;
12286 }
12287 
12288 /**
12289  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
12290  * @phba: Pointer to HBA context object.
12291  * @cmdiocb: Pointer to driver command iocb object.
12292  * @rspiocb: Pointer to driver response iocb object.
12293  *
12294  * This function is the completion handler for the abort iocbs for
12295  * ELS commands. This function is called from the ELS ring event
12296  * handler with no lock held. This function frees memory resources
12297  * associated with the abort iocb.
12298  **/
12299 static void
12300 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12301 			struct lpfc_iocbq *rspiocb)
12302 {
12303 	u32 ulp_status = get_job_ulpstatus(phba, rspiocb);
12304 	u32 ulp_word4 = get_job_word4(phba, rspiocb);
12305 	u8 cmnd = get_job_cmnd(phba, cmdiocb);
12306 
12307 	if (ulp_status) {
12308 		/*
12309 		 * Assume that the port already completed and returned, or
12310 		 * will return the iocb. Just Log the message.
12311 		 */
12312 		if (phba->sli_rev < LPFC_SLI_REV4) {
12313 			if (cmnd == CMD_ABORT_XRI_CX &&
12314 			    ulp_status == IOSTAT_LOCAL_REJECT &&
12315 			    ulp_word4 == IOERR_ABORT_REQUESTED) {
12316 				goto release_iocb;
12317 			}
12318 		}
12319 	}
12320 
12321 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS | LOG_SLI,
12322 			"0327 Abort els iocb complete x%px with io cmd xri %x "
12323 			"abort tag x%x abort status %x abort code %x\n",
12324 			cmdiocb, get_job_abtsiotag(phba, cmdiocb),
12325 			(phba->sli_rev == LPFC_SLI_REV4) ?
12326 			get_wqe_reqtag(cmdiocb) :
12327 			cmdiocb->iocb.ulpIoTag,
12328 			ulp_status, ulp_word4);
12329 release_iocb:
12330 	lpfc_sli_release_iocbq(phba, cmdiocb);
12331 	return;
12332 }
12333 
12334 /**
12335  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
12336  * @phba: Pointer to HBA context object.
12337  * @cmdiocb: Pointer to driver command iocb object.
12338  * @rspiocb: Pointer to driver response iocb object.
12339  *
12340  * The function is called from SLI ring event handler with no
12341  * lock held. This function is the completion handler for ELS commands
12342  * which are aborted. The function frees memory resources used for
12343  * the aborted ELS commands.
12344  **/
12345 void
12346 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12347 		     struct lpfc_iocbq *rspiocb)
12348 {
12349 	struct lpfc_nodelist *ndlp = cmdiocb->ndlp;
12350 	IOCB_t *irsp;
12351 	LPFC_MBOXQ_t *mbox;
12352 	u32 ulp_command, ulp_status, ulp_word4, iotag;
12353 
12354 	ulp_command = get_job_cmnd(phba, cmdiocb);
12355 	ulp_status = get_job_ulpstatus(phba, rspiocb);
12356 	ulp_word4 = get_job_word4(phba, rspiocb);
12357 
12358 	if (phba->sli_rev == LPFC_SLI_REV4) {
12359 		iotag = get_wqe_reqtag(cmdiocb);
12360 	} else {
12361 		irsp = &rspiocb->iocb;
12362 		iotag = irsp->ulpIoTag;
12363 
12364 		/* It is possible a PLOGI_RJT for NPIV ports to get aborted.
12365 		 * The MBX_REG_LOGIN64 mbox command is freed back to the
12366 		 * mbox_mem_pool here.
12367 		 */
12368 		if (cmdiocb->context_un.mbox) {
12369 			mbox = cmdiocb->context_un.mbox;
12370 			lpfc_mbox_rsrc_cleanup(phba, mbox, MBOX_THD_UNLOCKED);
12371 			cmdiocb->context_un.mbox = NULL;
12372 		}
12373 	}
12374 
12375 	/* ELS cmd tag <ulpIoTag> completes */
12376 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
12377 			"0139 Ignoring ELS cmd code x%x ref cnt x%x Data: "
12378 			"x%x x%x x%x x%px\n",
12379 			ulp_command, kref_read(&cmdiocb->ndlp->kref),
12380 			ulp_status, ulp_word4, iotag, cmdiocb->ndlp);
12381 	/*
12382 	 * Deref the ndlp after free_iocb. sli_release_iocb will access the ndlp
12383 	 * if exchange is busy.
12384 	 */
12385 	if (ulp_command == CMD_GEN_REQUEST64_CR)
12386 		lpfc_ct_free_iocb(phba, cmdiocb);
12387 	else
12388 		lpfc_els_free_iocb(phba, cmdiocb);
12389 
12390 	lpfc_nlp_put(ndlp);
12391 }
12392 
12393 /**
12394  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
12395  * @phba: Pointer to HBA context object.
12396  * @pring: Pointer to driver SLI ring object.
12397  * @cmdiocb: Pointer to driver command iocb object.
12398  * @cmpl: completion function.
12399  *
12400  * This function issues an abort iocb for the provided command iocb. In case
12401  * of unloading, the abort iocb will not be issued to commands on the ELS
12402  * ring. Instead, the callback function shall be changed to those commands
12403  * so that nothing happens when them finishes. This function is called with
12404  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
12405  * when the command iocb is an abort request.
12406  *
12407  **/
12408 int
12409 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12410 			   struct lpfc_iocbq *cmdiocb, void *cmpl)
12411 {
12412 	struct lpfc_vport *vport = cmdiocb->vport;
12413 	struct lpfc_iocbq *abtsiocbp;
12414 	int retval = IOCB_ERROR;
12415 	unsigned long iflags;
12416 	struct lpfc_nodelist *ndlp = NULL;
12417 	u32 ulp_command = get_job_cmnd(phba, cmdiocb);
12418 	u16 ulp_context, iotag;
12419 	bool ia;
12420 
12421 	/*
12422 	 * There are certain command types we don't want to abort.  And we
12423 	 * don't want to abort commands that are already in the process of
12424 	 * being aborted.
12425 	 */
12426 	if (ulp_command == CMD_ABORT_XRI_WQE ||
12427 	    ulp_command == CMD_ABORT_XRI_CN ||
12428 	    ulp_command == CMD_CLOSE_XRI_CN ||
12429 	    cmdiocb->cmd_flag & LPFC_DRIVER_ABORTED)
12430 		return IOCB_ABORTING;
12431 
12432 	if (!pring) {
12433 		if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12434 			cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12435 		else
12436 			cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12437 		return retval;
12438 	}
12439 
12440 	/*
12441 	 * Always abort the outstanding WQE and set the IA bit correctly
12442 	 * for the context.  This is necessary for correctly removing
12443 	 * outstanding ndlp reference counts when the CQE completes with
12444 	 * the XB bit set.
12445 	 */
12446 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
12447 	if (abtsiocbp == NULL)
12448 		return IOCB_NORESOURCE;
12449 
12450 	/* This signals the response to set the correct status
12451 	 * before calling the completion handler
12452 	 */
12453 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
12454 
12455 	if (phba->sli_rev == LPFC_SLI_REV4) {
12456 		ulp_context = cmdiocb->sli4_xritag;
12457 		iotag = abtsiocbp->iotag;
12458 	} else {
12459 		iotag = cmdiocb->iocb.ulpIoTag;
12460 		if (pring->ringno == LPFC_ELS_RING) {
12461 			ndlp = cmdiocb->ndlp;
12462 			ulp_context = ndlp->nlp_rpi;
12463 		} else {
12464 			ulp_context = cmdiocb->iocb.ulpContext;
12465 		}
12466 	}
12467 
12468 	/* Just close the exchange under certain conditions. */
12469 	if (test_bit(FC_UNLOADING, &vport->load_flag) ||
12470 	    phba->link_state < LPFC_LINK_UP ||
12471 	    (phba->sli_rev == LPFC_SLI_REV4 &&
12472 	     phba->sli4_hba.link_state.status == LPFC_FC_LA_TYPE_LINK_DOWN) ||
12473 	    (phba->link_flag & LS_EXTERNAL_LOOPBACK))
12474 		ia = true;
12475 	else
12476 		ia = false;
12477 
12478 	lpfc_sli_prep_abort_xri(phba, abtsiocbp, ulp_context, iotag,
12479 				cmdiocb->iocb.ulpClass,
12480 				LPFC_WQE_CQ_ID_DEFAULT, ia, false);
12481 
12482 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12483 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
12484 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
12485 		abtsiocbp->cmd_flag |= (LPFC_IO_FCP | LPFC_USE_FCPWQIDX);
12486 
12487 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
12488 		abtsiocbp->cmd_flag |= LPFC_IO_FOF;
12489 
12490 	if (cmpl)
12491 		abtsiocbp->cmd_cmpl = cmpl;
12492 	else
12493 		abtsiocbp->cmd_cmpl = lpfc_sli_abort_els_cmpl;
12494 	abtsiocbp->vport = vport;
12495 
12496 	if (phba->sli_rev == LPFC_SLI_REV4) {
12497 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
12498 		if (unlikely(pring == NULL))
12499 			goto abort_iotag_exit;
12500 		/* Note: both hbalock and ring_lock need to be set here */
12501 		spin_lock_irqsave(&pring->ring_lock, iflags);
12502 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12503 			abtsiocbp, 0);
12504 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
12505 	} else {
12506 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12507 			abtsiocbp, 0);
12508 	}
12509 
12510 abort_iotag_exit:
12511 
12512 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
12513 			 "0339 Abort IO XRI x%x, Original iotag x%x, "
12514 			 "abort tag x%x Cmdjob : x%px Abortjob : x%px "
12515 			 "retval x%x : IA %d cmd_cmpl %ps\n",
12516 			 ulp_context, (phba->sli_rev == LPFC_SLI_REV4) ?
12517 			 cmdiocb->iotag : iotag, iotag, cmdiocb, abtsiocbp,
12518 			 retval, ia, abtsiocbp->cmd_cmpl);
12519 	if (retval) {
12520 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
12521 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
12522 	}
12523 
12524 	/*
12525 	 * Caller to this routine should check for IOCB_ERROR
12526 	 * and handle it properly.  This routine no longer removes
12527 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
12528 	 */
12529 	return retval;
12530 }
12531 
12532 /**
12533  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
12534  * @phba: pointer to lpfc HBA data structure.
12535  *
12536  * This routine will abort all pending and outstanding iocbs to an HBA.
12537  **/
12538 void
12539 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
12540 {
12541 	struct lpfc_sli *psli = &phba->sli;
12542 	struct lpfc_sli_ring *pring;
12543 	struct lpfc_queue *qp = NULL;
12544 	int i;
12545 
12546 	if (phba->sli_rev != LPFC_SLI_REV4) {
12547 		for (i = 0; i < psli->num_rings; i++) {
12548 			pring = &psli->sli3_ring[i];
12549 			lpfc_sli_abort_iocb_ring(phba, pring);
12550 		}
12551 		return;
12552 	}
12553 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12554 		pring = qp->pring;
12555 		if (!pring)
12556 			continue;
12557 		lpfc_sli_abort_iocb_ring(phba, pring);
12558 	}
12559 }
12560 
12561 /**
12562  * lpfc_sli_validate_fcp_iocb_for_abort - filter iocbs appropriate for FCP aborts
12563  * @iocbq: Pointer to iocb object.
12564  * @vport: Pointer to driver virtual port object.
12565  *
12566  * This function acts as an iocb filter for functions which abort FCP iocbs.
12567  *
12568  * Return values
12569  * -ENODEV, if a null iocb or vport ptr is encountered
12570  * -EINVAL, if the iocb is not an FCP I/O, not on the TX cmpl queue, premarked as
12571  *          driver already started the abort process, or is an abort iocb itself
12572  * 0, passes criteria for aborting the FCP I/O iocb
12573  **/
12574 static int
12575 lpfc_sli_validate_fcp_iocb_for_abort(struct lpfc_iocbq *iocbq,
12576 				     struct lpfc_vport *vport)
12577 {
12578 	u8 ulp_command;
12579 
12580 	/* No null ptr vports */
12581 	if (!iocbq || iocbq->vport != vport)
12582 		return -ENODEV;
12583 
12584 	/* iocb must be for FCP IO, already exists on the TX cmpl queue,
12585 	 * can't be premarked as driver aborted, nor be an ABORT iocb itself
12586 	 */
12587 	ulp_command = get_job_cmnd(vport->phba, iocbq);
12588 	if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12589 	    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ) ||
12590 	    (iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12591 	    (ulp_command == CMD_ABORT_XRI_CN ||
12592 	     ulp_command == CMD_CLOSE_XRI_CN ||
12593 	     ulp_command == CMD_ABORT_XRI_WQE))
12594 		return -EINVAL;
12595 
12596 	return 0;
12597 }
12598 
12599 /**
12600  * lpfc_sli_validate_fcp_iocb - validate commands associated with a SCSI target
12601  * @iocbq: Pointer to driver iocb object.
12602  * @vport: Pointer to driver virtual port object.
12603  * @tgt_id: SCSI ID of the target.
12604  * @lun_id: LUN ID of the scsi device.
12605  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
12606  *
12607  * This function acts as an iocb filter for validating a lun/SCSI target/SCSI
12608  * host.
12609  *
12610  * It will return
12611  * 0 if the filtering criteria is met for the given iocb and will return
12612  * 1 if the filtering criteria is not met.
12613  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
12614  * given iocb is for the SCSI device specified by vport, tgt_id and
12615  * lun_id parameter.
12616  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
12617  * given iocb is for the SCSI target specified by vport and tgt_id
12618  * parameters.
12619  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
12620  * given iocb is for the SCSI host associated with the given vport.
12621  * This function is called with no locks held.
12622  **/
12623 static int
12624 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
12625 			   uint16_t tgt_id, uint64_t lun_id,
12626 			   lpfc_ctx_cmd ctx_cmd)
12627 {
12628 	struct lpfc_io_buf *lpfc_cmd;
12629 	int rc = 1;
12630 
12631 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12632 
12633 	if (lpfc_cmd->pCmd == NULL)
12634 		return rc;
12635 
12636 	switch (ctx_cmd) {
12637 	case LPFC_CTX_LUN:
12638 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12639 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
12640 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
12641 			rc = 0;
12642 		break;
12643 	case LPFC_CTX_TGT:
12644 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12645 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
12646 			rc = 0;
12647 		break;
12648 	case LPFC_CTX_HOST:
12649 		rc = 0;
12650 		break;
12651 	default:
12652 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
12653 			__func__, ctx_cmd);
12654 		break;
12655 	}
12656 
12657 	return rc;
12658 }
12659 
12660 /**
12661  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
12662  * @vport: Pointer to virtual port.
12663  * @tgt_id: SCSI ID of the target.
12664  * @lun_id: LUN ID of the scsi device.
12665  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12666  *
12667  * This function returns number of FCP commands pending for the vport.
12668  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
12669  * commands pending on the vport associated with SCSI device specified
12670  * by tgt_id and lun_id parameters.
12671  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
12672  * commands pending on the vport associated with SCSI target specified
12673  * by tgt_id parameter.
12674  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
12675  * commands pending on the vport.
12676  * This function returns the number of iocbs which satisfy the filter.
12677  * This function is called without any lock held.
12678  **/
12679 int
12680 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
12681 		  lpfc_ctx_cmd ctx_cmd)
12682 {
12683 	struct lpfc_hba *phba = vport->phba;
12684 	struct lpfc_iocbq *iocbq;
12685 	int sum, i;
12686 	unsigned long iflags;
12687 	u8 ulp_command;
12688 
12689 	spin_lock_irqsave(&phba->hbalock, iflags);
12690 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
12691 		iocbq = phba->sli.iocbq_lookup[i];
12692 
12693 		if (!iocbq || iocbq->vport != vport)
12694 			continue;
12695 		if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12696 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ))
12697 			continue;
12698 
12699 		/* Include counting outstanding aborts */
12700 		ulp_command = get_job_cmnd(phba, iocbq);
12701 		if (ulp_command == CMD_ABORT_XRI_CN ||
12702 		    ulp_command == CMD_CLOSE_XRI_CN ||
12703 		    ulp_command == CMD_ABORT_XRI_WQE) {
12704 			sum++;
12705 			continue;
12706 		}
12707 
12708 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12709 					       ctx_cmd) == 0)
12710 			sum++;
12711 	}
12712 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12713 
12714 	return sum;
12715 }
12716 
12717 /**
12718  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
12719  * @phba: Pointer to HBA context object
12720  * @cmdiocb: Pointer to command iocb object.
12721  * @rspiocb: Pointer to response iocb object.
12722  *
12723  * This function is called when an aborted FCP iocb completes. This
12724  * function is called by the ring event handler with no lock held.
12725  * This function frees the iocb.
12726  **/
12727 void
12728 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12729 			struct lpfc_iocbq *rspiocb)
12730 {
12731 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12732 			"3096 ABORT_XRI_CX completing on rpi x%x "
12733 			"original iotag x%x, abort cmd iotag x%x "
12734 			"status 0x%x, reason 0x%x\n",
12735 			(phba->sli_rev == LPFC_SLI_REV4) ?
12736 			cmdiocb->sli4_xritag :
12737 			cmdiocb->iocb.un.acxri.abortContextTag,
12738 			get_job_abtsiotag(phba, cmdiocb),
12739 			cmdiocb->iotag, get_job_ulpstatus(phba, rspiocb),
12740 			get_job_word4(phba, rspiocb));
12741 	lpfc_sli_release_iocbq(phba, cmdiocb);
12742 	return;
12743 }
12744 
12745 /**
12746  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
12747  * @vport: Pointer to virtual port.
12748  * @tgt_id: SCSI ID of the target.
12749  * @lun_id: LUN ID of the scsi device.
12750  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12751  *
12752  * This function sends an abort command for every SCSI command
12753  * associated with the given virtual port pending on the ring
12754  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12755  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12756  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12757  * followed by lpfc_sli_validate_fcp_iocb.
12758  *
12759  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
12760  * FCP iocbs associated with lun specified by tgt_id and lun_id
12761  * parameters
12762  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
12763  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12764  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
12765  * FCP iocbs associated with virtual port.
12766  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
12767  * lpfc_sli4_calc_ring is used.
12768  * This function returns number of iocbs it failed to abort.
12769  * This function is called with no locks held.
12770  **/
12771 int
12772 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
12773 		    lpfc_ctx_cmd abort_cmd)
12774 {
12775 	struct lpfc_hba *phba = vport->phba;
12776 	struct lpfc_sli_ring *pring = NULL;
12777 	struct lpfc_iocbq *iocbq;
12778 	int errcnt = 0, ret_val = 0;
12779 	unsigned long iflags;
12780 	int i;
12781 
12782 	/* all I/Os are in process of being flushed */
12783 	if (test_bit(HBA_IOQ_FLUSH, &phba->hba_flag))
12784 		return errcnt;
12785 
12786 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12787 		iocbq = phba->sli.iocbq_lookup[i];
12788 
12789 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12790 			continue;
12791 
12792 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12793 					       abort_cmd) != 0)
12794 			continue;
12795 
12796 		spin_lock_irqsave(&phba->hbalock, iflags);
12797 		if (phba->sli_rev == LPFC_SLI_REV3) {
12798 			pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12799 		} else if (phba->sli_rev == LPFC_SLI_REV4) {
12800 			pring = lpfc_sli4_calc_ring(phba, iocbq);
12801 		}
12802 		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
12803 						     lpfc_sli_abort_fcp_cmpl);
12804 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12805 		if (ret_val != IOCB_SUCCESS)
12806 			errcnt++;
12807 	}
12808 
12809 	return errcnt;
12810 }
12811 
12812 /**
12813  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12814  * @vport: Pointer to virtual port.
12815  * @pring: Pointer to driver SLI ring object.
12816  * @tgt_id: SCSI ID of the target.
12817  * @lun_id: LUN ID of the scsi device.
12818  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12819  *
12820  * This function sends an abort command for every SCSI command
12821  * associated with the given virtual port pending on the ring
12822  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12823  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12824  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12825  * followed by lpfc_sli_validate_fcp_iocb.
12826  *
12827  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12828  * FCP iocbs associated with lun specified by tgt_id and lun_id
12829  * parameters
12830  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12831  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12832  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12833  * FCP iocbs associated with virtual port.
12834  * This function returns number of iocbs it aborted .
12835  * This function is called with no locks held right after a taskmgmt
12836  * command is sent.
12837  **/
12838 int
12839 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12840 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12841 {
12842 	struct lpfc_hba *phba = vport->phba;
12843 	struct lpfc_io_buf *lpfc_cmd;
12844 	struct lpfc_iocbq *abtsiocbq;
12845 	struct lpfc_nodelist *ndlp = NULL;
12846 	struct lpfc_iocbq *iocbq;
12847 	int sum, i, ret_val;
12848 	unsigned long iflags;
12849 	struct lpfc_sli_ring *pring_s4 = NULL;
12850 	u16 ulp_context, iotag, cqid = LPFC_WQE_CQ_ID_DEFAULT;
12851 	bool ia;
12852 
12853 	/* all I/Os are in process of being flushed */
12854 	if (test_bit(HBA_IOQ_FLUSH, &phba->hba_flag))
12855 		return 0;
12856 
12857 	sum = 0;
12858 
12859 	spin_lock_irqsave(&phba->hbalock, iflags);
12860 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12861 		iocbq = phba->sli.iocbq_lookup[i];
12862 
12863 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12864 			continue;
12865 
12866 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12867 					       cmd) != 0)
12868 			continue;
12869 
12870 		/* Guard against IO completion being called at same time */
12871 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12872 		spin_lock(&lpfc_cmd->buf_lock);
12873 
12874 		if (!lpfc_cmd->pCmd) {
12875 			spin_unlock(&lpfc_cmd->buf_lock);
12876 			continue;
12877 		}
12878 
12879 		if (phba->sli_rev == LPFC_SLI_REV4) {
12880 			pring_s4 =
12881 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12882 			if (!pring_s4) {
12883 				spin_unlock(&lpfc_cmd->buf_lock);
12884 				continue;
12885 			}
12886 			/* Note: both hbalock and ring_lock must be set here */
12887 			spin_lock(&pring_s4->ring_lock);
12888 		}
12889 
12890 		/*
12891 		 * If the iocbq is already being aborted, don't take a second
12892 		 * action, but do count it.
12893 		 */
12894 		if ((iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12895 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ)) {
12896 			if (phba->sli_rev == LPFC_SLI_REV4)
12897 				spin_unlock(&pring_s4->ring_lock);
12898 			spin_unlock(&lpfc_cmd->buf_lock);
12899 			continue;
12900 		}
12901 
12902 		/* issue ABTS for this IOCB based on iotag */
12903 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
12904 		if (!abtsiocbq) {
12905 			if (phba->sli_rev == LPFC_SLI_REV4)
12906 				spin_unlock(&pring_s4->ring_lock);
12907 			spin_unlock(&lpfc_cmd->buf_lock);
12908 			continue;
12909 		}
12910 
12911 		if (phba->sli_rev == LPFC_SLI_REV4) {
12912 			iotag = abtsiocbq->iotag;
12913 			ulp_context = iocbq->sli4_xritag;
12914 			cqid = lpfc_cmd->hdwq->io_cq_map;
12915 		} else {
12916 			iotag = iocbq->iocb.ulpIoTag;
12917 			if (pring->ringno == LPFC_ELS_RING) {
12918 				ndlp = iocbq->ndlp;
12919 				ulp_context = ndlp->nlp_rpi;
12920 			} else {
12921 				ulp_context = iocbq->iocb.ulpContext;
12922 			}
12923 		}
12924 
12925 		ndlp = lpfc_cmd->rdata->pnode;
12926 
12927 		if (lpfc_is_link_up(phba) &&
12928 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE) &&
12929 		    !(phba->link_flag & LS_EXTERNAL_LOOPBACK))
12930 			ia = false;
12931 		else
12932 			ia = true;
12933 
12934 		lpfc_sli_prep_abort_xri(phba, abtsiocbq, ulp_context, iotag,
12935 					iocbq->iocb.ulpClass, cqid,
12936 					ia, false);
12937 
12938 		abtsiocbq->vport = vport;
12939 
12940 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12941 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12942 		if (iocbq->cmd_flag & LPFC_IO_FCP)
12943 			abtsiocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
12944 		if (iocbq->cmd_flag & LPFC_IO_FOF)
12945 			abtsiocbq->cmd_flag |= LPFC_IO_FOF;
12946 
12947 		/* Setup callback routine and issue the command. */
12948 		abtsiocbq->cmd_cmpl = lpfc_sli_abort_fcp_cmpl;
12949 
12950 		/*
12951 		 * Indicate the IO is being aborted by the driver and set
12952 		 * the caller's flag into the aborted IO.
12953 		 */
12954 		iocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
12955 
12956 		if (phba->sli_rev == LPFC_SLI_REV4) {
12957 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
12958 							abtsiocbq, 0);
12959 			spin_unlock(&pring_s4->ring_lock);
12960 		} else {
12961 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
12962 							abtsiocbq, 0);
12963 		}
12964 
12965 		spin_unlock(&lpfc_cmd->buf_lock);
12966 
12967 		if (ret_val == IOCB_ERROR)
12968 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
12969 		else
12970 			sum++;
12971 	}
12972 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12973 	return sum;
12974 }
12975 
12976 /**
12977  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
12978  * @phba: Pointer to HBA context object.
12979  * @cmdiocbq: Pointer to command iocb.
12980  * @rspiocbq: Pointer to response iocb.
12981  *
12982  * This function is the completion handler for iocbs issued using
12983  * lpfc_sli_issue_iocb_wait function. This function is called by the
12984  * ring event handler function without any lock held. This function
12985  * can be called from both worker thread context and interrupt
12986  * context. This function also can be called from other thread which
12987  * cleans up the SLI layer objects.
12988  * This function copy the contents of the response iocb to the
12989  * response iocb memory object provided by the caller of
12990  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
12991  * sleeps for the iocb completion.
12992  **/
12993 static void
12994 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
12995 			struct lpfc_iocbq *cmdiocbq,
12996 			struct lpfc_iocbq *rspiocbq)
12997 {
12998 	wait_queue_head_t *pdone_q;
12999 	unsigned long iflags;
13000 	struct lpfc_io_buf *lpfc_cmd;
13001 	size_t offset = offsetof(struct lpfc_iocbq, wqe);
13002 
13003 	spin_lock_irqsave(&phba->hbalock, iflags);
13004 	if (cmdiocbq->cmd_flag & LPFC_IO_WAKE_TMO) {
13005 
13006 		/*
13007 		 * A time out has occurred for the iocb.  If a time out
13008 		 * completion handler has been supplied, call it.  Otherwise,
13009 		 * just free the iocbq.
13010 		 */
13011 
13012 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13013 		cmdiocbq->cmd_cmpl = cmdiocbq->wait_cmd_cmpl;
13014 		cmdiocbq->wait_cmd_cmpl = NULL;
13015 		if (cmdiocbq->cmd_cmpl)
13016 			cmdiocbq->cmd_cmpl(phba, cmdiocbq, NULL);
13017 		else
13018 			lpfc_sli_release_iocbq(phba, cmdiocbq);
13019 		return;
13020 	}
13021 
13022 	/* Copy the contents of the local rspiocb into the caller's buffer. */
13023 	cmdiocbq->cmd_flag |= LPFC_IO_WAKE;
13024 	if (cmdiocbq->rsp_iocb && rspiocbq)
13025 		memcpy((char *)cmdiocbq->rsp_iocb + offset,
13026 		       (char *)rspiocbq + offset, sizeof(*rspiocbq) - offset);
13027 
13028 	/* Set the exchange busy flag for task management commands */
13029 	if ((cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
13030 	    !(cmdiocbq->cmd_flag & LPFC_IO_LIBDFC)) {
13031 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
13032 					cur_iocbq);
13033 		if (rspiocbq && (rspiocbq->cmd_flag & LPFC_EXCHANGE_BUSY))
13034 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
13035 		else
13036 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
13037 	}
13038 
13039 	pdone_q = cmdiocbq->context_un.wait_queue;
13040 	if (pdone_q)
13041 		wake_up(pdone_q);
13042 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13043 	return;
13044 }
13045 
13046 /**
13047  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
13048  * @phba: Pointer to HBA context object..
13049  * @piocbq: Pointer to command iocb.
13050  * @flag: Flag to test.
13051  *
13052  * This routine grabs the hbalock and then test the cmd_flag to
13053  * see if the passed in flag is set.
13054  * Returns:
13055  * 1 if flag is set.
13056  * 0 if flag is not set.
13057  **/
13058 static int
13059 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
13060 		 struct lpfc_iocbq *piocbq, uint32_t flag)
13061 {
13062 	unsigned long iflags;
13063 	int ret;
13064 
13065 	spin_lock_irqsave(&phba->hbalock, iflags);
13066 	ret = piocbq->cmd_flag & flag;
13067 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13068 	return ret;
13069 
13070 }
13071 
13072 /**
13073  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
13074  * @phba: Pointer to HBA context object..
13075  * @ring_number: Ring number
13076  * @piocb: Pointer to command iocb.
13077  * @prspiocbq: Pointer to response iocb.
13078  * @timeout: Timeout in number of seconds.
13079  *
13080  * This function issues the iocb to firmware and waits for the
13081  * iocb to complete. The cmd_cmpl field of the shall be used
13082  * to handle iocbs which time out. If the field is NULL, the
13083  * function shall free the iocbq structure.  If more clean up is
13084  * needed, the caller is expected to provide a completion function
13085  * that will provide the needed clean up.  If the iocb command is
13086  * not completed within timeout seconds, the function will either
13087  * free the iocbq structure (if cmd_cmpl == NULL) or execute the
13088  * completion function set in the cmd_cmpl field and then return
13089  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
13090  * resources if this function returns IOCB_TIMEDOUT.
13091  * The function waits for the iocb completion using an
13092  * non-interruptible wait.
13093  * This function will sleep while waiting for iocb completion.
13094  * So, this function should not be called from any context which
13095  * does not allow sleeping. Due to the same reason, this function
13096  * cannot be called with interrupt disabled.
13097  * This function assumes that the iocb completions occur while
13098  * this function sleep. So, this function cannot be called from
13099  * the thread which process iocb completion for this ring.
13100  * This function clears the cmd_flag of the iocb object before
13101  * issuing the iocb and the iocb completion handler sets this
13102  * flag and wakes this thread when the iocb completes.
13103  * The contents of the response iocb will be copied to prspiocbq
13104  * by the completion handler when the command completes.
13105  * This function returns IOCB_SUCCESS when success.
13106  * This function is called with no lock held.
13107  **/
13108 int
13109 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
13110 			 uint32_t ring_number,
13111 			 struct lpfc_iocbq *piocb,
13112 			 struct lpfc_iocbq *prspiocbq,
13113 			 uint32_t timeout)
13114 {
13115 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
13116 	long timeleft, timeout_req = 0;
13117 	int retval = IOCB_SUCCESS;
13118 	uint32_t creg_val;
13119 	struct lpfc_iocbq *iocb;
13120 	int txq_cnt = 0;
13121 	int txcmplq_cnt = 0;
13122 	struct lpfc_sli_ring *pring;
13123 	unsigned long iflags;
13124 	bool iocb_completed = true;
13125 
13126 	if (phba->sli_rev >= LPFC_SLI_REV4) {
13127 		lpfc_sli_prep_wqe(phba, piocb);
13128 
13129 		pring = lpfc_sli4_calc_ring(phba, piocb);
13130 	} else
13131 		pring = &phba->sli.sli3_ring[ring_number];
13132 	/*
13133 	 * If the caller has provided a response iocbq buffer, then rsp_iocb
13134 	 * is NULL or its an error.
13135 	 */
13136 	if (prspiocbq) {
13137 		if (piocb->rsp_iocb)
13138 			return IOCB_ERROR;
13139 		piocb->rsp_iocb = prspiocbq;
13140 	}
13141 
13142 	piocb->wait_cmd_cmpl = piocb->cmd_cmpl;
13143 	piocb->cmd_cmpl = lpfc_sli_wake_iocb_wait;
13144 	piocb->context_un.wait_queue = &done_q;
13145 	piocb->cmd_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
13146 
13147 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13148 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13149 			return IOCB_ERROR;
13150 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
13151 		writel(creg_val, phba->HCregaddr);
13152 		readl(phba->HCregaddr); /* flush */
13153 	}
13154 
13155 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
13156 				     SLI_IOCB_RET_IOCB);
13157 	if (retval == IOCB_SUCCESS) {
13158 		timeout_req = secs_to_jiffies(timeout);
13159 		timeleft = wait_event_timeout(done_q,
13160 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
13161 				timeout_req);
13162 		spin_lock_irqsave(&phba->hbalock, iflags);
13163 		if (!(piocb->cmd_flag & LPFC_IO_WAKE)) {
13164 
13165 			/*
13166 			 * IOCB timed out.  Inform the wake iocb wait
13167 			 * completion function and set local status
13168 			 */
13169 
13170 			iocb_completed = false;
13171 			piocb->cmd_flag |= LPFC_IO_WAKE_TMO;
13172 		}
13173 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13174 		if (iocb_completed) {
13175 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13176 					"0331 IOCB wake signaled\n");
13177 			/* Note: we are not indicating if the IOCB has a success
13178 			 * status or not - that's for the caller to check.
13179 			 * IOCB_SUCCESS means just that the command was sent and
13180 			 * completed. Not that it completed successfully.
13181 			 * */
13182 		} else if (timeleft == 0) {
13183 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13184 					"0338 IOCB wait timeout error - no "
13185 					"wake response Data x%x\n", timeout);
13186 			retval = IOCB_TIMEDOUT;
13187 		} else {
13188 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13189 					"0330 IOCB wake NOT set, "
13190 					"Data x%x x%lx\n",
13191 					timeout, (timeleft / jiffies));
13192 			retval = IOCB_TIMEDOUT;
13193 		}
13194 	} else if (retval == IOCB_BUSY) {
13195 		if (phba->cfg_log_verbose & LOG_SLI) {
13196 			list_for_each_entry(iocb, &pring->txq, list) {
13197 				txq_cnt++;
13198 			}
13199 			list_for_each_entry(iocb, &pring->txcmplq, list) {
13200 				txcmplq_cnt++;
13201 			}
13202 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13203 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
13204 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
13205 		}
13206 		return retval;
13207 	} else {
13208 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13209 				"0332 IOCB wait issue failed, Data x%x\n",
13210 				retval);
13211 		retval = IOCB_ERROR;
13212 	}
13213 
13214 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13215 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13216 			return IOCB_ERROR;
13217 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
13218 		writel(creg_val, phba->HCregaddr);
13219 		readl(phba->HCregaddr); /* flush */
13220 	}
13221 
13222 	if (prspiocbq)
13223 		piocb->rsp_iocb = NULL;
13224 
13225 	piocb->context_un.wait_queue = NULL;
13226 	piocb->cmd_cmpl = NULL;
13227 	return retval;
13228 }
13229 
13230 /**
13231  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
13232  * @phba: Pointer to HBA context object.
13233  * @pmboxq: Pointer to driver mailbox object.
13234  * @timeout: Timeout in number of seconds.
13235  *
13236  * This function issues the mailbox to firmware and waits for the
13237  * mailbox command to complete. If the mailbox command is not
13238  * completed within timeout seconds, it returns MBX_TIMEOUT.
13239  * The function waits for the mailbox completion using an
13240  * interruptible wait. If the thread is woken up due to a
13241  * signal, MBX_TIMEOUT error is returned to the caller. Caller
13242  * should not free the mailbox resources, if this function returns
13243  * MBX_TIMEOUT.
13244  * This function will sleep while waiting for mailbox completion.
13245  * So, this function should not be called from any context which
13246  * does not allow sleeping. Due to the same reason, this function
13247  * cannot be called with interrupt disabled.
13248  * This function assumes that the mailbox completion occurs while
13249  * this function sleep. So, this function cannot be called from
13250  * the worker thread which processes mailbox completion.
13251  * This function is called in the context of HBA management
13252  * applications.
13253  * This function returns MBX_SUCCESS when successful.
13254  * This function is called with no lock held.
13255  **/
13256 int
13257 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
13258 			 uint32_t timeout)
13259 {
13260 	struct completion mbox_done;
13261 	int retval;
13262 	unsigned long flag;
13263 
13264 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
13265 	/* setup wake call as IOCB callback */
13266 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
13267 
13268 	/* setup ctx_u field to pass wait_queue pointer to wake function  */
13269 	init_completion(&mbox_done);
13270 	pmboxq->ctx_u.mbox_wait = &mbox_done;
13271 	/* now issue the command */
13272 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
13273 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
13274 		wait_for_completion_timeout(&mbox_done, secs_to_jiffies(timeout));
13275 
13276 		spin_lock_irqsave(&phba->hbalock, flag);
13277 		pmboxq->ctx_u.mbox_wait = NULL;
13278 		/*
13279 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
13280 		 * else do not free the resources.
13281 		 */
13282 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
13283 			retval = MBX_SUCCESS;
13284 		} else {
13285 			retval = MBX_TIMEOUT;
13286 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13287 		}
13288 		spin_unlock_irqrestore(&phba->hbalock, flag);
13289 	}
13290 	return retval;
13291 }
13292 
13293 /**
13294  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
13295  * @phba: Pointer to HBA context.
13296  * @mbx_action: Mailbox shutdown options.
13297  *
13298  * This function is called to shutdown the driver's mailbox sub-system.
13299  * It first marks the mailbox sub-system is in a block state to prevent
13300  * the asynchronous mailbox command from issued off the pending mailbox
13301  * command queue. If the mailbox command sub-system shutdown is due to
13302  * HBA error conditions such as EEH or ERATT, this routine shall invoke
13303  * the mailbox sub-system flush routine to forcefully bring down the
13304  * mailbox sub-system. Otherwise, if it is due to normal condition (such
13305  * as with offline or HBA function reset), this routine will wait for the
13306  * outstanding mailbox command to complete before invoking the mailbox
13307  * sub-system flush routine to gracefully bring down mailbox sub-system.
13308  **/
13309 void
13310 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
13311 {
13312 	struct lpfc_sli *psli = &phba->sli;
13313 	unsigned long timeout;
13314 
13315 	if (mbx_action == LPFC_MBX_NO_WAIT) {
13316 		/* delay 100ms for port state */
13317 		msleep(100);
13318 		lpfc_sli_mbox_sys_flush(phba);
13319 		return;
13320 	}
13321 	timeout = secs_to_jiffies(LPFC_MBOX_TMO) + jiffies;
13322 
13323 	/* Disable softirqs, including timers from obtaining phba->hbalock */
13324 	local_bh_disable();
13325 
13326 	spin_lock_irq(&phba->hbalock);
13327 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13328 
13329 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
13330 		/* Determine how long we might wait for the active mailbox
13331 		 * command to be gracefully completed by firmware.
13332 		 */
13333 		if (phba->sli.mbox_active)
13334 			timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba,
13335 						phba->sli.mbox_active)) + jiffies;
13336 		spin_unlock_irq(&phba->hbalock);
13337 
13338 		/* Enable softirqs again, done with phba->hbalock */
13339 		local_bh_enable();
13340 
13341 		while (phba->sli.mbox_active) {
13342 			/* Check active mailbox complete status every 2ms */
13343 			msleep(2);
13344 			if (time_after(jiffies, timeout))
13345 				/* Timeout, let the mailbox flush routine to
13346 				 * forcefully release active mailbox command
13347 				 */
13348 				break;
13349 		}
13350 	} else {
13351 		spin_unlock_irq(&phba->hbalock);
13352 
13353 		/* Enable softirqs again, done with phba->hbalock */
13354 		local_bh_enable();
13355 	}
13356 
13357 	lpfc_sli_mbox_sys_flush(phba);
13358 }
13359 
13360 /**
13361  * lpfc_sli_eratt_read - read sli-3 error attention events
13362  * @phba: Pointer to HBA context.
13363  *
13364  * This function is called to read the SLI3 device error attention registers
13365  * for possible error attention events. The caller must hold the hostlock
13366  * with spin_lock_irq().
13367  *
13368  * This function returns 1 when there is Error Attention in the Host Attention
13369  * Register and returns 0 otherwise.
13370  **/
13371 static int
13372 lpfc_sli_eratt_read(struct lpfc_hba *phba)
13373 {
13374 	uint32_t ha_copy;
13375 
13376 	/* Read chip Host Attention (HA) register */
13377 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
13378 		goto unplug_err;
13379 
13380 	if (ha_copy & HA_ERATT) {
13381 		/* Read host status register to retrieve error event */
13382 		if (lpfc_sli_read_hs(phba))
13383 			goto unplug_err;
13384 
13385 		/* Check if there is a deferred error condition is active */
13386 		if ((HS_FFER1 & phba->work_hs) &&
13387 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13388 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
13389 			set_bit(DEFER_ERATT, &phba->hba_flag);
13390 			/* Clear all interrupt enable conditions */
13391 			writel(0, phba->HCregaddr);
13392 			readl(phba->HCregaddr);
13393 		}
13394 
13395 		/* Set the driver HA work bitmap */
13396 		phba->work_ha |= HA_ERATT;
13397 		/* Indicate polling handles this ERATT */
13398 		set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13399 		return 1;
13400 	}
13401 	return 0;
13402 
13403 unplug_err:
13404 	/* Set the driver HS work bitmap */
13405 	phba->work_hs |= UNPLUG_ERR;
13406 	/* Set the driver HA work bitmap */
13407 	phba->work_ha |= HA_ERATT;
13408 	/* Indicate polling handles this ERATT */
13409 	set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13410 	return 1;
13411 }
13412 
13413 /**
13414  * lpfc_sli4_eratt_read - read sli-4 error attention events
13415  * @phba: Pointer to HBA context.
13416  *
13417  * This function is called to read the SLI4 device error attention registers
13418  * for possible error attention events. The caller must hold the hostlock
13419  * with spin_lock_irq().
13420  *
13421  * This function returns 1 when there is Error Attention in the Host Attention
13422  * Register and returns 0 otherwise.
13423  **/
13424 static int
13425 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
13426 {
13427 	uint32_t uerr_sta_hi, uerr_sta_lo;
13428 	uint32_t if_type, portsmphr;
13429 	struct lpfc_register portstat_reg;
13430 	u32 logmask;
13431 
13432 	/*
13433 	 * For now, use the SLI4 device internal unrecoverable error
13434 	 * registers for error attention. This can be changed later.
13435 	 */
13436 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
13437 	switch (if_type) {
13438 	case LPFC_SLI_INTF_IF_TYPE_0:
13439 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
13440 			&uerr_sta_lo) ||
13441 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
13442 			&uerr_sta_hi)) {
13443 			phba->work_hs |= UNPLUG_ERR;
13444 			phba->work_ha |= HA_ERATT;
13445 			set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13446 			return 1;
13447 		}
13448 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
13449 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
13450 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13451 					"1423 HBA Unrecoverable error: "
13452 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
13453 					"ue_mask_lo_reg=0x%x, "
13454 					"ue_mask_hi_reg=0x%x\n",
13455 					uerr_sta_lo, uerr_sta_hi,
13456 					phba->sli4_hba.ue_mask_lo,
13457 					phba->sli4_hba.ue_mask_hi);
13458 			phba->work_status[0] = uerr_sta_lo;
13459 			phba->work_status[1] = uerr_sta_hi;
13460 			phba->work_ha |= HA_ERATT;
13461 			set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13462 			return 1;
13463 		}
13464 		break;
13465 	case LPFC_SLI_INTF_IF_TYPE_2:
13466 	case LPFC_SLI_INTF_IF_TYPE_6:
13467 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
13468 			&portstat_reg.word0) ||
13469 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
13470 			&portsmphr)){
13471 			phba->work_hs |= UNPLUG_ERR;
13472 			phba->work_ha |= HA_ERATT;
13473 			set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13474 			return 1;
13475 		}
13476 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
13477 			phba->work_status[0] =
13478 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
13479 			phba->work_status[1] =
13480 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
13481 			logmask = LOG_TRACE_EVENT;
13482 			if (phba->work_status[0] ==
13483 				SLIPORT_ERR1_REG_ERR_CODE_2 &&
13484 			    phba->work_status[1] == SLIPORT_ERR2_REG_FW_RESTART)
13485 				logmask = LOG_SLI;
13486 			lpfc_printf_log(phba, KERN_ERR, logmask,
13487 					"2885 Port Status Event: "
13488 					"port status reg 0x%x, "
13489 					"port smphr reg 0x%x, "
13490 					"error 1=0x%x, error 2=0x%x\n",
13491 					portstat_reg.word0,
13492 					portsmphr,
13493 					phba->work_status[0],
13494 					phba->work_status[1]);
13495 			phba->work_ha |= HA_ERATT;
13496 			set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13497 			return 1;
13498 		}
13499 		break;
13500 	case LPFC_SLI_INTF_IF_TYPE_1:
13501 	default:
13502 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13503 				"2886 HBA Error Attention on unsupported "
13504 				"if type %d.", if_type);
13505 		return 1;
13506 	}
13507 
13508 	return 0;
13509 }
13510 
13511 /**
13512  * lpfc_sli_check_eratt - check error attention events
13513  * @phba: Pointer to HBA context.
13514  *
13515  * This function is called from timer soft interrupt context to check HBA's
13516  * error attention register bit for error attention events.
13517  *
13518  * This function returns 1 when there is Error Attention in the Host Attention
13519  * Register and returns 0 otherwise.
13520  **/
13521 int
13522 lpfc_sli_check_eratt(struct lpfc_hba *phba)
13523 {
13524 	uint32_t ha_copy;
13525 
13526 	/* If somebody is waiting to handle an eratt, don't process it
13527 	 * here. The brdkill function will do this.
13528 	 */
13529 	if (phba->link_flag & LS_IGNORE_ERATT)
13530 		return 0;
13531 
13532 	/* Check if interrupt handler handles this ERATT */
13533 	if (test_bit(HBA_ERATT_HANDLED, &phba->hba_flag))
13534 		/* Interrupt handler has handled ERATT */
13535 		return 0;
13536 
13537 	/*
13538 	 * If there is deferred error attention, do not check for error
13539 	 * attention
13540 	 */
13541 	if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag)))
13542 		return 0;
13543 
13544 	spin_lock_irq(&phba->hbalock);
13545 	/* If PCI channel is offline, don't process it */
13546 	if (unlikely(pci_channel_offline(phba->pcidev))) {
13547 		spin_unlock_irq(&phba->hbalock);
13548 		return 0;
13549 	}
13550 
13551 	switch (phba->sli_rev) {
13552 	case LPFC_SLI_REV2:
13553 	case LPFC_SLI_REV3:
13554 		/* Read chip Host Attention (HA) register */
13555 		ha_copy = lpfc_sli_eratt_read(phba);
13556 		break;
13557 	case LPFC_SLI_REV4:
13558 		/* Read device Uncoverable Error (UERR) registers */
13559 		ha_copy = lpfc_sli4_eratt_read(phba);
13560 		break;
13561 	default:
13562 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13563 				"0299 Invalid SLI revision (%d)\n",
13564 				phba->sli_rev);
13565 		ha_copy = 0;
13566 		break;
13567 	}
13568 	spin_unlock_irq(&phba->hbalock);
13569 
13570 	return ha_copy;
13571 }
13572 
13573 /**
13574  * lpfc_intr_state_check - Check device state for interrupt handling
13575  * @phba: Pointer to HBA context.
13576  *
13577  * This inline routine checks whether a device or its PCI slot is in a state
13578  * that the interrupt should be handled.
13579  *
13580  * This function returns 0 if the device or the PCI slot is in a state that
13581  * interrupt should be handled, otherwise -EIO.
13582  */
13583 static inline int
13584 lpfc_intr_state_check(struct lpfc_hba *phba)
13585 {
13586 	/* If the pci channel is offline, ignore all the interrupts */
13587 	if (unlikely(pci_channel_offline(phba->pcidev)))
13588 		return -EIO;
13589 
13590 	/* Update device level interrupt statistics */
13591 	phba->sli.slistat.sli_intr++;
13592 
13593 	/* Ignore all interrupts during initialization. */
13594 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
13595 		return -EIO;
13596 
13597 	return 0;
13598 }
13599 
13600 /**
13601  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
13602  * @irq: Interrupt number.
13603  * @dev_id: The device context pointer.
13604  *
13605  * This function is directly called from the PCI layer as an interrupt
13606  * service routine when device with SLI-3 interface spec is enabled with
13607  * MSI-X multi-message interrupt mode and there are slow-path events in
13608  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
13609  * interrupt mode, this function is called as part of the device-level
13610  * interrupt handler. When the PCI slot is in error recovery or the HBA
13611  * is undergoing initialization, the interrupt handler will not process
13612  * the interrupt. The link attention and ELS ring attention events are
13613  * handled by the worker thread. The interrupt handler signals the worker
13614  * thread and returns for these events. This function is called without
13615  * any lock held. It gets the hbalock to access and update SLI data
13616  * structures.
13617  *
13618  * This function returns IRQ_HANDLED when interrupt is handled else it
13619  * returns IRQ_NONE.
13620  **/
13621 irqreturn_t
13622 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
13623 {
13624 	struct lpfc_hba  *phba;
13625 	uint32_t ha_copy, hc_copy;
13626 	uint32_t work_ha_copy;
13627 	unsigned long status;
13628 	unsigned long iflag;
13629 	uint32_t control;
13630 
13631 	MAILBOX_t *mbox, *pmbox;
13632 	struct lpfc_vport *vport;
13633 	struct lpfc_nodelist *ndlp;
13634 	struct lpfc_dmabuf *mp;
13635 	LPFC_MBOXQ_t *pmb;
13636 	int rc;
13637 
13638 	/*
13639 	 * Get the driver's phba structure from the dev_id and
13640 	 * assume the HBA is not interrupting.
13641 	 */
13642 	phba = (struct lpfc_hba *)dev_id;
13643 
13644 	if (unlikely(!phba))
13645 		return IRQ_NONE;
13646 
13647 	/*
13648 	 * Stuff needs to be attented to when this function is invoked as an
13649 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13650 	 */
13651 	if (phba->intr_type == MSIX) {
13652 		/* Check device state for handling interrupt */
13653 		if (lpfc_intr_state_check(phba))
13654 			return IRQ_NONE;
13655 		/* Need to read HA REG for slow-path events */
13656 		spin_lock_irqsave(&phba->hbalock, iflag);
13657 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13658 			goto unplug_error;
13659 		/* If somebody is waiting to handle an eratt don't process it
13660 		 * here. The brdkill function will do this.
13661 		 */
13662 		if (phba->link_flag & LS_IGNORE_ERATT)
13663 			ha_copy &= ~HA_ERATT;
13664 		/* Check the need for handling ERATT in interrupt handler */
13665 		if (ha_copy & HA_ERATT) {
13666 			if (test_and_set_bit(HBA_ERATT_HANDLED,
13667 					     &phba->hba_flag))
13668 				/* ERATT polling has handled ERATT */
13669 				ha_copy &= ~HA_ERATT;
13670 		}
13671 
13672 		/*
13673 		 * If there is deferred error attention, do not check for any
13674 		 * interrupt.
13675 		 */
13676 		if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag))) {
13677 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13678 			return IRQ_NONE;
13679 		}
13680 
13681 		/* Clear up only attention source related to slow-path */
13682 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
13683 			goto unplug_error;
13684 
13685 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
13686 			HC_LAINT_ENA | HC_ERINT_ENA),
13687 			phba->HCregaddr);
13688 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
13689 			phba->HAregaddr);
13690 		writel(hc_copy, phba->HCregaddr);
13691 		readl(phba->HAregaddr); /* flush */
13692 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13693 	} else
13694 		ha_copy = phba->ha_copy;
13695 
13696 	work_ha_copy = ha_copy & phba->work_ha_mask;
13697 
13698 	if (work_ha_copy) {
13699 		if (work_ha_copy & HA_LATT) {
13700 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
13701 				/*
13702 				 * Turn off Link Attention interrupts
13703 				 * until CLEAR_LA done
13704 				 */
13705 				spin_lock_irqsave(&phba->hbalock, iflag);
13706 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
13707 				if (lpfc_readl(phba->HCregaddr, &control))
13708 					goto unplug_error;
13709 				control &= ~HC_LAINT_ENA;
13710 				writel(control, phba->HCregaddr);
13711 				readl(phba->HCregaddr); /* flush */
13712 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13713 			}
13714 			else
13715 				work_ha_copy &= ~HA_LATT;
13716 		}
13717 
13718 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
13719 			/*
13720 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
13721 			 * the only slow ring.
13722 			 */
13723 			status = (work_ha_copy &
13724 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
13725 			status >>= (4*LPFC_ELS_RING);
13726 			if (status & HA_RXMASK) {
13727 				spin_lock_irqsave(&phba->hbalock, iflag);
13728 				if (lpfc_readl(phba->HCregaddr, &control))
13729 					goto unplug_error;
13730 
13731 				lpfc_debugfs_slow_ring_trc(phba,
13732 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
13733 				control, status,
13734 				(uint32_t)phba->sli.slistat.sli_intr);
13735 
13736 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
13737 					lpfc_debugfs_slow_ring_trc(phba,
13738 						"ISR Disable ring:"
13739 						"pwork:x%x hawork:x%x wait:x%x",
13740 						phba->work_ha, work_ha_copy,
13741 						(uint32_t)((unsigned long)
13742 						&phba->work_waitq));
13743 
13744 					control &=
13745 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
13746 					writel(control, phba->HCregaddr);
13747 					readl(phba->HCregaddr); /* flush */
13748 				}
13749 				else {
13750 					lpfc_debugfs_slow_ring_trc(phba,
13751 						"ISR slow ring:   pwork:"
13752 						"x%x hawork:x%x wait:x%x",
13753 						phba->work_ha, work_ha_copy,
13754 						(uint32_t)((unsigned long)
13755 						&phba->work_waitq));
13756 				}
13757 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13758 			}
13759 		}
13760 		spin_lock_irqsave(&phba->hbalock, iflag);
13761 		if (work_ha_copy & HA_ERATT) {
13762 			if (lpfc_sli_read_hs(phba))
13763 				goto unplug_error;
13764 			/*
13765 			 * Check if there is a deferred error condition
13766 			 * is active
13767 			 */
13768 			if ((HS_FFER1 & phba->work_hs) &&
13769 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13770 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
13771 				  phba->work_hs)) {
13772 				set_bit(DEFER_ERATT, &phba->hba_flag);
13773 				/* Clear all interrupt enable conditions */
13774 				writel(0, phba->HCregaddr);
13775 				readl(phba->HCregaddr);
13776 			}
13777 		}
13778 
13779 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
13780 			pmb = phba->sli.mbox_active;
13781 			pmbox = &pmb->u.mb;
13782 			mbox = phba->mbox;
13783 			vport = pmb->vport;
13784 
13785 			/* First check out the status word */
13786 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
13787 			if (pmbox->mbxOwner != OWN_HOST) {
13788 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13789 				/*
13790 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
13791 				 * mbxStatus <status>
13792 				 */
13793 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13794 						"(%d):0304 Stray Mailbox "
13795 						"Interrupt mbxCommand x%x "
13796 						"mbxStatus x%x\n",
13797 						(vport ? vport->vpi : 0),
13798 						pmbox->mbxCommand,
13799 						pmbox->mbxStatus);
13800 				/* clear mailbox attention bit */
13801 				work_ha_copy &= ~HA_MBATT;
13802 			} else {
13803 				phba->sli.mbox_active = NULL;
13804 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13805 				phba->last_completion_time = jiffies;
13806 				timer_delete(&phba->sli.mbox_tmo);
13807 				if (pmb->mbox_cmpl) {
13808 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
13809 							MAILBOX_CMD_SIZE);
13810 					if (pmb->out_ext_byte_len &&
13811 						pmb->ext_buf)
13812 						lpfc_sli_pcimem_bcopy(
13813 						phba->mbox_ext,
13814 						pmb->ext_buf,
13815 						pmb->out_ext_byte_len);
13816 				}
13817 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13818 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13819 
13820 					lpfc_debugfs_disc_trc(vport,
13821 						LPFC_DISC_TRC_MBOX_VPORT,
13822 						"MBOX dflt rpi: : "
13823 						"status:x%x rpi:x%x",
13824 						(uint32_t)pmbox->mbxStatus,
13825 						pmbox->un.varWords[0], 0);
13826 
13827 					if (!pmbox->mbxStatus) {
13828 						mp = pmb->ctx_buf;
13829 						ndlp = pmb->ctx_ndlp;
13830 
13831 						/* Reg_LOGIN of dflt RPI was
13832 						 * successful. new lets get
13833 						 * rid of the RPI using the
13834 						 * same mbox buffer.
13835 						 */
13836 						lpfc_unreg_login(phba,
13837 							vport->vpi,
13838 							pmbox->un.varWords[0],
13839 							pmb);
13840 						pmb->mbox_cmpl =
13841 							lpfc_mbx_cmpl_dflt_rpi;
13842 						pmb->ctx_buf = mp;
13843 						pmb->ctx_ndlp = ndlp;
13844 						pmb->vport = vport;
13845 						rc = lpfc_sli_issue_mbox(phba,
13846 								pmb,
13847 								MBX_NOWAIT);
13848 						if (rc != MBX_BUSY)
13849 							lpfc_printf_log(phba,
13850 							KERN_ERR,
13851 							LOG_TRACE_EVENT,
13852 							"0350 rc should have"
13853 							"been MBX_BUSY\n");
13854 						if (rc != MBX_NOT_FINISHED)
13855 							goto send_current_mbox;
13856 					}
13857 				}
13858 				spin_lock_irqsave(
13859 						&phba->pport->work_port_lock,
13860 						iflag);
13861 				phba->pport->work_port_events &=
13862 					~WORKER_MBOX_TMO;
13863 				spin_unlock_irqrestore(
13864 						&phba->pport->work_port_lock,
13865 						iflag);
13866 
13867 				/* Do NOT queue MBX_HEARTBEAT to the worker
13868 				 * thread for processing.
13869 				 */
13870 				if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13871 					/* Process mbox now */
13872 					phba->sli.mbox_active = NULL;
13873 					phba->sli.sli_flag &=
13874 						~LPFC_SLI_MBOX_ACTIVE;
13875 					if (pmb->mbox_cmpl)
13876 						pmb->mbox_cmpl(phba, pmb);
13877 				} else {
13878 					/* Queue to worker thread to process */
13879 					lpfc_mbox_cmpl_put(phba, pmb);
13880 				}
13881 			}
13882 		} else
13883 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13884 
13885 		if ((work_ha_copy & HA_MBATT) &&
13886 		    (phba->sli.mbox_active == NULL)) {
13887 send_current_mbox:
13888 			/* Process next mailbox command if there is one */
13889 			do {
13890 				rc = lpfc_sli_issue_mbox(phba, NULL,
13891 							 MBX_NOWAIT);
13892 			} while (rc == MBX_NOT_FINISHED);
13893 			if (rc != MBX_SUCCESS)
13894 				lpfc_printf_log(phba, KERN_ERR,
13895 						LOG_TRACE_EVENT,
13896 						"0349 rc should be "
13897 						"MBX_SUCCESS\n");
13898 		}
13899 
13900 		spin_lock_irqsave(&phba->hbalock, iflag);
13901 		phba->work_ha |= work_ha_copy;
13902 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13903 		lpfc_worker_wake_up(phba);
13904 	}
13905 	return IRQ_HANDLED;
13906 unplug_error:
13907 	spin_unlock_irqrestore(&phba->hbalock, iflag);
13908 	return IRQ_HANDLED;
13909 
13910 } /* lpfc_sli_sp_intr_handler */
13911 
13912 /**
13913  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13914  * @irq: Interrupt number.
13915  * @dev_id: The device context pointer.
13916  *
13917  * This function is directly called from the PCI layer as an interrupt
13918  * service routine when device with SLI-3 interface spec is enabled with
13919  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13920  * ring event in the HBA. However, when the device is enabled with either
13921  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13922  * device-level interrupt handler. When the PCI slot is in error recovery
13923  * or the HBA is undergoing initialization, the interrupt handler will not
13924  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13925  * the intrrupt context. This function is called without any lock held.
13926  * It gets the hbalock to access and update SLI data structures.
13927  *
13928  * This function returns IRQ_HANDLED when interrupt is handled else it
13929  * returns IRQ_NONE.
13930  **/
13931 irqreturn_t
13932 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13933 {
13934 	struct lpfc_hba  *phba;
13935 	uint32_t ha_copy;
13936 	unsigned long status;
13937 	unsigned long iflag;
13938 	struct lpfc_sli_ring *pring;
13939 
13940 	/* Get the driver's phba structure from the dev_id and
13941 	 * assume the HBA is not interrupting.
13942 	 */
13943 	phba = (struct lpfc_hba *) dev_id;
13944 
13945 	if (unlikely(!phba))
13946 		return IRQ_NONE;
13947 
13948 	/*
13949 	 * Stuff needs to be attented to when this function is invoked as an
13950 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13951 	 */
13952 	if (phba->intr_type == MSIX) {
13953 		/* Check device state for handling interrupt */
13954 		if (lpfc_intr_state_check(phba))
13955 			return IRQ_NONE;
13956 		/* Need to read HA REG for FCP ring and other ring events */
13957 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13958 			return IRQ_HANDLED;
13959 
13960 		/*
13961 		 * If there is deferred error attention, do not check for
13962 		 * any interrupt.
13963 		 */
13964 		if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag)))
13965 			return IRQ_NONE;
13966 
13967 		/* Clear up only attention source related to fast-path */
13968 		spin_lock_irqsave(&phba->hbalock, iflag);
13969 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
13970 			phba->HAregaddr);
13971 		readl(phba->HAregaddr); /* flush */
13972 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13973 	} else
13974 		ha_copy = phba->ha_copy;
13975 
13976 	/*
13977 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
13978 	 */
13979 	ha_copy &= ~(phba->work_ha_mask);
13980 
13981 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13982 	status >>= (4*LPFC_FCP_RING);
13983 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
13984 	if (status & HA_RXMASK)
13985 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
13986 
13987 	if (phba->cfg_multi_ring_support == 2) {
13988 		/*
13989 		 * Process all events on extra ring. Take the optimized path
13990 		 * for extra ring IO.
13991 		 */
13992 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13993 		status >>= (4*LPFC_EXTRA_RING);
13994 		if (status & HA_RXMASK) {
13995 			lpfc_sli_handle_fast_ring_event(phba,
13996 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
13997 					status);
13998 		}
13999 	}
14000 	return IRQ_HANDLED;
14001 }  /* lpfc_sli_fp_intr_handler */
14002 
14003 /**
14004  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
14005  * @irq: Interrupt number.
14006  * @dev_id: The device context pointer.
14007  *
14008  * This function is the HBA device-level interrupt handler to device with
14009  * SLI-3 interface spec, called from the PCI layer when either MSI or
14010  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
14011  * requires driver attention. This function invokes the slow-path interrupt
14012  * attention handling function and fast-path interrupt attention handling
14013  * function in turn to process the relevant HBA attention events. This
14014  * function is called without any lock held. It gets the hbalock to access
14015  * and update SLI data structures.
14016  *
14017  * This function returns IRQ_HANDLED when interrupt is handled, else it
14018  * returns IRQ_NONE.
14019  **/
14020 irqreturn_t
14021 lpfc_sli_intr_handler(int irq, void *dev_id)
14022 {
14023 	struct lpfc_hba  *phba;
14024 	irqreturn_t sp_irq_rc, fp_irq_rc;
14025 	unsigned long status1, status2;
14026 	uint32_t hc_copy;
14027 
14028 	/*
14029 	 * Get the driver's phba structure from the dev_id and
14030 	 * assume the HBA is not interrupting.
14031 	 */
14032 	phba = (struct lpfc_hba *) dev_id;
14033 
14034 	if (unlikely(!phba))
14035 		return IRQ_NONE;
14036 
14037 	/* Check device state for handling interrupt */
14038 	if (lpfc_intr_state_check(phba))
14039 		return IRQ_NONE;
14040 
14041 	spin_lock(&phba->hbalock);
14042 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
14043 		spin_unlock(&phba->hbalock);
14044 		return IRQ_HANDLED;
14045 	}
14046 
14047 	if (unlikely(!phba->ha_copy)) {
14048 		spin_unlock(&phba->hbalock);
14049 		return IRQ_NONE;
14050 	} else if (phba->ha_copy & HA_ERATT) {
14051 		if (test_and_set_bit(HBA_ERATT_HANDLED, &phba->hba_flag))
14052 			/* ERATT polling has handled ERATT */
14053 			phba->ha_copy &= ~HA_ERATT;
14054 	}
14055 
14056 	/*
14057 	 * If there is deferred error attention, do not check for any interrupt.
14058 	 */
14059 	if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag))) {
14060 		spin_unlock(&phba->hbalock);
14061 		return IRQ_NONE;
14062 	}
14063 
14064 	/* Clear attention sources except link and error attentions */
14065 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
14066 		spin_unlock(&phba->hbalock);
14067 		return IRQ_HANDLED;
14068 	}
14069 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
14070 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
14071 		phba->HCregaddr);
14072 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
14073 	writel(hc_copy, phba->HCregaddr);
14074 	readl(phba->HAregaddr); /* flush */
14075 	spin_unlock(&phba->hbalock);
14076 
14077 	/*
14078 	 * Invokes slow-path host attention interrupt handling as appropriate.
14079 	 */
14080 
14081 	/* status of events with mailbox and link attention */
14082 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
14083 
14084 	/* status of events with ELS ring */
14085 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
14086 	status2 >>= (4*LPFC_ELS_RING);
14087 
14088 	if (status1 || (status2 & HA_RXMASK))
14089 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
14090 	else
14091 		sp_irq_rc = IRQ_NONE;
14092 
14093 	/*
14094 	 * Invoke fast-path host attention interrupt handling as appropriate.
14095 	 */
14096 
14097 	/* status of events with FCP ring */
14098 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
14099 	status1 >>= (4*LPFC_FCP_RING);
14100 
14101 	/* status of events with extra ring */
14102 	if (phba->cfg_multi_ring_support == 2) {
14103 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14104 		status2 >>= (4*LPFC_EXTRA_RING);
14105 	} else
14106 		status2 = 0;
14107 
14108 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
14109 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
14110 	else
14111 		fp_irq_rc = IRQ_NONE;
14112 
14113 	/* Return device-level interrupt handling status */
14114 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
14115 }  /* lpfc_sli_intr_handler */
14116 
14117 /**
14118  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
14119  * @phba: pointer to lpfc hba data structure.
14120  *
14121  * This routine is invoked by the worker thread to process all the pending
14122  * SLI4 els abort xri events.
14123  **/
14124 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
14125 {
14126 	struct lpfc_cq_event *cq_event;
14127 	unsigned long iflags;
14128 
14129 	/* First, declare the els xri abort event has been handled */
14130 	clear_bit(ELS_XRI_ABORT_EVENT, &phba->hba_flag);
14131 
14132 	/* Now, handle all the els xri abort events */
14133 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14134 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
14135 		/* Get the first event from the head of the event queue */
14136 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
14137 				 cq_event, struct lpfc_cq_event, list);
14138 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14139 				       iflags);
14140 		/* Notify aborted XRI for ELS work queue */
14141 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
14142 
14143 		/* Free the event processed back to the free pool */
14144 		lpfc_sli4_cq_event_release(phba, cq_event);
14145 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14146 				  iflags);
14147 	}
14148 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14149 }
14150 
14151 /**
14152  * lpfc_sli4_els_preprocess_rspiocbq - Get response iocbq from els wcqe
14153  * @phba: Pointer to HBA context object.
14154  * @irspiocbq: Pointer to work-queue completion queue entry.
14155  *
14156  * This routine handles an ELS work-queue completion event and construct
14157  * a pseudo response ELS IOCBQ from the SLI4 ELS WCQE for the common
14158  * discovery engine to handle.
14159  *
14160  * Return: Pointer to the receive IOCBQ, NULL otherwise.
14161  **/
14162 static struct lpfc_iocbq *
14163 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
14164 				  struct lpfc_iocbq *irspiocbq)
14165 {
14166 	struct lpfc_sli_ring *pring;
14167 	struct lpfc_iocbq *cmdiocbq;
14168 	struct lpfc_wcqe_complete *wcqe;
14169 	unsigned long iflags;
14170 
14171 	pring = lpfc_phba_elsring(phba);
14172 	if (unlikely(!pring))
14173 		return NULL;
14174 
14175 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
14176 	spin_lock_irqsave(&pring->ring_lock, iflags);
14177 	pring->stats.iocb_event++;
14178 	/* Look up the ELS command IOCB and create pseudo response IOCB */
14179 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14180 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14181 	if (unlikely(!cmdiocbq)) {
14182 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
14183 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14184 				"0386 ELS complete with no corresponding "
14185 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
14186 				wcqe->word0, wcqe->total_data_placed,
14187 				wcqe->parameter, wcqe->word3);
14188 		lpfc_sli_release_iocbq(phba, irspiocbq);
14189 		return NULL;
14190 	}
14191 
14192 	memcpy(&irspiocbq->wqe, &cmdiocbq->wqe, sizeof(union lpfc_wqe128));
14193 	memcpy(&irspiocbq->wcqe_cmpl, wcqe, sizeof(*wcqe));
14194 
14195 	/* Put the iocb back on the txcmplq */
14196 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
14197 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
14198 
14199 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
14200 		spin_lock_irqsave(&phba->hbalock, iflags);
14201 		irspiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
14202 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14203 	}
14204 
14205 	return irspiocbq;
14206 }
14207 
14208 inline struct lpfc_cq_event *
14209 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
14210 {
14211 	struct lpfc_cq_event *cq_event;
14212 
14213 	/* Allocate a new internal CQ_EVENT entry */
14214 	cq_event = lpfc_sli4_cq_event_alloc(phba);
14215 	if (!cq_event) {
14216 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14217 				"0602 Failed to alloc CQ_EVENT entry\n");
14218 		return NULL;
14219 	}
14220 
14221 	/* Move the CQE into the event */
14222 	memcpy(&cq_event->cqe, entry, size);
14223 	return cq_event;
14224 }
14225 
14226 /**
14227  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
14228  * @phba: Pointer to HBA context object.
14229  * @mcqe: Pointer to mailbox completion queue entry.
14230  *
14231  * This routine process a mailbox completion queue entry with asynchronous
14232  * event.
14233  *
14234  * Return: true if work posted to worker thread, otherwise false.
14235  **/
14236 static bool
14237 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14238 {
14239 	struct lpfc_cq_event *cq_event;
14240 	unsigned long iflags;
14241 
14242 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14243 			"0392 Async Event: word0:x%x, word1:x%x, "
14244 			"word2:x%x, word3:x%x\n", mcqe->word0,
14245 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
14246 
14247 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
14248 	if (!cq_event)
14249 		return false;
14250 
14251 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
14252 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
14253 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
14254 
14255 	/* Set the async event flag */
14256 	set_bit(ASYNC_EVENT, &phba->hba_flag);
14257 
14258 	return true;
14259 }
14260 
14261 /**
14262  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
14263  * @phba: Pointer to HBA context object.
14264  * @mcqe: Pointer to mailbox completion queue entry.
14265  *
14266  * This routine process a mailbox completion queue entry with mailbox
14267  * completion event.
14268  *
14269  * Return: true if work posted to worker thread, otherwise false.
14270  **/
14271 static bool
14272 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14273 {
14274 	uint32_t mcqe_status;
14275 	MAILBOX_t *mbox, *pmbox;
14276 	struct lpfc_mqe *mqe;
14277 	struct lpfc_vport *vport;
14278 	struct lpfc_nodelist *ndlp;
14279 	struct lpfc_dmabuf *mp;
14280 	unsigned long iflags;
14281 	LPFC_MBOXQ_t *pmb;
14282 	bool workposted = false;
14283 	int rc;
14284 
14285 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
14286 	if (!bf_get(lpfc_trailer_completed, mcqe))
14287 		goto out_no_mqe_complete;
14288 
14289 	/* Get the reference to the active mbox command */
14290 	spin_lock_irqsave(&phba->hbalock, iflags);
14291 	pmb = phba->sli.mbox_active;
14292 	if (unlikely(!pmb)) {
14293 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14294 				"1832 No pending MBOX command to handle\n");
14295 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14296 		goto out_no_mqe_complete;
14297 	}
14298 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14299 	mqe = &pmb->u.mqe;
14300 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
14301 	mbox = phba->mbox;
14302 	vport = pmb->vport;
14303 
14304 	/* Reset heartbeat timer */
14305 	phba->last_completion_time = jiffies;
14306 	timer_delete(&phba->sli.mbox_tmo);
14307 
14308 	/* Move mbox data to caller's mailbox region, do endian swapping */
14309 	if (pmb->mbox_cmpl && mbox)
14310 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
14311 
14312 	/*
14313 	 * For mcqe errors, conditionally move a modified error code to
14314 	 * the mbox so that the error will not be missed.
14315 	 */
14316 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
14317 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
14318 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
14319 			bf_set(lpfc_mqe_status, mqe,
14320 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
14321 	}
14322 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
14323 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
14324 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
14325 				      "MBOX dflt rpi: status:x%x rpi:x%x",
14326 				      mcqe_status,
14327 				      pmbox->un.varWords[0], 0);
14328 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
14329 			mp = pmb->ctx_buf;
14330 			ndlp = pmb->ctx_ndlp;
14331 
14332 			/* Reg_LOGIN of dflt RPI was successful. Mark the
14333 			 * node as having an UNREG_LOGIN in progress to stop
14334 			 * an unsolicited PLOGI from the same NPortId from
14335 			 * starting another mailbox transaction.
14336 			 */
14337 			set_bit(NLP_UNREG_INP, &ndlp->nlp_flag);
14338 			lpfc_unreg_login(phba, vport->vpi,
14339 					 pmbox->un.varWords[0], pmb);
14340 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
14341 			pmb->ctx_buf = mp;
14342 
14343 			/* No reference taken here.  This is a default
14344 			 * RPI reg/immediate unreg cycle. The reference was
14345 			 * taken in the reg rpi path and is released when
14346 			 * this mailbox completes.
14347 			 */
14348 			pmb->ctx_ndlp = ndlp;
14349 			pmb->vport = vport;
14350 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
14351 			if (rc != MBX_BUSY)
14352 				lpfc_printf_log(phba, KERN_ERR,
14353 						LOG_TRACE_EVENT,
14354 						"0385 rc should "
14355 						"have been MBX_BUSY\n");
14356 			if (rc != MBX_NOT_FINISHED)
14357 				goto send_current_mbox;
14358 		}
14359 	}
14360 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
14361 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
14362 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
14363 
14364 	/* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
14365 	if (pmbox->mbxCommand == MBX_HEARTBEAT) {
14366 		spin_lock_irqsave(&phba->hbalock, iflags);
14367 		/* Release the mailbox command posting token */
14368 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14369 		phba->sli.mbox_active = NULL;
14370 		if (bf_get(lpfc_trailer_consumed, mcqe))
14371 			lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14372 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14373 
14374 		/* Post the next mbox command, if there is one */
14375 		lpfc_sli4_post_async_mbox(phba);
14376 
14377 		/* Process cmpl now */
14378 		if (pmb->mbox_cmpl)
14379 			pmb->mbox_cmpl(phba, pmb);
14380 		return false;
14381 	}
14382 
14383 	/* There is mailbox completion work to queue to the worker thread */
14384 	spin_lock_irqsave(&phba->hbalock, iflags);
14385 	__lpfc_mbox_cmpl_put(phba, pmb);
14386 	phba->work_ha |= HA_MBATT;
14387 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14388 	workposted = true;
14389 
14390 send_current_mbox:
14391 	spin_lock_irqsave(&phba->hbalock, iflags);
14392 	/* Release the mailbox command posting token */
14393 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14394 	/* Setting active mailbox pointer need to be in sync to flag clear */
14395 	phba->sli.mbox_active = NULL;
14396 	if (bf_get(lpfc_trailer_consumed, mcqe))
14397 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14398 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14399 	/* Wake up worker thread to post the next pending mailbox command */
14400 	lpfc_worker_wake_up(phba);
14401 	return workposted;
14402 
14403 out_no_mqe_complete:
14404 	spin_lock_irqsave(&phba->hbalock, iflags);
14405 	if (bf_get(lpfc_trailer_consumed, mcqe))
14406 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14407 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14408 	return false;
14409 }
14410 
14411 /**
14412  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
14413  * @phba: Pointer to HBA context object.
14414  * @cq: Pointer to associated CQ
14415  * @cqe: Pointer to mailbox completion queue entry.
14416  *
14417  * This routine process a mailbox completion queue entry, it invokes the
14418  * proper mailbox complete handling or asynchronous event handling routine
14419  * according to the MCQE's async bit.
14420  *
14421  * Return: true if work posted to worker thread, otherwise false.
14422  **/
14423 static bool
14424 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14425 			 struct lpfc_cqe *cqe)
14426 {
14427 	struct lpfc_mcqe mcqe;
14428 	bool workposted;
14429 
14430 	cq->CQ_mbox++;
14431 
14432 	/* Copy the mailbox MCQE and convert endian order as needed */
14433 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
14434 
14435 	/* Invoke the proper event handling routine */
14436 	if (!bf_get(lpfc_trailer_async, &mcqe))
14437 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
14438 	else
14439 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
14440 	return workposted;
14441 }
14442 
14443 /**
14444  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
14445  * @phba: Pointer to HBA context object.
14446  * @cq: Pointer to associated CQ
14447  * @wcqe: Pointer to work-queue completion queue entry.
14448  *
14449  * This routine handles an ELS work-queue completion event.
14450  *
14451  * Return: true if work posted to worker thread, otherwise false.
14452  **/
14453 static bool
14454 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14455 			     struct lpfc_wcqe_complete *wcqe)
14456 {
14457 	struct lpfc_iocbq *irspiocbq;
14458 	unsigned long iflags;
14459 	struct lpfc_sli_ring *pring = cq->pring;
14460 	int txq_cnt = 0;
14461 	int txcmplq_cnt = 0;
14462 
14463 	/* Check for response status */
14464 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14465 		/* Log the error status */
14466 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14467 				"0357 ELS CQE error: status=x%x: "
14468 				"CQE: %08x %08x %08x %08x\n",
14469 				bf_get(lpfc_wcqe_c_status, wcqe),
14470 				wcqe->word0, wcqe->total_data_placed,
14471 				wcqe->parameter, wcqe->word3);
14472 	}
14473 
14474 	/* Get an irspiocbq for later ELS response processing use */
14475 	irspiocbq = lpfc_sli_get_iocbq(phba);
14476 	if (!irspiocbq) {
14477 		if (!list_empty(&pring->txq))
14478 			txq_cnt++;
14479 		if (!list_empty(&pring->txcmplq))
14480 			txcmplq_cnt++;
14481 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14482 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
14483 			"els_txcmplq_cnt=%d\n",
14484 			txq_cnt, phba->iocb_cnt,
14485 			txcmplq_cnt);
14486 		return false;
14487 	}
14488 
14489 	/* Save off the slow-path queue event for work thread to process */
14490 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
14491 	spin_lock_irqsave(&phba->hbalock, iflags);
14492 	list_add_tail(&irspiocbq->cq_event.list,
14493 		      &phba->sli4_hba.sp_queue_event);
14494 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14495 	set_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
14496 
14497 	return true;
14498 }
14499 
14500 /**
14501  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
14502  * @phba: Pointer to HBA context object.
14503  * @wcqe: Pointer to work-queue completion queue entry.
14504  *
14505  * This routine handles slow-path WQ entry consumed event by invoking the
14506  * proper WQ release routine to the slow-path WQ.
14507  **/
14508 static void
14509 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
14510 			     struct lpfc_wcqe_release *wcqe)
14511 {
14512 	/* sanity check on queue memory */
14513 	if (unlikely(!phba->sli4_hba.els_wq))
14514 		return;
14515 	/* Check for the slow-path ELS work queue */
14516 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
14517 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
14518 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14519 	else
14520 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14521 				"2579 Slow-path wqe consume event carries "
14522 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
14523 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
14524 				phba->sli4_hba.els_wq->queue_id);
14525 }
14526 
14527 /**
14528  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
14529  * @phba: Pointer to HBA context object.
14530  * @cq: Pointer to a WQ completion queue.
14531  * @wcqe: Pointer to work-queue completion queue entry.
14532  *
14533  * This routine handles an XRI abort event.
14534  *
14535  * Return: true if work posted to worker thread, otherwise false.
14536  **/
14537 static bool
14538 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
14539 				   struct lpfc_queue *cq,
14540 				   struct sli4_wcqe_xri_aborted *wcqe)
14541 {
14542 	bool workposted = false;
14543 	struct lpfc_cq_event *cq_event;
14544 	unsigned long iflags;
14545 
14546 	switch (cq->subtype) {
14547 	case LPFC_IO:
14548 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
14549 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14550 			/* Notify aborted XRI for NVME work queue */
14551 			if (phba->nvmet_support)
14552 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
14553 		}
14554 		workposted = false;
14555 		break;
14556 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
14557 	case LPFC_ELS:
14558 		cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
14559 		if (!cq_event) {
14560 			workposted = false;
14561 			break;
14562 		}
14563 		cq_event->hdwq = cq->hdwq;
14564 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14565 				  iflags);
14566 		list_add_tail(&cq_event->list,
14567 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
14568 		/* Set the els xri abort event flag */
14569 		set_bit(ELS_XRI_ABORT_EVENT, &phba->hba_flag);
14570 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14571 				       iflags);
14572 		workposted = true;
14573 		break;
14574 	default:
14575 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14576 				"0603 Invalid CQ subtype %d: "
14577 				"%08x %08x %08x %08x\n",
14578 				cq->subtype, wcqe->word0, wcqe->parameter,
14579 				wcqe->word2, wcqe->word3);
14580 		workposted = false;
14581 		break;
14582 	}
14583 	return workposted;
14584 }
14585 
14586 #define FC_RCTL_MDS_DIAGS	0xF4
14587 
14588 /**
14589  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
14590  * @phba: Pointer to HBA context object.
14591  * @rcqe: Pointer to receive-queue completion queue entry.
14592  *
14593  * This routine process a receive-queue completion queue entry.
14594  *
14595  * Return: true if work posted to worker thread, otherwise false.
14596  **/
14597 static bool
14598 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
14599 {
14600 	bool workposted = false;
14601 	struct fc_frame_header *fc_hdr;
14602 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
14603 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
14604 	struct lpfc_nvmet_tgtport *tgtp;
14605 	struct hbq_dmabuf *dma_buf;
14606 	uint32_t status, rq_id;
14607 	unsigned long iflags;
14608 
14609 	/* sanity check on queue memory */
14610 	if (unlikely(!hrq) || unlikely(!drq))
14611 		return workposted;
14612 
14613 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14614 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14615 	else
14616 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14617 	if (rq_id != hrq->queue_id)
14618 		goto out;
14619 
14620 	status = bf_get(lpfc_rcqe_status, rcqe);
14621 	switch (status) {
14622 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14623 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14624 				"2537 Receive Frame Truncated!!\n");
14625 		fallthrough;
14626 	case FC_STATUS_RQ_SUCCESS:
14627 		spin_lock_irqsave(&phba->hbalock, iflags);
14628 		lpfc_sli4_rq_release(hrq, drq);
14629 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14630 		if (!dma_buf) {
14631 			hrq->RQ_no_buf_found++;
14632 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14633 			goto out;
14634 		}
14635 		hrq->RQ_rcv_buf++;
14636 		hrq->RQ_buf_posted--;
14637 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
14638 
14639 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14640 
14641 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
14642 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
14643 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14644 			/* Handle MDS Loopback frames */
14645 			if  (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
14646 				lpfc_sli4_handle_mds_loopback(phba->pport,
14647 							      dma_buf);
14648 			else
14649 				lpfc_in_buf_free(phba, &dma_buf->dbuf);
14650 			break;
14651 		}
14652 
14653 		/* save off the frame for the work thread to process */
14654 		list_add_tail(&dma_buf->cq_event.list,
14655 			      &phba->sli4_hba.sp_queue_event);
14656 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14657 		/* Frame received */
14658 		set_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
14659 		workposted = true;
14660 		break;
14661 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14662 		if (phba->nvmet_support) {
14663 			tgtp = phba->targetport->private;
14664 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14665 					"6402 RQE Error x%x, posted %d err_cnt "
14666 					"%d: %x %x %x\n",
14667 					status, hrq->RQ_buf_posted,
14668 					hrq->RQ_no_posted_buf,
14669 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14670 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14671 					atomic_read(&tgtp->xmt_fcp_release));
14672 		}
14673 		fallthrough;
14674 
14675 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14676 		hrq->RQ_no_posted_buf++;
14677 		/* Post more buffers if possible */
14678 		set_bit(HBA_POST_RECEIVE_BUFFER, &phba->hba_flag);
14679 		workposted = true;
14680 		break;
14681 	case FC_STATUS_RQ_DMA_FAILURE:
14682 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14683 				"2564 RQE DMA Error x%x, x%08x x%08x x%08x "
14684 				"x%08x\n",
14685 				status, rcqe->word0, rcqe->word1,
14686 				rcqe->word2, rcqe->word3);
14687 
14688 		/* If IV set, no further recovery */
14689 		if (bf_get(lpfc_rcqe_iv, rcqe))
14690 			break;
14691 
14692 		/* recycle consumed resource */
14693 		spin_lock_irqsave(&phba->hbalock, iflags);
14694 		lpfc_sli4_rq_release(hrq, drq);
14695 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14696 		if (!dma_buf) {
14697 			hrq->RQ_no_buf_found++;
14698 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14699 			break;
14700 		}
14701 		hrq->RQ_rcv_buf++;
14702 		hrq->RQ_buf_posted--;
14703 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14704 		lpfc_in_buf_free(phba, &dma_buf->dbuf);
14705 		break;
14706 	default:
14707 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14708 				"2565 Unexpected RQE Status x%x, w0-3 x%08x "
14709 				"x%08x x%08x x%08x\n",
14710 				status, rcqe->word0, rcqe->word1,
14711 				rcqe->word2, rcqe->word3);
14712 		break;
14713 	}
14714 out:
14715 	return workposted;
14716 }
14717 
14718 /**
14719  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
14720  * @phba: Pointer to HBA context object.
14721  * @cq: Pointer to the completion queue.
14722  * @cqe: Pointer to a completion queue entry.
14723  *
14724  * This routine process a slow-path work-queue or receive queue completion queue
14725  * entry.
14726  *
14727  * Return: true if work posted to worker thread, otherwise false.
14728  **/
14729 static bool
14730 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14731 			 struct lpfc_cqe *cqe)
14732 {
14733 	struct lpfc_cqe cqevt;
14734 	bool workposted = false;
14735 
14736 	/* Copy the work queue CQE and convert endian order if needed */
14737 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14738 
14739 	/* Check and process for different type of WCQE and dispatch */
14740 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
14741 	case CQE_CODE_COMPL_WQE:
14742 		/* Process the WQ/RQ complete event */
14743 		phba->last_completion_time = jiffies;
14744 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14745 				(struct lpfc_wcqe_complete *)&cqevt);
14746 		break;
14747 	case CQE_CODE_RELEASE_WQE:
14748 		/* Process the WQ release event */
14749 		lpfc_sli4_sp_handle_rel_wcqe(phba,
14750 				(struct lpfc_wcqe_release *)&cqevt);
14751 		break;
14752 	case CQE_CODE_XRI_ABORTED:
14753 		/* Process the WQ XRI abort event */
14754 		phba->last_completion_time = jiffies;
14755 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14756 				(struct sli4_wcqe_xri_aborted *)&cqevt);
14757 		break;
14758 	case CQE_CODE_RECEIVE:
14759 	case CQE_CODE_RECEIVE_V1:
14760 		/* Process the RQ event */
14761 		phba->last_completion_time = jiffies;
14762 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
14763 				(struct lpfc_rcqe *)&cqevt);
14764 		break;
14765 	default:
14766 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14767 				"0388 Not a valid WCQE code: x%x\n",
14768 				bf_get(lpfc_cqe_code, &cqevt));
14769 		break;
14770 	}
14771 	return workposted;
14772 }
14773 
14774 /**
14775  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14776  * @phba: Pointer to HBA context object.
14777  * @eqe: Pointer to fast-path event queue entry.
14778  * @speq: Pointer to slow-path event queue.
14779  *
14780  * This routine process a event queue entry from the slow-path event queue.
14781  * It will check the MajorCode and MinorCode to determine this is for a
14782  * completion event on a completion queue, if not, an error shall be logged
14783  * and just return. Otherwise, it will get to the corresponding completion
14784  * queue and process all the entries on that completion queue, rearm the
14785  * completion queue, and then return.
14786  *
14787  **/
14788 static void
14789 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14790 	struct lpfc_queue *speq)
14791 {
14792 	struct lpfc_queue *cq = NULL, *childq;
14793 	uint16_t cqid;
14794 	int ret = 0;
14795 
14796 	/* Get the reference to the corresponding CQ */
14797 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14798 
14799 	list_for_each_entry(childq, &speq->child_list, list) {
14800 		if (childq->queue_id == cqid) {
14801 			cq = childq;
14802 			break;
14803 		}
14804 	}
14805 	if (unlikely(!cq)) {
14806 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14807 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14808 					"0365 Slow-path CQ identifier "
14809 					"(%d) does not exist\n", cqid);
14810 		return;
14811 	}
14812 
14813 	/* Save EQ associated with this CQ */
14814 	cq->assoc_qp = speq;
14815 
14816 	if (is_kdump_kernel())
14817 		ret = queue_work(phba->wq, &cq->spwork);
14818 	else
14819 		ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14820 
14821 	if (!ret)
14822 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14823 				"0390 Cannot schedule queue work "
14824 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14825 				cqid, cq->queue_id, raw_smp_processor_id());
14826 }
14827 
14828 /**
14829  * __lpfc_sli4_process_cq - Process elements of a CQ
14830  * @phba: Pointer to HBA context object.
14831  * @cq: Pointer to CQ to be processed
14832  * @handler: Routine to process each cqe
14833  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14834  *
14835  * This routine processes completion queue entries in a CQ. While a valid
14836  * queue element is found, the handler is called. During processing checks
14837  * are made for periodic doorbell writes to let the hardware know of
14838  * element consumption.
14839  *
14840  * If the max limit on cqes to process is hit, or there are no more valid
14841  * entries, the loop stops. If we processed a sufficient number of elements,
14842  * meaning there is sufficient load, rather than rearming and generating
14843  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14844  * indicates no rescheduling.
14845  *
14846  * Returns True if work scheduled, False otherwise.
14847  **/
14848 static bool
14849 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14850 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14851 			struct lpfc_cqe *), unsigned long *delay)
14852 {
14853 	struct lpfc_cqe *cqe;
14854 	bool workposted = false;
14855 	int count = 0, consumed = 0;
14856 	bool arm = true;
14857 
14858 	/* default - no reschedule */
14859 	*delay = 0;
14860 
14861 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14862 		goto rearm_and_exit;
14863 
14864 	/* Process all the entries to the CQ */
14865 	cq->q_flag = 0;
14866 	cqe = lpfc_sli4_cq_get(cq);
14867 	while (cqe) {
14868 		workposted |= handler(phba, cq, cqe);
14869 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
14870 
14871 		consumed++;
14872 		if (!(++count % cq->max_proc_limit))
14873 			break;
14874 
14875 		if (!(count % cq->notify_interval)) {
14876 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14877 						LPFC_QUEUE_NOARM);
14878 			consumed = 0;
14879 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14880 		}
14881 
14882 		if (count == LPFC_NVMET_CQ_NOTIFY)
14883 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14884 
14885 		cqe = lpfc_sli4_cq_get(cq);
14886 	}
14887 	if (count >= phba->cfg_cq_poll_threshold) {
14888 		*delay = 1;
14889 		arm = false;
14890 	}
14891 
14892 	/* Track the max number of CQEs processed in 1 EQ */
14893 	if (count > cq->CQ_max_cqe)
14894 		cq->CQ_max_cqe = count;
14895 
14896 	cq->assoc_qp->EQ_cqe_cnt += count;
14897 
14898 	/* Catch the no cq entry condition */
14899 	if (unlikely(count == 0))
14900 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14901 				"0369 No entry from completion queue "
14902 				"qid=%d\n", cq->queue_id);
14903 
14904 	xchg(&cq->queue_claimed, 0);
14905 
14906 rearm_and_exit:
14907 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14908 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14909 
14910 	return workposted;
14911 }
14912 
14913 /**
14914  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14915  * @cq: pointer to CQ to process
14916  *
14917  * This routine calls the cq processing routine with a handler specific
14918  * to the type of queue bound to it.
14919  *
14920  * The CQ routine returns two values: the first is the calling status,
14921  * which indicates whether work was queued to the  background discovery
14922  * thread. If true, the routine should wakeup the discovery thread;
14923  * the second is the delay parameter. If non-zero, rather than rearming
14924  * the CQ and yet another interrupt, the CQ handler should be queued so
14925  * that it is processed in a subsequent polling action. The value of
14926  * the delay indicates when to reschedule it.
14927  **/
14928 static void
14929 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14930 {
14931 	struct lpfc_hba *phba = cq->phba;
14932 	unsigned long delay;
14933 	bool workposted = false;
14934 	int ret = 0;
14935 
14936 	/* Process and rearm the CQ */
14937 	switch (cq->type) {
14938 	case LPFC_MCQ:
14939 		workposted |= __lpfc_sli4_process_cq(phba, cq,
14940 						lpfc_sli4_sp_handle_mcqe,
14941 						&delay);
14942 		break;
14943 	case LPFC_WCQ:
14944 		if (cq->subtype == LPFC_IO)
14945 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14946 						lpfc_sli4_fp_handle_cqe,
14947 						&delay);
14948 		else
14949 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14950 						lpfc_sli4_sp_handle_cqe,
14951 						&delay);
14952 		break;
14953 	default:
14954 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14955 				"0370 Invalid completion queue type (%d)\n",
14956 				cq->type);
14957 		return;
14958 	}
14959 
14960 	if (delay) {
14961 		if (is_kdump_kernel())
14962 			ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
14963 						delay);
14964 		else
14965 			ret = queue_delayed_work_on(cq->chann, phba->wq,
14966 						&cq->sched_spwork, delay);
14967 		if (!ret)
14968 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14969 				"0394 Cannot schedule queue work "
14970 				"for cqid=%d on CPU %d\n",
14971 				cq->queue_id, cq->chann);
14972 	}
14973 
14974 	/* wake up worker thread if there are works to be done */
14975 	if (workposted)
14976 		lpfc_worker_wake_up(phba);
14977 }
14978 
14979 /**
14980  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
14981  *   interrupt
14982  * @work: pointer to work element
14983  *
14984  * translates from the work handler and calls the slow-path handler.
14985  **/
14986 static void
14987 lpfc_sli4_sp_process_cq(struct work_struct *work)
14988 {
14989 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
14990 
14991 	__lpfc_sli4_sp_process_cq(cq);
14992 }
14993 
14994 /**
14995  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
14996  * @work: pointer to work element
14997  *
14998  * translates from the work handler and calls the slow-path handler.
14999  **/
15000 static void
15001 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
15002 {
15003 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15004 					struct lpfc_queue, sched_spwork);
15005 
15006 	__lpfc_sli4_sp_process_cq(cq);
15007 }
15008 
15009 /**
15010  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
15011  * @phba: Pointer to HBA context object.
15012  * @cq: Pointer to associated CQ
15013  * @wcqe: Pointer to work-queue completion queue entry.
15014  *
15015  * This routine process a fast-path work queue completion entry from fast-path
15016  * event queue for FCP command response completion.
15017  **/
15018 static void
15019 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15020 			     struct lpfc_wcqe_complete *wcqe)
15021 {
15022 	struct lpfc_sli_ring *pring = cq->pring;
15023 	struct lpfc_iocbq *cmdiocbq;
15024 	unsigned long iflags;
15025 
15026 	/* Check for response status */
15027 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
15028 		/* If resource errors reported from HBA, reduce queue
15029 		 * depth of the SCSI device.
15030 		 */
15031 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
15032 		     IOSTAT_LOCAL_REJECT)) &&
15033 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
15034 		     IOERR_NO_RESOURCES))
15035 			phba->lpfc_rampdown_queue_depth(phba);
15036 
15037 		/* Log the cmpl status */
15038 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15039 				"0373 FCP CQE cmpl: status=x%x: "
15040 				"CQE: %08x %08x %08x %08x\n",
15041 				bf_get(lpfc_wcqe_c_status, wcqe),
15042 				wcqe->word0, wcqe->total_data_placed,
15043 				wcqe->parameter, wcqe->word3);
15044 	}
15045 
15046 	/* Look up the FCP command IOCB and create pseudo response IOCB */
15047 	spin_lock_irqsave(&pring->ring_lock, iflags);
15048 	pring->stats.iocb_event++;
15049 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
15050 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15051 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
15052 	if (unlikely(!cmdiocbq)) {
15053 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15054 				"0374 FCP complete with no corresponding "
15055 				"cmdiocb: iotag (%d)\n",
15056 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15057 		return;
15058 	}
15059 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
15060 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
15061 #endif
15062 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
15063 		spin_lock_irqsave(&phba->hbalock, iflags);
15064 		cmdiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
15065 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15066 	}
15067 
15068 	if (cmdiocbq->cmd_cmpl) {
15069 		/* For FCP the flag is cleared in cmd_cmpl */
15070 		if (!(cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
15071 		    cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED) {
15072 			spin_lock_irqsave(&phba->hbalock, iflags);
15073 			cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
15074 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15075 		}
15076 
15077 		/* Pass the cmd_iocb and the wcqe to the upper layer */
15078 		memcpy(&cmdiocbq->wcqe_cmpl, wcqe,
15079 		       sizeof(struct lpfc_wcqe_complete));
15080 		cmdiocbq->cmd_cmpl(phba, cmdiocbq, cmdiocbq);
15081 	} else {
15082 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15083 				"0375 FCP cmdiocb not callback function "
15084 				"iotag: (%d)\n",
15085 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15086 	}
15087 }
15088 
15089 /**
15090  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
15091  * @phba: Pointer to HBA context object.
15092  * @cq: Pointer to completion queue.
15093  * @wcqe: Pointer to work-queue completion queue entry.
15094  *
15095  * This routine handles an fast-path WQ entry consumed event by invoking the
15096  * proper WQ release routine to the slow-path WQ.
15097  **/
15098 static void
15099 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15100 			     struct lpfc_wcqe_release *wcqe)
15101 {
15102 	struct lpfc_queue *childwq;
15103 	bool wqid_matched = false;
15104 	uint16_t hba_wqid;
15105 
15106 	/* Check for fast-path FCP work queue release */
15107 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
15108 	list_for_each_entry(childwq, &cq->child_list, list) {
15109 		if (childwq->queue_id == hba_wqid) {
15110 			lpfc_sli4_wq_release(childwq,
15111 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
15112 			if (childwq->q_flag & HBA_NVMET_WQFULL)
15113 				lpfc_nvmet_wqfull_process(phba, childwq);
15114 			wqid_matched = true;
15115 			break;
15116 		}
15117 	}
15118 	/* Report warning log message if no match found */
15119 	if (wqid_matched != true)
15120 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15121 				"2580 Fast-path wqe consume event carries "
15122 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
15123 }
15124 
15125 /**
15126  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
15127  * @phba: Pointer to HBA context object.
15128  * @cq: Pointer to completion queue.
15129  * @rcqe: Pointer to receive-queue completion queue entry.
15130  *
15131  * This routine process a receive-queue completion queue entry.
15132  *
15133  * Return: true if work posted to worker thread, otherwise false.
15134  **/
15135 static bool
15136 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15137 			    struct lpfc_rcqe *rcqe)
15138 {
15139 	bool workposted = false;
15140 	struct lpfc_queue *hrq;
15141 	struct lpfc_queue *drq;
15142 	struct rqb_dmabuf *dma_buf;
15143 	struct fc_frame_header *fc_hdr;
15144 	struct lpfc_nvmet_tgtport *tgtp;
15145 	uint32_t status, rq_id;
15146 	unsigned long iflags;
15147 	uint32_t fctl, idx;
15148 
15149 	if ((phba->nvmet_support == 0) ||
15150 	    (phba->sli4_hba.nvmet_cqset == NULL))
15151 		return workposted;
15152 
15153 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
15154 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
15155 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
15156 
15157 	/* sanity check on queue memory */
15158 	if (unlikely(!hrq) || unlikely(!drq))
15159 		return workposted;
15160 
15161 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
15162 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
15163 	else
15164 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
15165 
15166 	if ((phba->nvmet_support == 0) ||
15167 	    (rq_id != hrq->queue_id))
15168 		return workposted;
15169 
15170 	status = bf_get(lpfc_rcqe_status, rcqe);
15171 	switch (status) {
15172 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
15173 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15174 				"6126 Receive Frame Truncated!!\n");
15175 		fallthrough;
15176 	case FC_STATUS_RQ_SUCCESS:
15177 		spin_lock_irqsave(&phba->hbalock, iflags);
15178 		lpfc_sli4_rq_release(hrq, drq);
15179 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15180 		if (!dma_buf) {
15181 			hrq->RQ_no_buf_found++;
15182 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15183 			goto out;
15184 		}
15185 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15186 		hrq->RQ_rcv_buf++;
15187 		hrq->RQ_buf_posted--;
15188 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
15189 
15190 		/* Just some basic sanity checks on FCP Command frame */
15191 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
15192 			fc_hdr->fh_f_ctl[1] << 8 |
15193 			fc_hdr->fh_f_ctl[2]);
15194 		if (((fctl &
15195 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
15196 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
15197 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
15198 			goto drop;
15199 
15200 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
15201 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
15202 			lpfc_nvmet_unsol_fcp_event(
15203 				phba, idx, dma_buf, cq->isr_timestamp,
15204 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
15205 			return false;
15206 		}
15207 drop:
15208 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15209 		break;
15210 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
15211 		if (phba->nvmet_support) {
15212 			tgtp = phba->targetport->private;
15213 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15214 					"6401 RQE Error x%x, posted %d err_cnt "
15215 					"%d: %x %x %x\n",
15216 					status, hrq->RQ_buf_posted,
15217 					hrq->RQ_no_posted_buf,
15218 					atomic_read(&tgtp->rcv_fcp_cmd_in),
15219 					atomic_read(&tgtp->rcv_fcp_cmd_out),
15220 					atomic_read(&tgtp->xmt_fcp_release));
15221 		}
15222 		fallthrough;
15223 
15224 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
15225 		hrq->RQ_no_posted_buf++;
15226 		/* Post more buffers if possible */
15227 		break;
15228 	case FC_STATUS_RQ_DMA_FAILURE:
15229 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15230 				"2575 RQE DMA Error x%x, x%08x x%08x x%08x "
15231 				"x%08x\n",
15232 				status, rcqe->word0, rcqe->word1,
15233 				rcqe->word2, rcqe->word3);
15234 
15235 		/* If IV set, no further recovery */
15236 		if (bf_get(lpfc_rcqe_iv, rcqe))
15237 			break;
15238 
15239 		/* recycle consumed resource */
15240 		spin_lock_irqsave(&phba->hbalock, iflags);
15241 		lpfc_sli4_rq_release(hrq, drq);
15242 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15243 		if (!dma_buf) {
15244 			hrq->RQ_no_buf_found++;
15245 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15246 			break;
15247 		}
15248 		hrq->RQ_rcv_buf++;
15249 		hrq->RQ_buf_posted--;
15250 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15251 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15252 		break;
15253 	default:
15254 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15255 				"2576 Unexpected RQE Status x%x, w0-3 x%08x "
15256 				"x%08x x%08x x%08x\n",
15257 				status, rcqe->word0, rcqe->word1,
15258 				rcqe->word2, rcqe->word3);
15259 		break;
15260 	}
15261 out:
15262 	return workposted;
15263 }
15264 
15265 /**
15266  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
15267  * @phba: adapter with cq
15268  * @cq: Pointer to the completion queue.
15269  * @cqe: Pointer to fast-path completion queue entry.
15270  *
15271  * This routine process a fast-path work queue completion entry from fast-path
15272  * event queue for FCP command response completion.
15273  *
15274  * Return: true if work posted to worker thread, otherwise false.
15275  **/
15276 static bool
15277 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15278 			 struct lpfc_cqe *cqe)
15279 {
15280 	struct lpfc_wcqe_release wcqe;
15281 	bool workposted = false;
15282 
15283 	/* Copy the work queue CQE and convert endian order if needed */
15284 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
15285 
15286 	/* Check and process for different type of WCQE and dispatch */
15287 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
15288 	case CQE_CODE_COMPL_WQE:
15289 	case CQE_CODE_NVME_ERSP:
15290 		cq->CQ_wq++;
15291 		/* Process the WQ complete event */
15292 		phba->last_completion_time = jiffies;
15293 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
15294 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
15295 				(struct lpfc_wcqe_complete *)&wcqe);
15296 		break;
15297 	case CQE_CODE_RELEASE_WQE:
15298 		cq->CQ_release_wqe++;
15299 		/* Process the WQ release event */
15300 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
15301 				(struct lpfc_wcqe_release *)&wcqe);
15302 		break;
15303 	case CQE_CODE_XRI_ABORTED:
15304 		cq->CQ_xri_aborted++;
15305 		/* Process the WQ XRI abort event */
15306 		phba->last_completion_time = jiffies;
15307 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
15308 				(struct sli4_wcqe_xri_aborted *)&wcqe);
15309 		break;
15310 	case CQE_CODE_RECEIVE_V1:
15311 	case CQE_CODE_RECEIVE:
15312 		phba->last_completion_time = jiffies;
15313 		if (cq->subtype == LPFC_NVMET) {
15314 			workposted = lpfc_sli4_nvmet_handle_rcqe(
15315 				phba, cq, (struct lpfc_rcqe *)&wcqe);
15316 		}
15317 		break;
15318 	default:
15319 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15320 				"0144 Not a valid CQE code: x%x\n",
15321 				bf_get(lpfc_wcqe_c_code, &wcqe));
15322 		break;
15323 	}
15324 	return workposted;
15325 }
15326 
15327 /**
15328  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
15329  * @cq: Pointer to CQ to be processed
15330  *
15331  * This routine calls the cq processing routine with the handler for
15332  * fast path CQEs.
15333  *
15334  * The CQ routine returns two values: the first is the calling status,
15335  * which indicates whether work was queued to the  background discovery
15336  * thread. If true, the routine should wakeup the discovery thread;
15337  * the second is the delay parameter. If non-zero, rather than rearming
15338  * the CQ and yet another interrupt, the CQ handler should be queued so
15339  * that it is processed in a subsequent polling action. The value of
15340  * the delay indicates when to reschedule it.
15341  **/
15342 static void
15343 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq)
15344 {
15345 	struct lpfc_hba *phba = cq->phba;
15346 	unsigned long delay;
15347 	bool workposted = false;
15348 	int ret;
15349 
15350 	/* process and rearm the CQ */
15351 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
15352 					     &delay);
15353 
15354 	if (delay) {
15355 		if (is_kdump_kernel())
15356 			ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
15357 						delay);
15358 		else
15359 			ret = queue_delayed_work_on(cq->chann, phba->wq,
15360 						&cq->sched_irqwork, delay);
15361 		if (!ret)
15362 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15363 					"0367 Cannot schedule queue work "
15364 					"for cqid=%d on CPU %d\n",
15365 					cq->queue_id, cq->chann);
15366 	}
15367 
15368 	/* wake up worker thread if there are works to be done */
15369 	if (workposted)
15370 		lpfc_worker_wake_up(phba);
15371 }
15372 
15373 /**
15374  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
15375  *   interrupt
15376  * @work: pointer to work element
15377  *
15378  * translates from the work handler and calls the fast-path handler.
15379  **/
15380 static void
15381 lpfc_sli4_hba_process_cq(struct work_struct *work)
15382 {
15383 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
15384 
15385 	__lpfc_sli4_hba_process_cq(cq);
15386 }
15387 
15388 /**
15389  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
15390  * @phba: Pointer to HBA context object.
15391  * @eq: Pointer to the queue structure.
15392  * @eqe: Pointer to fast-path event queue entry.
15393  * @poll_mode: poll_mode to execute processing the cq.
15394  *
15395  * This routine process a event queue entry from the fast-path event queue.
15396  * It will check the MajorCode and MinorCode to determine this is for a
15397  * completion event on a completion queue, if not, an error shall be logged
15398  * and just return. Otherwise, it will get to the corresponding completion
15399  * queue and process all the entries on the completion queue, rearm the
15400  * completion queue, and then return.
15401  **/
15402 static void
15403 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
15404 			 struct lpfc_eqe *eqe, enum lpfc_poll_mode poll_mode)
15405 {
15406 	struct lpfc_queue *cq = NULL;
15407 	uint32_t qidx = eq->hdwq;
15408 	uint16_t cqid, id;
15409 	int ret;
15410 
15411 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
15412 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15413 				"0366 Not a valid completion "
15414 				"event: majorcode=x%x, minorcode=x%x\n",
15415 				bf_get_le32(lpfc_eqe_major_code, eqe),
15416 				bf_get_le32(lpfc_eqe_minor_code, eqe));
15417 		return;
15418 	}
15419 
15420 	/* Get the reference to the corresponding CQ */
15421 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
15422 
15423 	/* Use the fast lookup method first */
15424 	if (cqid <= phba->sli4_hba.cq_max) {
15425 		cq = phba->sli4_hba.cq_lookup[cqid];
15426 		if (cq)
15427 			goto  work_cq;
15428 	}
15429 
15430 	/* Next check for NVMET completion */
15431 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
15432 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
15433 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
15434 			/* Process NVMET unsol rcv */
15435 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
15436 			goto  process_cq;
15437 		}
15438 	}
15439 
15440 	if (phba->sli4_hba.nvmels_cq &&
15441 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
15442 		/* Process NVME unsol rcv */
15443 		cq = phba->sli4_hba.nvmels_cq;
15444 	}
15445 
15446 	/* Otherwise this is a Slow path event */
15447 	if (cq == NULL) {
15448 		lpfc_sli4_sp_handle_eqe(phba, eqe,
15449 					phba->sli4_hba.hdwq[qidx].hba_eq);
15450 		return;
15451 	}
15452 
15453 process_cq:
15454 	if (unlikely(cqid != cq->queue_id)) {
15455 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15456 				"0368 Miss-matched fast-path completion "
15457 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
15458 				cqid, cq->queue_id);
15459 		return;
15460 	}
15461 
15462 work_cq:
15463 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
15464 	if (phba->ktime_on)
15465 		cq->isr_timestamp = ktime_get_ns();
15466 	else
15467 		cq->isr_timestamp = 0;
15468 #endif
15469 
15470 	switch (poll_mode) {
15471 	case LPFC_THREADED_IRQ:
15472 		__lpfc_sli4_hba_process_cq(cq);
15473 		break;
15474 	case LPFC_QUEUE_WORK:
15475 	default:
15476 		if (is_kdump_kernel())
15477 			ret = queue_work(phba->wq, &cq->irqwork);
15478 		else
15479 			ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
15480 		if (!ret)
15481 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15482 					"0383 Cannot schedule queue work "
15483 					"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
15484 					cqid, cq->queue_id,
15485 					raw_smp_processor_id());
15486 		break;
15487 	}
15488 }
15489 
15490 /**
15491  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
15492  * @work: pointer to work element
15493  *
15494  * translates from the work handler and calls the fast-path handler.
15495  **/
15496 static void
15497 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
15498 {
15499 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15500 					struct lpfc_queue, sched_irqwork);
15501 
15502 	__lpfc_sli4_hba_process_cq(cq);
15503 }
15504 
15505 /**
15506  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
15507  * @irq: Interrupt number.
15508  * @dev_id: The device context pointer.
15509  *
15510  * This function is directly called from the PCI layer as an interrupt
15511  * service routine when device with SLI-4 interface spec is enabled with
15512  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
15513  * ring event in the HBA. However, when the device is enabled with either
15514  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
15515  * device-level interrupt handler. When the PCI slot is in error recovery
15516  * or the HBA is undergoing initialization, the interrupt handler will not
15517  * process the interrupt. The SCSI FCP fast-path ring event are handled in
15518  * the intrrupt context. This function is called without any lock held.
15519  * It gets the hbalock to access and update SLI data structures. Note that,
15520  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
15521  * equal to that of FCP CQ index.
15522  *
15523  * The link attention and ELS ring attention events are handled
15524  * by the worker thread. The interrupt handler signals the worker thread
15525  * and returns for these events. This function is called without any lock
15526  * held. It gets the hbalock to access and update SLI data structures.
15527  *
15528  * This function returns IRQ_HANDLED when interrupt is handled, IRQ_WAKE_THREAD
15529  * when interrupt is scheduled to be handled from a threaded irq context, or
15530  * else returns IRQ_NONE.
15531  **/
15532 irqreturn_t
15533 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
15534 {
15535 	struct lpfc_hba *phba;
15536 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
15537 	struct lpfc_queue *fpeq;
15538 	unsigned long iflag;
15539 	int hba_eqidx;
15540 	int ecount = 0;
15541 	struct lpfc_eq_intr_info *eqi;
15542 
15543 	/* Get the driver's phba structure from the dev_id */
15544 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
15545 	phba = hba_eq_hdl->phba;
15546 	hba_eqidx = hba_eq_hdl->idx;
15547 
15548 	if (unlikely(!phba))
15549 		return IRQ_NONE;
15550 	if (unlikely(!phba->sli4_hba.hdwq))
15551 		return IRQ_NONE;
15552 
15553 	/* Get to the EQ struct associated with this vector */
15554 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
15555 	if (unlikely(!fpeq))
15556 		return IRQ_NONE;
15557 
15558 	/* Check device state for handling interrupt */
15559 	if (unlikely(lpfc_intr_state_check(phba))) {
15560 		/* Check again for link_state with lock held */
15561 		spin_lock_irqsave(&phba->hbalock, iflag);
15562 		if (phba->link_state < LPFC_LINK_DOWN)
15563 			/* Flush, clear interrupt, and rearm the EQ */
15564 			lpfc_sli4_eqcq_flush(phba, fpeq);
15565 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15566 		return IRQ_NONE;
15567 	}
15568 
15569 	switch (fpeq->poll_mode) {
15570 	case LPFC_THREADED_IRQ:
15571 		/* CGN mgmt is mutually exclusive from irq processing */
15572 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
15573 			return IRQ_WAKE_THREAD;
15574 		fallthrough;
15575 	case LPFC_QUEUE_WORK:
15576 	default:
15577 		eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
15578 		eqi->icnt++;
15579 
15580 		fpeq->last_cpu = raw_smp_processor_id();
15581 
15582 		if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
15583 		    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
15584 		    phba->cfg_auto_imax &&
15585 		    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
15586 		    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
15587 			lpfc_sli4_mod_hba_eq_delay(phba, fpeq,
15588 						   LPFC_MAX_AUTO_EQ_DELAY);
15589 
15590 		/* process and rearm the EQ */
15591 		ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
15592 					      LPFC_QUEUE_WORK);
15593 
15594 		if (unlikely(ecount == 0)) {
15595 			fpeq->EQ_no_entry++;
15596 			if (phba->intr_type == MSIX)
15597 				/* MSI-X treated interrupt served as no EQ share INT */
15598 				lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15599 						"0358 MSI-X interrupt with no EQE\n");
15600 			else
15601 				/* Non MSI-X treated on interrupt as EQ share INT */
15602 				return IRQ_NONE;
15603 		}
15604 	}
15605 
15606 	return IRQ_HANDLED;
15607 } /* lpfc_sli4_hba_intr_handler */
15608 
15609 /**
15610  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
15611  * @irq: Interrupt number.
15612  * @dev_id: The device context pointer.
15613  *
15614  * This function is the device-level interrupt handler to device with SLI-4
15615  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
15616  * interrupt mode is enabled and there is an event in the HBA which requires
15617  * driver attention. This function invokes the slow-path interrupt attention
15618  * handling function and fast-path interrupt attention handling function in
15619  * turn to process the relevant HBA attention events. This function is called
15620  * without any lock held. It gets the hbalock to access and update SLI data
15621  * structures.
15622  *
15623  * This function returns IRQ_HANDLED when interrupt is handled, else it
15624  * returns IRQ_NONE.
15625  **/
15626 irqreturn_t
15627 lpfc_sli4_intr_handler(int irq, void *dev_id)
15628 {
15629 	struct lpfc_hba  *phba;
15630 	irqreturn_t hba_irq_rc;
15631 	bool hba_handled = false;
15632 	int qidx;
15633 
15634 	/* Get the driver's phba structure from the dev_id */
15635 	phba = (struct lpfc_hba *)dev_id;
15636 
15637 	if (unlikely(!phba))
15638 		return IRQ_NONE;
15639 
15640 	/*
15641 	 * Invoke fast-path host attention interrupt handling as appropriate.
15642 	 */
15643 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
15644 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
15645 					&phba->sli4_hba.hba_eq_hdl[qidx]);
15646 		if (hba_irq_rc == IRQ_HANDLED)
15647 			hba_handled |= true;
15648 	}
15649 
15650 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
15651 } /* lpfc_sli4_intr_handler */
15652 
15653 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
15654 {
15655 	struct lpfc_hba *phba = timer_container_of(phba, t, cpuhp_poll_timer);
15656 	struct lpfc_queue *eq;
15657 
15658 	rcu_read_lock();
15659 
15660 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
15661 		lpfc_sli4_poll_eq(eq);
15662 	if (!list_empty(&phba->poll_list))
15663 		mod_timer(&phba->cpuhp_poll_timer,
15664 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15665 
15666 	rcu_read_unlock();
15667 }
15668 
15669 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
15670 {
15671 	struct lpfc_hba *phba = eq->phba;
15672 
15673 	/* kickstart slowpath processing if needed */
15674 	if (list_empty(&phba->poll_list))
15675 		mod_timer(&phba->cpuhp_poll_timer,
15676 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15677 
15678 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
15679 	synchronize_rcu();
15680 }
15681 
15682 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
15683 {
15684 	struct lpfc_hba *phba = eq->phba;
15685 
15686 	/* Disable slowpath processing for this eq.  Kick start the eq
15687 	 * by RE-ARMING the eq's ASAP
15688 	 */
15689 	list_del_rcu(&eq->_poll_list);
15690 	synchronize_rcu();
15691 
15692 	if (list_empty(&phba->poll_list))
15693 		timer_delete_sync(&phba->cpuhp_poll_timer);
15694 }
15695 
15696 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
15697 {
15698 	struct lpfc_queue *eq, *next;
15699 
15700 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
15701 		list_del(&eq->_poll_list);
15702 
15703 	INIT_LIST_HEAD(&phba->poll_list);
15704 	synchronize_rcu();
15705 }
15706 
15707 static inline void
15708 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
15709 {
15710 	if (mode == eq->mode)
15711 		return;
15712 	/*
15713 	 * currently this function is only called during a hotplug
15714 	 * event and the cpu on which this function is executing
15715 	 * is going offline.  By now the hotplug has instructed
15716 	 * the scheduler to remove this cpu from cpu active mask.
15717 	 * So we don't need to work about being put aside by the
15718 	 * scheduler for a high priority process.  Yes, the inte-
15719 	 * rrupts could come but they are known to retire ASAP.
15720 	 */
15721 
15722 	/* Disable polling in the fastpath */
15723 	WRITE_ONCE(eq->mode, mode);
15724 	/* flush out the store buffer */
15725 	smp_wmb();
15726 
15727 	/*
15728 	 * Add this eq to the polling list and start polling. For
15729 	 * a grace period both interrupt handler and poller will
15730 	 * try to process the eq _but_ that's fine.  We have a
15731 	 * synchronization mechanism in place (queue_claimed) to
15732 	 * deal with it.  This is just a draining phase for int-
15733 	 * errupt handler (not eq's) as we have guranteed through
15734 	 * barrier that all the CPUs have seen the new CQ_POLLED
15735 	 * state. which will effectively disable the REARMING of
15736 	 * the EQ.  The whole idea is eq's die off eventually as
15737 	 * we are not rearming EQ's anymore.
15738 	 */
15739 	mode ? lpfc_sli4_add_to_poll_list(eq) :
15740 	       lpfc_sli4_remove_from_poll_list(eq);
15741 }
15742 
15743 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15744 {
15745 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15746 }
15747 
15748 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15749 {
15750 	struct lpfc_hba *phba = eq->phba;
15751 
15752 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15753 
15754 	/* Kick start for the pending io's in h/w.
15755 	 * Once we switch back to interrupt processing on a eq
15756 	 * the io path completion will only arm eq's when it
15757 	 * receives a completion.  But since eq's are in disa-
15758 	 * rmed state it doesn't receive a completion.  This
15759 	 * creates a deadlock scenaro.
15760 	 */
15761 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15762 }
15763 
15764 /**
15765  * lpfc_sli4_queue_free - free a queue structure and associated memory
15766  * @queue: The queue structure to free.
15767  *
15768  * This function frees a queue structure and the DMAable memory used for
15769  * the host resident queue. This function must be called after destroying the
15770  * queue on the HBA.
15771  **/
15772 void
15773 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15774 {
15775 	struct lpfc_dmabuf *dmabuf;
15776 
15777 	if (!queue)
15778 		return;
15779 
15780 	if (!list_empty(&queue->wq_list))
15781 		list_del(&queue->wq_list);
15782 
15783 	while (!list_empty(&queue->page_list)) {
15784 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15785 				 list);
15786 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15787 				  dmabuf->virt, dmabuf->phys);
15788 		kfree(dmabuf);
15789 	}
15790 	if (queue->rqbp) {
15791 		lpfc_free_rq_buffer(queue->phba, queue);
15792 		kfree(queue->rqbp);
15793 	}
15794 
15795 	if (!list_empty(&queue->cpu_list))
15796 		list_del(&queue->cpu_list);
15797 
15798 	kfree(queue);
15799 	return;
15800 }
15801 
15802 /**
15803  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15804  * @phba: The HBA that this queue is being created on.
15805  * @page_size: The size of a queue page
15806  * @entry_size: The size of each queue entry for this queue.
15807  * @entry_count: The number of entries that this queue will handle.
15808  * @cpu: The cpu that will primarily utilize this queue.
15809  *
15810  * This function allocates a queue structure and the DMAable memory used for
15811  * the host resident queue. This function must be called before creating the
15812  * queue on the HBA.
15813  **/
15814 struct lpfc_queue *
15815 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15816 		      uint32_t entry_size, uint32_t entry_count, int cpu)
15817 {
15818 	struct lpfc_queue *queue;
15819 	struct lpfc_dmabuf *dmabuf;
15820 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15821 	uint16_t x, pgcnt;
15822 
15823 	if (!phba->sli4_hba.pc_sli4_params.supported)
15824 		hw_page_size = page_size;
15825 
15826 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15827 
15828 	/* If needed, Adjust page count to match the max the adapter supports */
15829 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15830 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15831 
15832 	queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
15833 			     GFP_KERNEL, cpu_to_node(cpu));
15834 	if (!queue)
15835 		return NULL;
15836 
15837 	INIT_LIST_HEAD(&queue->list);
15838 	INIT_LIST_HEAD(&queue->_poll_list);
15839 	INIT_LIST_HEAD(&queue->wq_list);
15840 	INIT_LIST_HEAD(&queue->wqfull_list);
15841 	INIT_LIST_HEAD(&queue->page_list);
15842 	INIT_LIST_HEAD(&queue->child_list);
15843 	INIT_LIST_HEAD(&queue->cpu_list);
15844 
15845 	/* Set queue parameters now.  If the system cannot provide memory
15846 	 * resources, the free routine needs to know what was allocated.
15847 	 */
15848 	queue->page_count = pgcnt;
15849 	queue->q_pgs = (void **)&queue[1];
15850 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
15851 	queue->entry_size = entry_size;
15852 	queue->entry_count = entry_count;
15853 	queue->page_size = hw_page_size;
15854 	queue->phba = phba;
15855 
15856 	for (x = 0; x < queue->page_count; x++) {
15857 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15858 				      dev_to_node(&phba->pcidev->dev));
15859 		if (!dmabuf)
15860 			goto out_fail;
15861 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15862 						  hw_page_size, &dmabuf->phys,
15863 						  GFP_KERNEL);
15864 		if (!dmabuf->virt) {
15865 			kfree(dmabuf);
15866 			goto out_fail;
15867 		}
15868 		dmabuf->buffer_tag = x;
15869 		list_add_tail(&dmabuf->list, &queue->page_list);
15870 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
15871 		queue->q_pgs[x] = dmabuf->virt;
15872 	}
15873 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15874 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15875 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15876 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15877 
15878 	/* notify_interval will be set during q creation */
15879 
15880 	return queue;
15881 out_fail:
15882 	lpfc_sli4_queue_free(queue);
15883 	return NULL;
15884 }
15885 
15886 /**
15887  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15888  * @phba: HBA structure that indicates port to create a queue on.
15889  * @pci_barset: PCI BAR set flag.
15890  *
15891  * This function shall perform iomap of the specified PCI BAR address to host
15892  * memory address if not already done so and return it. The returned host
15893  * memory address can be NULL.
15894  */
15895 static void __iomem *
15896 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15897 {
15898 	if (!phba->pcidev)
15899 		return NULL;
15900 
15901 	switch (pci_barset) {
15902 	case WQ_PCI_BAR_0_AND_1:
15903 		return phba->pci_bar0_memmap_p;
15904 	case WQ_PCI_BAR_2_AND_3:
15905 		return phba->pci_bar2_memmap_p;
15906 	case WQ_PCI_BAR_4_AND_5:
15907 		return phba->pci_bar4_memmap_p;
15908 	default:
15909 		break;
15910 	}
15911 	return NULL;
15912 }
15913 
15914 /**
15915  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
15916  * @phba: HBA structure that EQs are on.
15917  * @startq: The starting EQ index to modify
15918  * @numq: The number of EQs (consecutive indexes) to modify
15919  * @usdelay: amount of delay
15920  *
15921  * This function revises the EQ delay on 1 or more EQs. The EQ delay
15922  * is set either by writing to a register (if supported by the SLI Port)
15923  * or by mailbox command. The mailbox command allows several EQs to be
15924  * updated at once.
15925  *
15926  * The @phba struct is used to send a mailbox command to HBA. The @startq
15927  * is used to get the starting EQ index to change. The @numq value is
15928  * used to specify how many consecutive EQ indexes, starting at EQ index,
15929  * are to be changed. This function is asynchronous and will wait for any
15930  * mailbox commands to finish before returning.
15931  *
15932  * On success this function will return a zero. If unable to allocate
15933  * enough memory this function will return -ENOMEM. If a mailbox command
15934  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
15935  * have had their delay multipler changed.
15936  **/
15937 void
15938 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
15939 			 uint32_t numq, uint32_t usdelay)
15940 {
15941 	struct lpfc_mbx_modify_eq_delay *eq_delay;
15942 	LPFC_MBOXQ_t *mbox;
15943 	struct lpfc_queue *eq;
15944 	int cnt = 0, rc, length;
15945 	uint32_t shdr_status, shdr_add_status;
15946 	uint32_t dmult;
15947 	int qidx;
15948 	union lpfc_sli4_cfg_shdr *shdr;
15949 
15950 	if (startq >= phba->cfg_irq_chann)
15951 		return;
15952 
15953 	if (usdelay > 0xFFFF) {
15954 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
15955 				"6429 usdelay %d too large. Scaled down to "
15956 				"0xFFFF.\n", usdelay);
15957 		usdelay = 0xFFFF;
15958 	}
15959 
15960 	/* set values by EQ_DELAY register if supported */
15961 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
15962 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15963 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15964 			if (!eq)
15965 				continue;
15966 
15967 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
15968 
15969 			if (++cnt >= numq)
15970 				break;
15971 		}
15972 		return;
15973 	}
15974 
15975 	/* Otherwise, set values by mailbox cmd */
15976 
15977 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15978 	if (!mbox) {
15979 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15980 				"6428 Failed allocating mailbox cmd buffer."
15981 				" EQ delay was not set.\n");
15982 		return;
15983 	}
15984 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
15985 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15986 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15987 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
15988 			 length, LPFC_SLI4_MBX_EMBED);
15989 	eq_delay = &mbox->u.mqe.un.eq_delay;
15990 
15991 	/* Calculate delay multiper from maximum interrupt per second */
15992 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
15993 	if (dmult)
15994 		dmult--;
15995 	if (dmult > LPFC_DMULT_MAX)
15996 		dmult = LPFC_DMULT_MAX;
15997 
15998 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15999 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
16000 		if (!eq)
16001 			continue;
16002 		eq->q_mode = usdelay;
16003 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
16004 		eq_delay->u.request.eq[cnt].phase = 0;
16005 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
16006 
16007 		if (++cnt >= numq)
16008 			break;
16009 	}
16010 	eq_delay->u.request.num_eq = cnt;
16011 
16012 	mbox->vport = phba->pport;
16013 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16014 	mbox->ctx_ndlp = NULL;
16015 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16016 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
16017 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16018 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16019 	if (shdr_status || shdr_add_status || rc) {
16020 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16021 				"2512 MODIFY_EQ_DELAY mailbox failed with "
16022 				"status x%x add_status x%x, mbx status x%x\n",
16023 				shdr_status, shdr_add_status, rc);
16024 	}
16025 	mempool_free(mbox, phba->mbox_mem_pool);
16026 	return;
16027 }
16028 
16029 /**
16030  * lpfc_eq_create - Create an Event Queue on the HBA
16031  * @phba: HBA structure that indicates port to create a queue on.
16032  * @eq: The queue structure to use to create the event queue.
16033  * @imax: The maximum interrupt per second limit.
16034  *
16035  * This function creates an event queue, as detailed in @eq, on a port,
16036  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
16037  *
16038  * The @phba struct is used to send mailbox command to HBA. The @eq struct
16039  * is used to get the entry count and entry size that are necessary to
16040  * determine the number of pages to allocate and use for this queue. This
16041  * function will send the EQ_CREATE mailbox command to the HBA to setup the
16042  * event queue. This function is asynchronous and will wait for the mailbox
16043  * command to finish before continuing.
16044  *
16045  * On success this function will return a zero. If unable to allocate enough
16046  * memory this function will return -ENOMEM. If the queue create mailbox command
16047  * fails this function will return -ENXIO.
16048  **/
16049 int
16050 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
16051 {
16052 	struct lpfc_mbx_eq_create *eq_create;
16053 	LPFC_MBOXQ_t *mbox;
16054 	int rc, length, status = 0;
16055 	struct lpfc_dmabuf *dmabuf;
16056 	uint32_t shdr_status, shdr_add_status;
16057 	union lpfc_sli4_cfg_shdr *shdr;
16058 	uint16_t dmult;
16059 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16060 
16061 	/* sanity check on queue memory */
16062 	if (!eq)
16063 		return -ENODEV;
16064 	if (!phba->sli4_hba.pc_sli4_params.supported)
16065 		hw_page_size = SLI4_PAGE_SIZE;
16066 
16067 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16068 	if (!mbox)
16069 		return -ENOMEM;
16070 	length = (sizeof(struct lpfc_mbx_eq_create) -
16071 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16072 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16073 			 LPFC_MBOX_OPCODE_EQ_CREATE,
16074 			 length, LPFC_SLI4_MBX_EMBED);
16075 	eq_create = &mbox->u.mqe.un.eq_create;
16076 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
16077 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
16078 	       eq->page_count);
16079 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
16080 	       LPFC_EQE_SIZE);
16081 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
16082 
16083 	/* Use version 2 of CREATE_EQ if eqav is set */
16084 	if (phba->sli4_hba.pc_sli4_params.eqav) {
16085 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16086 		       LPFC_Q_CREATE_VERSION_2);
16087 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
16088 		       phba->sli4_hba.pc_sli4_params.eqav);
16089 	}
16090 
16091 	/* don't setup delay multiplier using EQ_CREATE */
16092 	dmult = 0;
16093 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
16094 	       dmult);
16095 	switch (eq->entry_count) {
16096 	default:
16097 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16098 				"0360 Unsupported EQ count. (%d)\n",
16099 				eq->entry_count);
16100 		if (eq->entry_count < 256) {
16101 			status = -EINVAL;
16102 			goto out;
16103 		}
16104 		fallthrough;	/* otherwise default to smallest count */
16105 	case 256:
16106 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16107 		       LPFC_EQ_CNT_256);
16108 		break;
16109 	case 512:
16110 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16111 		       LPFC_EQ_CNT_512);
16112 		break;
16113 	case 1024:
16114 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16115 		       LPFC_EQ_CNT_1024);
16116 		break;
16117 	case 2048:
16118 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16119 		       LPFC_EQ_CNT_2048);
16120 		break;
16121 	case 4096:
16122 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16123 		       LPFC_EQ_CNT_4096);
16124 		break;
16125 	}
16126 	list_for_each_entry(dmabuf, &eq->page_list, list) {
16127 		memset(dmabuf->virt, 0, hw_page_size);
16128 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16129 					putPaddrLow(dmabuf->phys);
16130 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16131 					putPaddrHigh(dmabuf->phys);
16132 	}
16133 	mbox->vport = phba->pport;
16134 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16135 	mbox->ctx_buf = NULL;
16136 	mbox->ctx_ndlp = NULL;
16137 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16138 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16139 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16140 	if (shdr_status || shdr_add_status || rc) {
16141 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16142 				"2500 EQ_CREATE mailbox failed with "
16143 				"status x%x add_status x%x, mbx status x%x\n",
16144 				shdr_status, shdr_add_status, rc);
16145 		status = -ENXIO;
16146 	}
16147 	eq->type = LPFC_EQ;
16148 	eq->subtype = LPFC_NONE;
16149 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
16150 	if (eq->queue_id == 0xFFFF)
16151 		status = -ENXIO;
16152 	eq->host_index = 0;
16153 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
16154 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
16155 out:
16156 	mempool_free(mbox, phba->mbox_mem_pool);
16157 	return status;
16158 }
16159 
16160 /**
16161  * lpfc_sli4_hba_intr_handler_th - SLI4 HBA threaded interrupt handler
16162  * @irq: Interrupt number.
16163  * @dev_id: The device context pointer.
16164  *
16165  * This routine is a mirror of lpfc_sli4_hba_intr_handler, but executed within
16166  * threaded irq context.
16167  *
16168  * Returns
16169  * IRQ_HANDLED - interrupt is handled
16170  * IRQ_NONE - otherwise
16171  **/
16172 irqreturn_t lpfc_sli4_hba_intr_handler_th(int irq, void *dev_id)
16173 {
16174 	struct lpfc_hba *phba;
16175 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
16176 	struct lpfc_queue *fpeq;
16177 	int ecount = 0;
16178 	int hba_eqidx;
16179 	struct lpfc_eq_intr_info *eqi;
16180 
16181 	/* Get the driver's phba structure from the dev_id */
16182 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
16183 	phba = hba_eq_hdl->phba;
16184 	hba_eqidx = hba_eq_hdl->idx;
16185 
16186 	if (unlikely(!phba))
16187 		return IRQ_NONE;
16188 	if (unlikely(!phba->sli4_hba.hdwq))
16189 		return IRQ_NONE;
16190 
16191 	/* Get to the EQ struct associated with this vector */
16192 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
16193 	if (unlikely(!fpeq))
16194 		return IRQ_NONE;
16195 
16196 	eqi = per_cpu_ptr(phba->sli4_hba.eq_info, raw_smp_processor_id());
16197 	eqi->icnt++;
16198 
16199 	fpeq->last_cpu = raw_smp_processor_id();
16200 
16201 	if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
16202 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
16203 	    phba->cfg_auto_imax &&
16204 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
16205 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
16206 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
16207 
16208 	/* process and rearm the EQ */
16209 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
16210 				      LPFC_THREADED_IRQ);
16211 
16212 	if (unlikely(ecount == 0)) {
16213 		fpeq->EQ_no_entry++;
16214 		if (phba->intr_type == MSIX)
16215 			/* MSI-X treated interrupt served as no EQ share INT */
16216 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
16217 					"3358 MSI-X interrupt with no EQE\n");
16218 		else
16219 			/* Non MSI-X treated on interrupt as EQ share INT */
16220 			return IRQ_NONE;
16221 	}
16222 	return IRQ_HANDLED;
16223 }
16224 
16225 /**
16226  * lpfc_cq_create - Create a Completion Queue on the HBA
16227  * @phba: HBA structure that indicates port to create a queue on.
16228  * @cq: The queue structure to use to create the completion queue.
16229  * @eq: The event queue to bind this completion queue to.
16230  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16231  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16232  *
16233  * This function creates a completion queue, as detailed in @wq, on a port,
16234  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
16235  *
16236  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16237  * is used to get the entry count and entry size that are necessary to
16238  * determine the number of pages to allocate and use for this queue. The @eq
16239  * is used to indicate which event queue to bind this completion queue to. This
16240  * function will send the CQ_CREATE mailbox command to the HBA to setup the
16241  * completion queue. This function is asynchronous and will wait for the mailbox
16242  * command to finish before continuing.
16243  *
16244  * On success this function will return a zero. If unable to allocate enough
16245  * memory this function will return -ENOMEM. If the queue create mailbox command
16246  * fails this function will return -ENXIO.
16247  **/
16248 int
16249 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
16250 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
16251 {
16252 	struct lpfc_mbx_cq_create *cq_create;
16253 	struct lpfc_dmabuf *dmabuf;
16254 	LPFC_MBOXQ_t *mbox;
16255 	int rc, length, status = 0;
16256 	uint32_t shdr_status, shdr_add_status;
16257 	union lpfc_sli4_cfg_shdr *shdr;
16258 
16259 	/* sanity check on queue memory */
16260 	if (!cq || !eq)
16261 		return -ENODEV;
16262 
16263 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16264 	if (!mbox)
16265 		return -ENOMEM;
16266 	length = (sizeof(struct lpfc_mbx_cq_create) -
16267 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16268 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16269 			 LPFC_MBOX_OPCODE_CQ_CREATE,
16270 			 length, LPFC_SLI4_MBX_EMBED);
16271 	cq_create = &mbox->u.mqe.un.cq_create;
16272 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
16273 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
16274 		    cq->page_count);
16275 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
16276 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
16277 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16278 	       phba->sli4_hba.pc_sli4_params.cqv);
16279 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
16280 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
16281 		       (cq->page_size / SLI4_PAGE_SIZE));
16282 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
16283 		       eq->queue_id);
16284 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
16285 		       phba->sli4_hba.pc_sli4_params.cqav);
16286 	} else {
16287 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
16288 		       eq->queue_id);
16289 	}
16290 	switch (cq->entry_count) {
16291 	case 2048:
16292 	case 4096:
16293 		if (phba->sli4_hba.pc_sli4_params.cqv ==
16294 		    LPFC_Q_CREATE_VERSION_2) {
16295 			cq_create->u.request.context.lpfc_cq_context_count =
16296 				cq->entry_count;
16297 			bf_set(lpfc_cq_context_count,
16298 			       &cq_create->u.request.context,
16299 			       LPFC_CQ_CNT_WORD7);
16300 			break;
16301 		}
16302 		fallthrough;
16303 	default:
16304 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16305 				"0361 Unsupported CQ count: "
16306 				"entry cnt %d sz %d pg cnt %d\n",
16307 				cq->entry_count, cq->entry_size,
16308 				cq->page_count);
16309 		if (cq->entry_count < 256) {
16310 			status = -EINVAL;
16311 			goto out;
16312 		}
16313 		fallthrough;	/* otherwise default to smallest count */
16314 	case 256:
16315 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16316 		       LPFC_CQ_CNT_256);
16317 		break;
16318 	case 512:
16319 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16320 		       LPFC_CQ_CNT_512);
16321 		break;
16322 	case 1024:
16323 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16324 		       LPFC_CQ_CNT_1024);
16325 		break;
16326 	}
16327 	list_for_each_entry(dmabuf, &cq->page_list, list) {
16328 		memset(dmabuf->virt, 0, cq->page_size);
16329 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16330 					putPaddrLow(dmabuf->phys);
16331 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16332 					putPaddrHigh(dmabuf->phys);
16333 	}
16334 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16335 
16336 	/* The IOCTL status is embedded in the mailbox subheader. */
16337 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16338 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16339 	if (shdr_status || shdr_add_status || rc) {
16340 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16341 				"2501 CQ_CREATE mailbox failed with "
16342 				"status x%x add_status x%x, mbx status x%x\n",
16343 				shdr_status, shdr_add_status, rc);
16344 		status = -ENXIO;
16345 		goto out;
16346 	}
16347 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16348 	if (cq->queue_id == 0xFFFF) {
16349 		status = -ENXIO;
16350 		goto out;
16351 	}
16352 	/* link the cq onto the parent eq child list */
16353 	list_add_tail(&cq->list, &eq->child_list);
16354 	/* Set up completion queue's type and subtype */
16355 	cq->type = type;
16356 	cq->subtype = subtype;
16357 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16358 	cq->assoc_qid = eq->queue_id;
16359 	cq->assoc_qp = eq;
16360 	cq->host_index = 0;
16361 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16362 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
16363 
16364 	if (cq->queue_id > phba->sli4_hba.cq_max)
16365 		phba->sli4_hba.cq_max = cq->queue_id;
16366 out:
16367 	mempool_free(mbox, phba->mbox_mem_pool);
16368 	return status;
16369 }
16370 
16371 /**
16372  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
16373  * @phba: HBA structure that indicates port to create a queue on.
16374  * @cqp: The queue structure array to use to create the completion queues.
16375  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
16376  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16377  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16378  *
16379  * This function creates a set of  completion queue, s to support MRQ
16380  * as detailed in @cqp, on a port,
16381  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
16382  *
16383  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16384  * is used to get the entry count and entry size that are necessary to
16385  * determine the number of pages to allocate and use for this queue. The @eq
16386  * is used to indicate which event queue to bind this completion queue to. This
16387  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
16388  * completion queue. This function is asynchronous and will wait for the mailbox
16389  * command to finish before continuing.
16390  *
16391  * On success this function will return a zero. If unable to allocate enough
16392  * memory this function will return -ENOMEM. If the queue create mailbox command
16393  * fails this function will return -ENXIO.
16394  **/
16395 int
16396 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
16397 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
16398 		   uint32_t subtype)
16399 {
16400 	struct lpfc_queue *cq;
16401 	struct lpfc_queue *eq;
16402 	struct lpfc_mbx_cq_create_set *cq_set;
16403 	struct lpfc_dmabuf *dmabuf;
16404 	LPFC_MBOXQ_t *mbox;
16405 	int rc, length, alloclen, status = 0;
16406 	int cnt, idx, numcq, page_idx = 0;
16407 	uint32_t shdr_status, shdr_add_status;
16408 	union lpfc_sli4_cfg_shdr *shdr;
16409 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16410 
16411 	/* sanity check on queue memory */
16412 	numcq = phba->cfg_nvmet_mrq;
16413 	if (!cqp || !hdwq || !numcq)
16414 		return -ENODEV;
16415 
16416 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16417 	if (!mbox)
16418 		return -ENOMEM;
16419 
16420 	length = sizeof(struct lpfc_mbx_cq_create_set);
16421 	length += ((numcq * cqp[0]->page_count) *
16422 		   sizeof(struct dma_address));
16423 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16424 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
16425 			LPFC_SLI4_MBX_NEMBED);
16426 	if (alloclen < length) {
16427 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16428 				"3098 Allocated DMA memory size (%d) is "
16429 				"less than the requested DMA memory size "
16430 				"(%d)\n", alloclen, length);
16431 		status = -ENOMEM;
16432 		goto out;
16433 	}
16434 	cq_set = mbox->sge_array->addr[0];
16435 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
16436 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
16437 
16438 	for (idx = 0; idx < numcq; idx++) {
16439 		cq = cqp[idx];
16440 		eq = hdwq[idx].hba_eq;
16441 		if (!cq || !eq) {
16442 			status = -ENOMEM;
16443 			goto out;
16444 		}
16445 		if (!phba->sli4_hba.pc_sli4_params.supported)
16446 			hw_page_size = cq->page_size;
16447 
16448 		switch (idx) {
16449 		case 0:
16450 			bf_set(lpfc_mbx_cq_create_set_page_size,
16451 			       &cq_set->u.request,
16452 			       (hw_page_size / SLI4_PAGE_SIZE));
16453 			bf_set(lpfc_mbx_cq_create_set_num_pages,
16454 			       &cq_set->u.request, cq->page_count);
16455 			bf_set(lpfc_mbx_cq_create_set_evt,
16456 			       &cq_set->u.request, 1);
16457 			bf_set(lpfc_mbx_cq_create_set_valid,
16458 			       &cq_set->u.request, 1);
16459 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
16460 			       &cq_set->u.request, 0);
16461 			bf_set(lpfc_mbx_cq_create_set_num_cq,
16462 			       &cq_set->u.request, numcq);
16463 			bf_set(lpfc_mbx_cq_create_set_autovalid,
16464 			       &cq_set->u.request,
16465 			       phba->sli4_hba.pc_sli4_params.cqav);
16466 			switch (cq->entry_count) {
16467 			case 2048:
16468 			case 4096:
16469 				if (phba->sli4_hba.pc_sli4_params.cqv ==
16470 				    LPFC_Q_CREATE_VERSION_2) {
16471 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt_lo,
16472 					       &cq_set->u.request,
16473 					       cq->entry_count);
16474 					bf_set(lpfc_mbx_cq_create_set_cqecnt,
16475 					       &cq_set->u.request,
16476 					       LPFC_CQ_CNT_WORD7);
16477 					break;
16478 				}
16479 				fallthrough;
16480 			default:
16481 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16482 						"3118 Bad CQ count. (%d)\n",
16483 						cq->entry_count);
16484 				if (cq->entry_count < 256) {
16485 					status = -EINVAL;
16486 					goto out;
16487 				}
16488 				fallthrough;	/* otherwise default to smallest */
16489 			case 256:
16490 				bf_set(lpfc_mbx_cq_create_set_cqecnt,
16491 				       &cq_set->u.request, LPFC_CQ_CNT_256);
16492 				break;
16493 			case 512:
16494 				bf_set(lpfc_mbx_cq_create_set_cqecnt,
16495 				       &cq_set->u.request, LPFC_CQ_CNT_512);
16496 				break;
16497 			case 1024:
16498 				bf_set(lpfc_mbx_cq_create_set_cqecnt,
16499 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
16500 				break;
16501 			}
16502 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
16503 			       &cq_set->u.request, eq->queue_id);
16504 			break;
16505 		case 1:
16506 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
16507 			       &cq_set->u.request, eq->queue_id);
16508 			break;
16509 		case 2:
16510 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
16511 			       &cq_set->u.request, eq->queue_id);
16512 			break;
16513 		case 3:
16514 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
16515 			       &cq_set->u.request, eq->queue_id);
16516 			break;
16517 		case 4:
16518 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
16519 			       &cq_set->u.request, eq->queue_id);
16520 			break;
16521 		case 5:
16522 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
16523 			       &cq_set->u.request, eq->queue_id);
16524 			break;
16525 		case 6:
16526 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
16527 			       &cq_set->u.request, eq->queue_id);
16528 			break;
16529 		case 7:
16530 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
16531 			       &cq_set->u.request, eq->queue_id);
16532 			break;
16533 		case 8:
16534 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
16535 			       &cq_set->u.request, eq->queue_id);
16536 			break;
16537 		case 9:
16538 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
16539 			       &cq_set->u.request, eq->queue_id);
16540 			break;
16541 		case 10:
16542 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
16543 			       &cq_set->u.request, eq->queue_id);
16544 			break;
16545 		case 11:
16546 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
16547 			       &cq_set->u.request, eq->queue_id);
16548 			break;
16549 		case 12:
16550 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
16551 			       &cq_set->u.request, eq->queue_id);
16552 			break;
16553 		case 13:
16554 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
16555 			       &cq_set->u.request, eq->queue_id);
16556 			break;
16557 		case 14:
16558 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
16559 			       &cq_set->u.request, eq->queue_id);
16560 			break;
16561 		case 15:
16562 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
16563 			       &cq_set->u.request, eq->queue_id);
16564 			break;
16565 		}
16566 
16567 		/* link the cq onto the parent eq child list */
16568 		list_add_tail(&cq->list, &eq->child_list);
16569 		/* Set up completion queue's type and subtype */
16570 		cq->type = type;
16571 		cq->subtype = subtype;
16572 		cq->assoc_qid = eq->queue_id;
16573 		cq->assoc_qp = eq;
16574 		cq->host_index = 0;
16575 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16576 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
16577 					 cq->entry_count);
16578 		cq->chann = idx;
16579 
16580 		rc = 0;
16581 		list_for_each_entry(dmabuf, &cq->page_list, list) {
16582 			memset(dmabuf->virt, 0, hw_page_size);
16583 			cnt = page_idx + dmabuf->buffer_tag;
16584 			cq_set->u.request.page[cnt].addr_lo =
16585 					putPaddrLow(dmabuf->phys);
16586 			cq_set->u.request.page[cnt].addr_hi =
16587 					putPaddrHigh(dmabuf->phys);
16588 			rc++;
16589 		}
16590 		page_idx += rc;
16591 	}
16592 
16593 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16594 
16595 	/* The IOCTL status is embedded in the mailbox subheader. */
16596 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16597 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16598 	if (shdr_status || shdr_add_status || rc) {
16599 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16600 				"3119 CQ_CREATE_SET mailbox failed with "
16601 				"status x%x add_status x%x, mbx status x%x\n",
16602 				shdr_status, shdr_add_status, rc);
16603 		status = -ENXIO;
16604 		goto out;
16605 	}
16606 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
16607 	if (rc == 0xFFFF) {
16608 		status = -ENXIO;
16609 		goto out;
16610 	}
16611 
16612 	for (idx = 0; idx < numcq; idx++) {
16613 		cq = cqp[idx];
16614 		cq->queue_id = rc + idx;
16615 		if (cq->queue_id > phba->sli4_hba.cq_max)
16616 			phba->sli4_hba.cq_max = cq->queue_id;
16617 	}
16618 
16619 out:
16620 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16621 	return status;
16622 }
16623 
16624 /**
16625  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
16626  * @phba: HBA structure that indicates port to create a queue on.
16627  * @mq: The queue structure to use to create the mailbox queue.
16628  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
16629  * @cq: The completion queue to associate with this cq.
16630  *
16631  * This function provides failback (fb) functionality when the
16632  * mq_create_ext fails on older FW generations.  It's purpose is identical
16633  * to mq_create_ext otherwise.
16634  *
16635  * This routine cannot fail as all attributes were previously accessed and
16636  * initialized in mq_create_ext.
16637  **/
16638 static void
16639 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
16640 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
16641 {
16642 	struct lpfc_mbx_mq_create *mq_create;
16643 	struct lpfc_dmabuf *dmabuf;
16644 	int length;
16645 
16646 	length = (sizeof(struct lpfc_mbx_mq_create) -
16647 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16648 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16649 			 LPFC_MBOX_OPCODE_MQ_CREATE,
16650 			 length, LPFC_SLI4_MBX_EMBED);
16651 	mq_create = &mbox->u.mqe.un.mq_create;
16652 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
16653 	       mq->page_count);
16654 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
16655 	       cq->queue_id);
16656 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
16657 	switch (mq->entry_count) {
16658 	case 16:
16659 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16660 		       LPFC_MQ_RING_SIZE_16);
16661 		break;
16662 	case 32:
16663 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16664 		       LPFC_MQ_RING_SIZE_32);
16665 		break;
16666 	case 64:
16667 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16668 		       LPFC_MQ_RING_SIZE_64);
16669 		break;
16670 	case 128:
16671 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16672 		       LPFC_MQ_RING_SIZE_128);
16673 		break;
16674 	}
16675 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16676 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16677 			putPaddrLow(dmabuf->phys);
16678 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16679 			putPaddrHigh(dmabuf->phys);
16680 	}
16681 }
16682 
16683 /**
16684  * lpfc_mq_create - Create a mailbox Queue on the HBA
16685  * @phba: HBA structure that indicates port to create a queue on.
16686  * @mq: The queue structure to use to create the mailbox queue.
16687  * @cq: The completion queue to associate with this cq.
16688  * @subtype: The queue's subtype.
16689  *
16690  * This function creates a mailbox queue, as detailed in @mq, on a port,
16691  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
16692  *
16693  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16694  * is used to get the entry count and entry size that are necessary to
16695  * determine the number of pages to allocate and use for this queue. This
16696  * function will send the MQ_CREATE mailbox command to the HBA to setup the
16697  * mailbox queue. This function is asynchronous and will wait for the mailbox
16698  * command to finish before continuing.
16699  *
16700  * On success this function will return a zero. If unable to allocate enough
16701  * memory this function will return -ENOMEM. If the queue create mailbox command
16702  * fails this function will return -ENXIO.
16703  **/
16704 int32_t
16705 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
16706 	       struct lpfc_queue *cq, uint32_t subtype)
16707 {
16708 	struct lpfc_mbx_mq_create *mq_create;
16709 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
16710 	struct lpfc_dmabuf *dmabuf;
16711 	LPFC_MBOXQ_t *mbox;
16712 	int rc, length, status = 0;
16713 	uint32_t shdr_status, shdr_add_status;
16714 	union lpfc_sli4_cfg_shdr *shdr;
16715 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16716 
16717 	/* sanity check on queue memory */
16718 	if (!mq || !cq)
16719 		return -ENODEV;
16720 	if (!phba->sli4_hba.pc_sli4_params.supported)
16721 		hw_page_size = SLI4_PAGE_SIZE;
16722 
16723 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16724 	if (!mbox)
16725 		return -ENOMEM;
16726 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
16727 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16728 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16729 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
16730 			 length, LPFC_SLI4_MBX_EMBED);
16731 
16732 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
16733 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
16734 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
16735 	       &mq_create_ext->u.request, mq->page_count);
16736 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
16737 	       &mq_create_ext->u.request, 1);
16738 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
16739 	       &mq_create_ext->u.request, 1);
16740 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
16741 	       &mq_create_ext->u.request, 1);
16742 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
16743 	       &mq_create_ext->u.request, 1);
16744 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
16745 	       &mq_create_ext->u.request, 1);
16746 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
16747 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16748 	       phba->sli4_hba.pc_sli4_params.mqv);
16749 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
16750 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
16751 		       cq->queue_id);
16752 	else
16753 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
16754 		       cq->queue_id);
16755 	switch (mq->entry_count) {
16756 	default:
16757 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16758 				"0362 Unsupported MQ count. (%d)\n",
16759 				mq->entry_count);
16760 		if (mq->entry_count < 16) {
16761 			status = -EINVAL;
16762 			goto out;
16763 		}
16764 		fallthrough;	/* otherwise default to smallest count */
16765 	case 16:
16766 		bf_set(lpfc_mq_context_ring_size,
16767 		       &mq_create_ext->u.request.context,
16768 		       LPFC_MQ_RING_SIZE_16);
16769 		break;
16770 	case 32:
16771 		bf_set(lpfc_mq_context_ring_size,
16772 		       &mq_create_ext->u.request.context,
16773 		       LPFC_MQ_RING_SIZE_32);
16774 		break;
16775 	case 64:
16776 		bf_set(lpfc_mq_context_ring_size,
16777 		       &mq_create_ext->u.request.context,
16778 		       LPFC_MQ_RING_SIZE_64);
16779 		break;
16780 	case 128:
16781 		bf_set(lpfc_mq_context_ring_size,
16782 		       &mq_create_ext->u.request.context,
16783 		       LPFC_MQ_RING_SIZE_128);
16784 		break;
16785 	}
16786 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16787 		memset(dmabuf->virt, 0, hw_page_size);
16788 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16789 					putPaddrLow(dmabuf->phys);
16790 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16791 					putPaddrHigh(dmabuf->phys);
16792 	}
16793 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16794 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16795 			      &mq_create_ext->u.response);
16796 	if (rc != MBX_SUCCESS) {
16797 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16798 				"2795 MQ_CREATE_EXT failed with "
16799 				"status x%x. Failback to MQ_CREATE.\n",
16800 				rc);
16801 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16802 		mq_create = &mbox->u.mqe.un.mq_create;
16803 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16804 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16805 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16806 				      &mq_create->u.response);
16807 	}
16808 
16809 	/* The IOCTL status is embedded in the mailbox subheader. */
16810 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16811 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16812 	if (shdr_status || shdr_add_status || rc) {
16813 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16814 				"2502 MQ_CREATE mailbox failed with "
16815 				"status x%x add_status x%x, mbx status x%x\n",
16816 				shdr_status, shdr_add_status, rc);
16817 		status = -ENXIO;
16818 		goto out;
16819 	}
16820 	if (mq->queue_id == 0xFFFF) {
16821 		status = -ENXIO;
16822 		goto out;
16823 	}
16824 	mq->type = LPFC_MQ;
16825 	mq->assoc_qid = cq->queue_id;
16826 	mq->subtype = subtype;
16827 	mq->host_index = 0;
16828 	mq->hba_index = 0;
16829 
16830 	/* link the mq onto the parent cq child list */
16831 	list_add_tail(&mq->list, &cq->child_list);
16832 out:
16833 	mempool_free(mbox, phba->mbox_mem_pool);
16834 	return status;
16835 }
16836 
16837 /**
16838  * lpfc_wq_create - Create a Work Queue on the HBA
16839  * @phba: HBA structure that indicates port to create a queue on.
16840  * @wq: The queue structure to use to create the work queue.
16841  * @cq: The completion queue to bind this work queue to.
16842  * @subtype: The subtype of the work queue indicating its functionality.
16843  *
16844  * This function creates a work queue, as detailed in @wq, on a port, described
16845  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16846  *
16847  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16848  * is used to get the entry count and entry size that are necessary to
16849  * determine the number of pages to allocate and use for this queue. The @cq
16850  * is used to indicate which completion queue to bind this work queue to. This
16851  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16852  * work queue. This function is asynchronous and will wait for the mailbox
16853  * command to finish before continuing.
16854  *
16855  * On success this function will return a zero. If unable to allocate enough
16856  * memory this function will return -ENOMEM. If the queue create mailbox command
16857  * fails this function will return -ENXIO.
16858  **/
16859 int
16860 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16861 	       struct lpfc_queue *cq, uint32_t subtype)
16862 {
16863 	struct lpfc_mbx_wq_create *wq_create;
16864 	struct lpfc_dmabuf *dmabuf;
16865 	LPFC_MBOXQ_t *mbox;
16866 	int rc, length, status = 0;
16867 	uint32_t shdr_status, shdr_add_status;
16868 	union lpfc_sli4_cfg_shdr *shdr;
16869 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16870 	struct dma_address *page;
16871 	void __iomem *bar_memmap_p;
16872 	uint32_t db_offset;
16873 	uint16_t pci_barset;
16874 	uint8_t dpp_barset;
16875 	uint32_t dpp_offset;
16876 	uint8_t wq_create_version;
16877 #ifdef CONFIG_X86
16878 	unsigned long pg_addr;
16879 #endif
16880 
16881 	/* sanity check on queue memory */
16882 	if (!wq || !cq)
16883 		return -ENODEV;
16884 	if (!phba->sli4_hba.pc_sli4_params.supported)
16885 		hw_page_size = wq->page_size;
16886 
16887 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16888 	if (!mbox)
16889 		return -ENOMEM;
16890 	length = (sizeof(struct lpfc_mbx_wq_create) -
16891 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16892 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16893 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16894 			 length, LPFC_SLI4_MBX_EMBED);
16895 	wq_create = &mbox->u.mqe.un.wq_create;
16896 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16897 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16898 		    wq->page_count);
16899 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16900 		    cq->queue_id);
16901 
16902 	/* wqv is the earliest version supported, NOT the latest */
16903 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16904 	       phba->sli4_hba.pc_sli4_params.wqv);
16905 
16906 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16907 	    (wq->page_size > SLI4_PAGE_SIZE))
16908 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
16909 	else
16910 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
16911 
16912 	switch (wq_create_version) {
16913 	case LPFC_Q_CREATE_VERSION_1:
16914 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
16915 		       wq->entry_count);
16916 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16917 		       LPFC_Q_CREATE_VERSION_1);
16918 
16919 		switch (wq->entry_size) {
16920 		default:
16921 		case 64:
16922 			bf_set(lpfc_mbx_wq_create_wqe_size,
16923 			       &wq_create->u.request_1,
16924 			       LPFC_WQ_WQE_SIZE_64);
16925 			break;
16926 		case 128:
16927 			bf_set(lpfc_mbx_wq_create_wqe_size,
16928 			       &wq_create->u.request_1,
16929 			       LPFC_WQ_WQE_SIZE_128);
16930 			break;
16931 		}
16932 		/* Request DPP by default */
16933 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
16934 		bf_set(lpfc_mbx_wq_create_page_size,
16935 		       &wq_create->u.request_1,
16936 		       (wq->page_size / SLI4_PAGE_SIZE));
16937 		page = wq_create->u.request_1.page;
16938 		break;
16939 	default:
16940 		page = wq_create->u.request.page;
16941 		break;
16942 	}
16943 
16944 	list_for_each_entry(dmabuf, &wq->page_list, list) {
16945 		memset(dmabuf->virt, 0, hw_page_size);
16946 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
16947 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
16948 	}
16949 
16950 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16951 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
16952 
16953 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16954 	/* The IOCTL status is embedded in the mailbox subheader. */
16955 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16956 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16957 	if (shdr_status || shdr_add_status || rc) {
16958 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16959 				"2503 WQ_CREATE mailbox failed with "
16960 				"status x%x add_status x%x, mbx status x%x\n",
16961 				shdr_status, shdr_add_status, rc);
16962 		status = -ENXIO;
16963 		goto out;
16964 	}
16965 
16966 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
16967 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
16968 					&wq_create->u.response);
16969 	else
16970 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
16971 					&wq_create->u.response_1);
16972 
16973 	if (wq->queue_id == 0xFFFF) {
16974 		status = -ENXIO;
16975 		goto out;
16976 	}
16977 
16978 	wq->db_format = LPFC_DB_LIST_FORMAT;
16979 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
16980 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16981 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
16982 					       &wq_create->u.response);
16983 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
16984 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
16985 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16986 						"3265 WQ[%d] doorbell format "
16987 						"not supported: x%x\n",
16988 						wq->queue_id, wq->db_format);
16989 				status = -EINVAL;
16990 				goto out;
16991 			}
16992 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
16993 					    &wq_create->u.response);
16994 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16995 								   pci_barset);
16996 			if (!bar_memmap_p) {
16997 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16998 						"3263 WQ[%d] failed to memmap "
16999 						"pci barset:x%x\n",
17000 						wq->queue_id, pci_barset);
17001 				status = -ENOMEM;
17002 				goto out;
17003 			}
17004 			db_offset = wq_create->u.response.doorbell_offset;
17005 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
17006 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
17007 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17008 						"3252 WQ[%d] doorbell offset "
17009 						"not supported: x%x\n",
17010 						wq->queue_id, db_offset);
17011 				status = -EINVAL;
17012 				goto out;
17013 			}
17014 			wq->db_regaddr = bar_memmap_p + db_offset;
17015 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17016 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
17017 					"format:x%x\n", wq->queue_id,
17018 					pci_barset, db_offset, wq->db_format);
17019 		} else
17020 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17021 	} else {
17022 		/* Check if DPP was honored by the firmware */
17023 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
17024 				    &wq_create->u.response_1);
17025 		if (wq->dpp_enable) {
17026 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
17027 					    &wq_create->u.response_1);
17028 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17029 								   pci_barset);
17030 			if (!bar_memmap_p) {
17031 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17032 						"3267 WQ[%d] failed to memmap "
17033 						"pci barset:x%x\n",
17034 						wq->queue_id, pci_barset);
17035 				status = -ENOMEM;
17036 				goto out;
17037 			}
17038 			db_offset = wq_create->u.response_1.doorbell_offset;
17039 			wq->db_regaddr = bar_memmap_p + db_offset;
17040 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
17041 					    &wq_create->u.response_1);
17042 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
17043 					    &wq_create->u.response_1);
17044 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17045 								   dpp_barset);
17046 			if (!bar_memmap_p) {
17047 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17048 						"3268 WQ[%d] failed to memmap "
17049 						"pci barset:x%x\n",
17050 						wq->queue_id, dpp_barset);
17051 				status = -ENOMEM;
17052 				goto out;
17053 			}
17054 			dpp_offset = wq_create->u.response_1.dpp_offset;
17055 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
17056 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17057 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
17058 					"dpp_id:x%x dpp_barset:x%x "
17059 					"dpp_offset:x%x\n",
17060 					wq->queue_id, pci_barset, db_offset,
17061 					wq->dpp_id, dpp_barset, dpp_offset);
17062 
17063 #ifdef CONFIG_X86
17064 			/* Enable combined writes for DPP aperture */
17065 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
17066 			rc = set_memory_wc(pg_addr, 1);
17067 			if (rc) {
17068 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17069 					"3272 Cannot setup Combined "
17070 					"Write on WQ[%d] - disable DPP\n",
17071 					wq->queue_id);
17072 				phba->cfg_enable_dpp = 0;
17073 			}
17074 #else
17075 			phba->cfg_enable_dpp = 0;
17076 #endif
17077 		} else
17078 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17079 	}
17080 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
17081 	if (wq->pring == NULL) {
17082 		status = -ENOMEM;
17083 		goto out;
17084 	}
17085 	wq->type = LPFC_WQ;
17086 	wq->assoc_qid = cq->queue_id;
17087 	wq->subtype = subtype;
17088 	wq->host_index = 0;
17089 	wq->hba_index = 0;
17090 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
17091 
17092 	/* link the wq onto the parent cq child list */
17093 	list_add_tail(&wq->list, &cq->child_list);
17094 out:
17095 	mempool_free(mbox, phba->mbox_mem_pool);
17096 	return status;
17097 }
17098 
17099 /**
17100  * lpfc_rq_create - Create a Receive Queue on the HBA
17101  * @phba: HBA structure that indicates port to create a queue on.
17102  * @hrq: The queue structure to use to create the header receive queue.
17103  * @drq: The queue structure to use to create the data receive queue.
17104  * @cq: The completion queue to bind this work queue to.
17105  * @subtype: The subtype of the work queue indicating its functionality.
17106  *
17107  * This function creates a receive buffer queue pair , as detailed in @hrq and
17108  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17109  * to the HBA.
17110  *
17111  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17112  * struct is used to get the entry count that is necessary to determine the
17113  * number of pages to use for this queue. The @cq is used to indicate which
17114  * completion queue to bind received buffers that are posted to these queues to.
17115  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17116  * receive queue pair. This function is asynchronous and will wait for the
17117  * mailbox command to finish before continuing.
17118  *
17119  * On success this function will return a zero. If unable to allocate enough
17120  * memory this function will return -ENOMEM. If the queue create mailbox command
17121  * fails this function will return -ENXIO.
17122  **/
17123 int
17124 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17125 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
17126 {
17127 	struct lpfc_mbx_rq_create *rq_create;
17128 	struct lpfc_dmabuf *dmabuf;
17129 	LPFC_MBOXQ_t *mbox;
17130 	int rc, length, status = 0;
17131 	uint32_t shdr_status, shdr_add_status;
17132 	union lpfc_sli4_cfg_shdr *shdr;
17133 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17134 	void __iomem *bar_memmap_p;
17135 	uint32_t db_offset;
17136 	uint16_t pci_barset;
17137 
17138 	/* sanity check on queue memory */
17139 	if (!hrq || !drq || !cq)
17140 		return -ENODEV;
17141 	if (!phba->sli4_hba.pc_sli4_params.supported)
17142 		hw_page_size = SLI4_PAGE_SIZE;
17143 
17144 	if (hrq->entry_count != drq->entry_count)
17145 		return -EINVAL;
17146 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17147 	if (!mbox)
17148 		return -ENOMEM;
17149 	length = (sizeof(struct lpfc_mbx_rq_create) -
17150 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17151 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17152 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17153 			 length, LPFC_SLI4_MBX_EMBED);
17154 	rq_create = &mbox->u.mqe.un.rq_create;
17155 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17156 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17157 	       phba->sli4_hba.pc_sli4_params.rqv);
17158 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17159 		bf_set(lpfc_rq_context_rqe_count_1,
17160 		       &rq_create->u.request.context,
17161 		       hrq->entry_count);
17162 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
17163 		bf_set(lpfc_rq_context_rqe_size,
17164 		       &rq_create->u.request.context,
17165 		       LPFC_RQE_SIZE_8);
17166 		bf_set(lpfc_rq_context_page_size,
17167 		       &rq_create->u.request.context,
17168 		       LPFC_RQ_PAGE_SIZE_4096);
17169 	} else {
17170 		switch (hrq->entry_count) {
17171 		default:
17172 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17173 					"2535 Unsupported RQ count. (%d)\n",
17174 					hrq->entry_count);
17175 			if (hrq->entry_count < 512) {
17176 				status = -EINVAL;
17177 				goto out;
17178 			}
17179 			fallthrough;	/* otherwise default to smallest count */
17180 		case 512:
17181 			bf_set(lpfc_rq_context_rqe_count,
17182 			       &rq_create->u.request.context,
17183 			       LPFC_RQ_RING_SIZE_512);
17184 			break;
17185 		case 1024:
17186 			bf_set(lpfc_rq_context_rqe_count,
17187 			       &rq_create->u.request.context,
17188 			       LPFC_RQ_RING_SIZE_1024);
17189 			break;
17190 		case 2048:
17191 			bf_set(lpfc_rq_context_rqe_count,
17192 			       &rq_create->u.request.context,
17193 			       LPFC_RQ_RING_SIZE_2048);
17194 			break;
17195 		case 4096:
17196 			bf_set(lpfc_rq_context_rqe_count,
17197 			       &rq_create->u.request.context,
17198 			       LPFC_RQ_RING_SIZE_4096);
17199 			break;
17200 		}
17201 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
17202 		       LPFC_HDR_BUF_SIZE);
17203 	}
17204 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17205 	       cq->queue_id);
17206 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17207 	       hrq->page_count);
17208 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
17209 		memset(dmabuf->virt, 0, hw_page_size);
17210 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17211 					putPaddrLow(dmabuf->phys);
17212 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17213 					putPaddrHigh(dmabuf->phys);
17214 	}
17215 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17216 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17217 
17218 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17219 	/* The IOCTL status is embedded in the mailbox subheader. */
17220 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17221 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17222 	if (shdr_status || shdr_add_status || rc) {
17223 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17224 				"2504 RQ_CREATE mailbox failed with "
17225 				"status x%x add_status x%x, mbx status x%x\n",
17226 				shdr_status, shdr_add_status, rc);
17227 		status = -ENXIO;
17228 		goto out;
17229 	}
17230 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17231 	if (hrq->queue_id == 0xFFFF) {
17232 		status = -ENXIO;
17233 		goto out;
17234 	}
17235 
17236 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
17237 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
17238 					&rq_create->u.response);
17239 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
17240 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
17241 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17242 					"3262 RQ [%d] doorbell format not "
17243 					"supported: x%x\n", hrq->queue_id,
17244 					hrq->db_format);
17245 			status = -EINVAL;
17246 			goto out;
17247 		}
17248 
17249 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
17250 				    &rq_create->u.response);
17251 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
17252 		if (!bar_memmap_p) {
17253 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17254 					"3269 RQ[%d] failed to memmap pci "
17255 					"barset:x%x\n", hrq->queue_id,
17256 					pci_barset);
17257 			status = -ENOMEM;
17258 			goto out;
17259 		}
17260 
17261 		db_offset = rq_create->u.response.doorbell_offset;
17262 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
17263 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
17264 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17265 					"3270 RQ[%d] doorbell offset not "
17266 					"supported: x%x\n", hrq->queue_id,
17267 					db_offset);
17268 			status = -EINVAL;
17269 			goto out;
17270 		}
17271 		hrq->db_regaddr = bar_memmap_p + db_offset;
17272 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17273 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
17274 				"format:x%x\n", hrq->queue_id, pci_barset,
17275 				db_offset, hrq->db_format);
17276 	} else {
17277 		hrq->db_format = LPFC_DB_RING_FORMAT;
17278 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17279 	}
17280 	hrq->type = LPFC_HRQ;
17281 	hrq->assoc_qid = cq->queue_id;
17282 	hrq->subtype = subtype;
17283 	hrq->host_index = 0;
17284 	hrq->hba_index = 0;
17285 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17286 
17287 	/* now create the data queue */
17288 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17289 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17290 			 length, LPFC_SLI4_MBX_EMBED);
17291 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17292 	       phba->sli4_hba.pc_sli4_params.rqv);
17293 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17294 		bf_set(lpfc_rq_context_rqe_count_1,
17295 		       &rq_create->u.request.context, hrq->entry_count);
17296 		if (subtype == LPFC_NVMET)
17297 			rq_create->u.request.context.buffer_size =
17298 				LPFC_NVMET_DATA_BUF_SIZE;
17299 		else
17300 			rq_create->u.request.context.buffer_size =
17301 				LPFC_DATA_BUF_SIZE;
17302 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
17303 		       LPFC_RQE_SIZE_8);
17304 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
17305 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
17306 	} else {
17307 		switch (drq->entry_count) {
17308 		default:
17309 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17310 					"2536 Unsupported RQ count. (%d)\n",
17311 					drq->entry_count);
17312 			if (drq->entry_count < 512) {
17313 				status = -EINVAL;
17314 				goto out;
17315 			}
17316 			fallthrough;	/* otherwise default to smallest count */
17317 		case 512:
17318 			bf_set(lpfc_rq_context_rqe_count,
17319 			       &rq_create->u.request.context,
17320 			       LPFC_RQ_RING_SIZE_512);
17321 			break;
17322 		case 1024:
17323 			bf_set(lpfc_rq_context_rqe_count,
17324 			       &rq_create->u.request.context,
17325 			       LPFC_RQ_RING_SIZE_1024);
17326 			break;
17327 		case 2048:
17328 			bf_set(lpfc_rq_context_rqe_count,
17329 			       &rq_create->u.request.context,
17330 			       LPFC_RQ_RING_SIZE_2048);
17331 			break;
17332 		case 4096:
17333 			bf_set(lpfc_rq_context_rqe_count,
17334 			       &rq_create->u.request.context,
17335 			       LPFC_RQ_RING_SIZE_4096);
17336 			break;
17337 		}
17338 		if (subtype == LPFC_NVMET)
17339 			bf_set(lpfc_rq_context_buf_size,
17340 			       &rq_create->u.request.context,
17341 			       LPFC_NVMET_DATA_BUF_SIZE);
17342 		else
17343 			bf_set(lpfc_rq_context_buf_size,
17344 			       &rq_create->u.request.context,
17345 			       LPFC_DATA_BUF_SIZE);
17346 	}
17347 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17348 	       cq->queue_id);
17349 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17350 	       drq->page_count);
17351 	list_for_each_entry(dmabuf, &drq->page_list, list) {
17352 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17353 					putPaddrLow(dmabuf->phys);
17354 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17355 					putPaddrHigh(dmabuf->phys);
17356 	}
17357 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17358 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17359 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17360 	/* The IOCTL status is embedded in the mailbox subheader. */
17361 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17362 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17363 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17364 	if (shdr_status || shdr_add_status || rc) {
17365 		status = -ENXIO;
17366 		goto out;
17367 	}
17368 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17369 	if (drq->queue_id == 0xFFFF) {
17370 		status = -ENXIO;
17371 		goto out;
17372 	}
17373 	drq->type = LPFC_DRQ;
17374 	drq->assoc_qid = cq->queue_id;
17375 	drq->subtype = subtype;
17376 	drq->host_index = 0;
17377 	drq->hba_index = 0;
17378 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17379 
17380 	/* link the header and data RQs onto the parent cq child list */
17381 	list_add_tail(&hrq->list, &cq->child_list);
17382 	list_add_tail(&drq->list, &cq->child_list);
17383 
17384 out:
17385 	mempool_free(mbox, phba->mbox_mem_pool);
17386 	return status;
17387 }
17388 
17389 /**
17390  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
17391  * @phba: HBA structure that indicates port to create a queue on.
17392  * @hrqp: The queue structure array to use to create the header receive queues.
17393  * @drqp: The queue structure array to use to create the data receive queues.
17394  * @cqp: The completion queue array to bind these receive queues to.
17395  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
17396  *
17397  * This function creates a receive buffer queue pair , as detailed in @hrq and
17398  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17399  * to the HBA.
17400  *
17401  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17402  * struct is used to get the entry count that is necessary to determine the
17403  * number of pages to use for this queue. The @cq is used to indicate which
17404  * completion queue to bind received buffers that are posted to these queues to.
17405  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17406  * receive queue pair. This function is asynchronous and will wait for the
17407  * mailbox command to finish before continuing.
17408  *
17409  * On success this function will return a zero. If unable to allocate enough
17410  * memory this function will return -ENOMEM. If the queue create mailbox command
17411  * fails this function will return -ENXIO.
17412  **/
17413 int
17414 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
17415 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
17416 		uint32_t subtype)
17417 {
17418 	struct lpfc_queue *hrq, *drq, *cq;
17419 	struct lpfc_mbx_rq_create_v2 *rq_create;
17420 	struct lpfc_dmabuf *dmabuf;
17421 	LPFC_MBOXQ_t *mbox;
17422 	int rc, length, alloclen, status = 0;
17423 	int cnt, idx, numrq, page_idx = 0;
17424 	uint32_t shdr_status, shdr_add_status;
17425 	union lpfc_sli4_cfg_shdr *shdr;
17426 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17427 
17428 	numrq = phba->cfg_nvmet_mrq;
17429 	/* sanity check on array memory */
17430 	if (!hrqp || !drqp || !cqp || !numrq)
17431 		return -ENODEV;
17432 	if (!phba->sli4_hba.pc_sli4_params.supported)
17433 		hw_page_size = SLI4_PAGE_SIZE;
17434 
17435 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17436 	if (!mbox)
17437 		return -ENOMEM;
17438 
17439 	length = sizeof(struct lpfc_mbx_rq_create_v2);
17440 	length += ((2 * numrq * hrqp[0]->page_count) *
17441 		   sizeof(struct dma_address));
17442 
17443 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17444 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
17445 				    LPFC_SLI4_MBX_NEMBED);
17446 	if (alloclen < length) {
17447 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17448 				"3099 Allocated DMA memory size (%d) is "
17449 				"less than the requested DMA memory size "
17450 				"(%d)\n", alloclen, length);
17451 		status = -ENOMEM;
17452 		goto out;
17453 	}
17454 
17455 
17456 
17457 	rq_create = mbox->sge_array->addr[0];
17458 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
17459 
17460 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
17461 	cnt = 0;
17462 
17463 	for (idx = 0; idx < numrq; idx++) {
17464 		hrq = hrqp[idx];
17465 		drq = drqp[idx];
17466 		cq  = cqp[idx];
17467 
17468 		/* sanity check on queue memory */
17469 		if (!hrq || !drq || !cq) {
17470 			status = -ENODEV;
17471 			goto out;
17472 		}
17473 
17474 		if (hrq->entry_count != drq->entry_count) {
17475 			status = -EINVAL;
17476 			goto out;
17477 		}
17478 
17479 		if (idx == 0) {
17480 			bf_set(lpfc_mbx_rq_create_num_pages,
17481 			       &rq_create->u.request,
17482 			       hrq->page_count);
17483 			bf_set(lpfc_mbx_rq_create_rq_cnt,
17484 			       &rq_create->u.request, (numrq * 2));
17485 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
17486 			       1);
17487 			bf_set(lpfc_rq_context_base_cq,
17488 			       &rq_create->u.request.context,
17489 			       cq->queue_id);
17490 			bf_set(lpfc_rq_context_data_size,
17491 			       &rq_create->u.request.context,
17492 			       LPFC_NVMET_DATA_BUF_SIZE);
17493 			bf_set(lpfc_rq_context_hdr_size,
17494 			       &rq_create->u.request.context,
17495 			       LPFC_HDR_BUF_SIZE);
17496 			bf_set(lpfc_rq_context_rqe_count_1,
17497 			       &rq_create->u.request.context,
17498 			       hrq->entry_count);
17499 			bf_set(lpfc_rq_context_rqe_size,
17500 			       &rq_create->u.request.context,
17501 			       LPFC_RQE_SIZE_8);
17502 			bf_set(lpfc_rq_context_page_size,
17503 			       &rq_create->u.request.context,
17504 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
17505 		}
17506 		rc = 0;
17507 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
17508 			memset(dmabuf->virt, 0, hw_page_size);
17509 			cnt = page_idx + dmabuf->buffer_tag;
17510 			rq_create->u.request.page[cnt].addr_lo =
17511 					putPaddrLow(dmabuf->phys);
17512 			rq_create->u.request.page[cnt].addr_hi =
17513 					putPaddrHigh(dmabuf->phys);
17514 			rc++;
17515 		}
17516 		page_idx += rc;
17517 
17518 		rc = 0;
17519 		list_for_each_entry(dmabuf, &drq->page_list, list) {
17520 			memset(dmabuf->virt, 0, hw_page_size);
17521 			cnt = page_idx + dmabuf->buffer_tag;
17522 			rq_create->u.request.page[cnt].addr_lo =
17523 					putPaddrLow(dmabuf->phys);
17524 			rq_create->u.request.page[cnt].addr_hi =
17525 					putPaddrHigh(dmabuf->phys);
17526 			rc++;
17527 		}
17528 		page_idx += rc;
17529 
17530 		hrq->db_format = LPFC_DB_RING_FORMAT;
17531 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17532 		hrq->type = LPFC_HRQ;
17533 		hrq->assoc_qid = cq->queue_id;
17534 		hrq->subtype = subtype;
17535 		hrq->host_index = 0;
17536 		hrq->hba_index = 0;
17537 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17538 
17539 		drq->db_format = LPFC_DB_RING_FORMAT;
17540 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17541 		drq->type = LPFC_DRQ;
17542 		drq->assoc_qid = cq->queue_id;
17543 		drq->subtype = subtype;
17544 		drq->host_index = 0;
17545 		drq->hba_index = 0;
17546 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17547 
17548 		list_add_tail(&hrq->list, &cq->child_list);
17549 		list_add_tail(&drq->list, &cq->child_list);
17550 	}
17551 
17552 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17553 	/* The IOCTL status is embedded in the mailbox subheader. */
17554 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17555 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17556 	if (shdr_status || shdr_add_status || rc) {
17557 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17558 				"3120 RQ_CREATE mailbox failed with "
17559 				"status x%x add_status x%x, mbx status x%x\n",
17560 				shdr_status, shdr_add_status, rc);
17561 		status = -ENXIO;
17562 		goto out;
17563 	}
17564 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17565 	if (rc == 0xFFFF) {
17566 		status = -ENXIO;
17567 		goto out;
17568 	}
17569 
17570 	/* Initialize all RQs with associated queue id */
17571 	for (idx = 0; idx < numrq; idx++) {
17572 		hrq = hrqp[idx];
17573 		hrq->queue_id = rc + (2 * idx);
17574 		drq = drqp[idx];
17575 		drq->queue_id = rc + (2 * idx) + 1;
17576 	}
17577 
17578 out:
17579 	lpfc_sli4_mbox_cmd_free(phba, mbox);
17580 	return status;
17581 }
17582 
17583 /**
17584  * lpfc_eq_destroy - Destroy an event Queue on the HBA
17585  * @phba: HBA structure that indicates port to destroy a queue on.
17586  * @eq: The queue structure associated with the queue to destroy.
17587  *
17588  * This function destroys a queue, as detailed in @eq by sending an mailbox
17589  * command, specific to the type of queue, to the HBA.
17590  *
17591  * The @eq struct is used to get the queue ID of the queue to destroy.
17592  *
17593  * On success this function will return a zero. If the queue destroy mailbox
17594  * command fails this function will return -ENXIO.
17595  **/
17596 int
17597 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
17598 {
17599 	LPFC_MBOXQ_t *mbox;
17600 	int rc, length, status = 0;
17601 	uint32_t shdr_status, shdr_add_status;
17602 	union lpfc_sli4_cfg_shdr *shdr;
17603 
17604 	/* sanity check on queue memory */
17605 	if (!eq)
17606 		return -ENODEV;
17607 
17608 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17609 		goto list_remove;
17610 
17611 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
17612 	if (!mbox)
17613 		return -ENOMEM;
17614 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
17615 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17616 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17617 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
17618 			 length, LPFC_SLI4_MBX_EMBED);
17619 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
17620 	       eq->queue_id);
17621 	mbox->vport = eq->phba->pport;
17622 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17623 
17624 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
17625 	/* The IOCTL status is embedded in the mailbox subheader. */
17626 	shdr = (union lpfc_sli4_cfg_shdr *)
17627 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
17628 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17629 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17630 	if (shdr_status || shdr_add_status || rc) {
17631 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17632 				"2505 EQ_DESTROY mailbox failed with "
17633 				"status x%x add_status x%x, mbx status x%x\n",
17634 				shdr_status, shdr_add_status, rc);
17635 		status = -ENXIO;
17636 	}
17637 	mempool_free(mbox, eq->phba->mbox_mem_pool);
17638 
17639 list_remove:
17640 	/* Remove eq from any list */
17641 	list_del_init(&eq->list);
17642 
17643 	return status;
17644 }
17645 
17646 /**
17647  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
17648  * @phba: HBA structure that indicates port to destroy a queue on.
17649  * @cq: The queue structure associated with the queue to destroy.
17650  *
17651  * This function destroys a queue, as detailed in @cq by sending an mailbox
17652  * command, specific to the type of queue, to the HBA.
17653  *
17654  * The @cq struct is used to get the queue ID of the queue to destroy.
17655  *
17656  * On success this function will return a zero. If the queue destroy mailbox
17657  * command fails this function will return -ENXIO.
17658  **/
17659 int
17660 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
17661 {
17662 	LPFC_MBOXQ_t *mbox;
17663 	int rc, length, status = 0;
17664 	uint32_t shdr_status, shdr_add_status;
17665 	union lpfc_sli4_cfg_shdr *shdr;
17666 
17667 	/* sanity check on queue memory */
17668 	if (!cq)
17669 		return -ENODEV;
17670 
17671 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17672 		goto list_remove;
17673 
17674 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
17675 	if (!mbox)
17676 		return -ENOMEM;
17677 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
17678 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17679 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17680 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
17681 			 length, LPFC_SLI4_MBX_EMBED);
17682 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
17683 	       cq->queue_id);
17684 	mbox->vport = cq->phba->pport;
17685 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17686 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
17687 	/* The IOCTL status is embedded in the mailbox subheader. */
17688 	shdr = (union lpfc_sli4_cfg_shdr *)
17689 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
17690 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17691 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17692 	if (shdr_status || shdr_add_status || rc) {
17693 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17694 				"2506 CQ_DESTROY mailbox failed with "
17695 				"status x%x add_status x%x, mbx status x%x\n",
17696 				shdr_status, shdr_add_status, rc);
17697 		status = -ENXIO;
17698 	}
17699 	mempool_free(mbox, cq->phba->mbox_mem_pool);
17700 
17701 list_remove:
17702 	/* Remove cq from any list */
17703 	list_del_init(&cq->list);
17704 	return status;
17705 }
17706 
17707 /**
17708  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
17709  * @phba: HBA structure that indicates port to destroy a queue on.
17710  * @mq: The queue structure associated with the queue to destroy.
17711  *
17712  * This function destroys a queue, as detailed in @mq by sending an mailbox
17713  * command, specific to the type of queue, to the HBA.
17714  *
17715  * The @mq struct is used to get the queue ID of the queue to destroy.
17716  *
17717  * On success this function will return a zero. If the queue destroy mailbox
17718  * command fails this function will return -ENXIO.
17719  **/
17720 int
17721 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
17722 {
17723 	LPFC_MBOXQ_t *mbox;
17724 	int rc, length, status = 0;
17725 	uint32_t shdr_status, shdr_add_status;
17726 	union lpfc_sli4_cfg_shdr *shdr;
17727 
17728 	/* sanity check on queue memory */
17729 	if (!mq)
17730 		return -ENODEV;
17731 
17732 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17733 		goto list_remove;
17734 
17735 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
17736 	if (!mbox)
17737 		return -ENOMEM;
17738 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
17739 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17740 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17741 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
17742 			 length, LPFC_SLI4_MBX_EMBED);
17743 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
17744 	       mq->queue_id);
17745 	mbox->vport = mq->phba->pport;
17746 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17747 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
17748 	/* The IOCTL status is embedded in the mailbox subheader. */
17749 	shdr = (union lpfc_sli4_cfg_shdr *)
17750 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
17751 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17752 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17753 	if (shdr_status || shdr_add_status || rc) {
17754 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17755 				"2507 MQ_DESTROY mailbox failed with "
17756 				"status x%x add_status x%x, mbx status x%x\n",
17757 				shdr_status, shdr_add_status, rc);
17758 		status = -ENXIO;
17759 	}
17760 	mempool_free(mbox, mq->phba->mbox_mem_pool);
17761 
17762 list_remove:
17763 	/* Remove mq from any list */
17764 	list_del_init(&mq->list);
17765 	return status;
17766 }
17767 
17768 /**
17769  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
17770  * @phba: HBA structure that indicates port to destroy a queue on.
17771  * @wq: The queue structure associated with the queue to destroy.
17772  *
17773  * This function destroys a queue, as detailed in @wq by sending an mailbox
17774  * command, specific to the type of queue, to the HBA.
17775  *
17776  * The @wq struct is used to get the queue ID of the queue to destroy.
17777  *
17778  * On success this function will return a zero. If the queue destroy mailbox
17779  * command fails this function will return -ENXIO.
17780  **/
17781 int
17782 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
17783 {
17784 	LPFC_MBOXQ_t *mbox;
17785 	int rc, length, status = 0;
17786 	uint32_t shdr_status, shdr_add_status;
17787 	union lpfc_sli4_cfg_shdr *shdr;
17788 
17789 	/* sanity check on queue memory */
17790 	if (!wq)
17791 		return -ENODEV;
17792 
17793 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17794 		goto list_remove;
17795 
17796 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17797 	if (!mbox)
17798 		return -ENOMEM;
17799 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
17800 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17801 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17802 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17803 			 length, LPFC_SLI4_MBX_EMBED);
17804 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17805 	       wq->queue_id);
17806 	mbox->vport = wq->phba->pport;
17807 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17808 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17809 	shdr = (union lpfc_sli4_cfg_shdr *)
17810 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17811 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17812 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17813 	if (shdr_status || shdr_add_status || rc) {
17814 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17815 				"2508 WQ_DESTROY mailbox failed with "
17816 				"status x%x add_status x%x, mbx status x%x\n",
17817 				shdr_status, shdr_add_status, rc);
17818 		status = -ENXIO;
17819 	}
17820 	mempool_free(mbox, wq->phba->mbox_mem_pool);
17821 
17822 list_remove:
17823 	/* Remove wq from any list */
17824 	list_del_init(&wq->list);
17825 	kfree(wq->pring);
17826 	wq->pring = NULL;
17827 	return status;
17828 }
17829 
17830 /**
17831  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17832  * @phba: HBA structure that indicates port to destroy a queue on.
17833  * @hrq: The queue structure associated with the queue to destroy.
17834  * @drq: The queue structure associated with the queue to destroy.
17835  *
17836  * This function destroys a queue, as detailed in @rq by sending an mailbox
17837  * command, specific to the type of queue, to the HBA.
17838  *
17839  * The @rq struct is used to get the queue ID of the queue to destroy.
17840  *
17841  * On success this function will return a zero. If the queue destroy mailbox
17842  * command fails this function will return -ENXIO.
17843  **/
17844 int
17845 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17846 		struct lpfc_queue *drq)
17847 {
17848 	LPFC_MBOXQ_t *mbox;
17849 	int rc, length, status = 0;
17850 	uint32_t shdr_status, shdr_add_status;
17851 	union lpfc_sli4_cfg_shdr *shdr;
17852 
17853 	/* sanity check on queue memory */
17854 	if (!hrq || !drq)
17855 		return -ENODEV;
17856 
17857 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17858 		goto list_remove;
17859 
17860 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17861 	if (!mbox)
17862 		return -ENOMEM;
17863 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
17864 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17865 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17866 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17867 			 length, LPFC_SLI4_MBX_EMBED);
17868 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17869 	       hrq->queue_id);
17870 	mbox->vport = hrq->phba->pport;
17871 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17872 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17873 	/* The IOCTL status is embedded in the mailbox subheader. */
17874 	shdr = (union lpfc_sli4_cfg_shdr *)
17875 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17876 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17877 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17878 	if (shdr_status || shdr_add_status || rc) {
17879 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17880 				"2509 RQ_DESTROY mailbox failed with "
17881 				"status x%x add_status x%x, mbx status x%x\n",
17882 				shdr_status, shdr_add_status, rc);
17883 		mempool_free(mbox, hrq->phba->mbox_mem_pool);
17884 		return -ENXIO;
17885 	}
17886 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17887 	       drq->queue_id);
17888 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17889 	shdr = (union lpfc_sli4_cfg_shdr *)
17890 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17891 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17892 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17893 	if (shdr_status || shdr_add_status || rc) {
17894 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17895 				"2510 RQ_DESTROY mailbox failed with "
17896 				"status x%x add_status x%x, mbx status x%x\n",
17897 				shdr_status, shdr_add_status, rc);
17898 		status = -ENXIO;
17899 	}
17900 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
17901 
17902 list_remove:
17903 	list_del_init(&hrq->list);
17904 	list_del_init(&drq->list);
17905 	return status;
17906 }
17907 
17908 /**
17909  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17910  * @phba: The virtual port for which this call being executed.
17911  * @pdma_phys_addr0: Physical address of the 1st SGL page.
17912  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
17913  * @xritag: the xritag that ties this io to the SGL pages.
17914  *
17915  * This routine will post the sgl pages for the IO that has the xritag
17916  * that is in the iocbq structure. The xritag is assigned during iocbq
17917  * creation and persists for as long as the driver is loaded.
17918  * if the caller has fewer than 256 scatter gather segments to map then
17919  * pdma_phys_addr1 should be 0.
17920  * If the caller needs to map more than 256 scatter gather segment then
17921  * pdma_phys_addr1 should be a valid physical address.
17922  * physical address for SGLs must be 64 byte aligned.
17923  * If you are going to map 2 SGL's then the first one must have 256 entries
17924  * the second sgl can have between 1 and 256 entries.
17925  *
17926  * Return codes:
17927  * 	0 - Success
17928  * 	-ENXIO, -ENOMEM - Failure
17929  **/
17930 int
17931 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
17932 		dma_addr_t pdma_phys_addr0,
17933 		dma_addr_t pdma_phys_addr1,
17934 		uint16_t xritag)
17935 {
17936 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
17937 	LPFC_MBOXQ_t *mbox;
17938 	int rc;
17939 	uint32_t shdr_status, shdr_add_status;
17940 	uint32_t mbox_tmo;
17941 	union lpfc_sli4_cfg_shdr *shdr;
17942 
17943 	if (xritag == NO_XRI) {
17944 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17945 				"0364 Invalid param:\n");
17946 		return -EINVAL;
17947 	}
17948 
17949 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17950 	if (!mbox)
17951 		return -ENOMEM;
17952 
17953 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17954 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17955 			sizeof(struct lpfc_mbx_post_sgl_pages) -
17956 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17957 
17958 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
17959 				&mbox->u.mqe.un.post_sgl_pages;
17960 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
17961 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
17962 
17963 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
17964 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
17965 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
17966 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
17967 
17968 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
17969 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
17970 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
17971 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
17972 	if (!phba->sli4_hba.intr_enable)
17973 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17974 	else {
17975 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17976 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17977 	}
17978 	/* The IOCTL status is embedded in the mailbox subheader. */
17979 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
17980 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17981 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17982 	if (!phba->sli4_hba.intr_enable)
17983 		mempool_free(mbox, phba->mbox_mem_pool);
17984 	else if (rc != MBX_TIMEOUT)
17985 		mempool_free(mbox, phba->mbox_mem_pool);
17986 	if (shdr_status || shdr_add_status || rc) {
17987 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17988 				"2511 POST_SGL mailbox failed with "
17989 				"status x%x add_status x%x, mbx status x%x\n",
17990 				shdr_status, shdr_add_status, rc);
17991 	}
17992 	return 0;
17993 }
17994 
17995 /**
17996  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
17997  * @phba: pointer to lpfc hba data structure.
17998  *
17999  * This routine is invoked to post rpi header templates to the
18000  * HBA consistent with the SLI-4 interface spec.  This routine
18001  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18002  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18003  *
18004  * Returns
18005  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
18006  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
18007  **/
18008 static uint16_t
18009 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
18010 {
18011 	unsigned long xri;
18012 
18013 	/*
18014 	 * Fetch the next logical xri.  Because this index is logical,
18015 	 * the driver starts at 0 each time.
18016 	 */
18017 	spin_lock_irq(&phba->hbalock);
18018 	xri = find_first_zero_bit(phba->sli4_hba.xri_bmask,
18019 				 phba->sli4_hba.max_cfg_param.max_xri);
18020 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
18021 		spin_unlock_irq(&phba->hbalock);
18022 		return NO_XRI;
18023 	} else {
18024 		set_bit(xri, phba->sli4_hba.xri_bmask);
18025 		phba->sli4_hba.max_cfg_param.xri_used++;
18026 	}
18027 	spin_unlock_irq(&phba->hbalock);
18028 	return xri;
18029 }
18030 
18031 /**
18032  * __lpfc_sli4_free_xri - Release an xri for reuse.
18033  * @phba: pointer to lpfc hba data structure.
18034  * @xri: xri to release.
18035  *
18036  * This routine is invoked to release an xri to the pool of
18037  * available rpis maintained by the driver.
18038  **/
18039 static void
18040 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18041 {
18042 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
18043 		phba->sli4_hba.max_cfg_param.xri_used--;
18044 	}
18045 }
18046 
18047 /**
18048  * lpfc_sli4_free_xri - Release an xri for reuse.
18049  * @phba: pointer to lpfc hba data structure.
18050  * @xri: xri to release.
18051  *
18052  * This routine is invoked to release an xri to the pool of
18053  * available rpis maintained by the driver.
18054  **/
18055 void
18056 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18057 {
18058 	spin_lock_irq(&phba->hbalock);
18059 	__lpfc_sli4_free_xri(phba, xri);
18060 	spin_unlock_irq(&phba->hbalock);
18061 }
18062 
18063 /**
18064  * lpfc_sli4_next_xritag - Get an xritag for the io
18065  * @phba: Pointer to HBA context object.
18066  *
18067  * This function gets an xritag for the iocb. If there is no unused xritag
18068  * it will return 0xffff.
18069  * The function returns the allocated xritag if successful, else returns zero.
18070  * Zero is not a valid xritag.
18071  * The caller is not required to hold any lock.
18072  **/
18073 uint16_t
18074 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
18075 {
18076 	uint16_t xri_index;
18077 
18078 	xri_index = lpfc_sli4_alloc_xri(phba);
18079 	if (xri_index == NO_XRI)
18080 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18081 				"2004 Failed to allocate XRI.last XRITAG is %d"
18082 				" Max XRI is %d, Used XRI is %d\n",
18083 				xri_index,
18084 				phba->sli4_hba.max_cfg_param.max_xri,
18085 				phba->sli4_hba.max_cfg_param.xri_used);
18086 	return xri_index;
18087 }
18088 
18089 /**
18090  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
18091  * @phba: pointer to lpfc hba data structure.
18092  * @post_sgl_list: pointer to els sgl entry list.
18093  * @post_cnt: number of els sgl entries on the list.
18094  *
18095  * This routine is invoked to post a block of driver's sgl pages to the
18096  * HBA using non-embedded mailbox command. No Lock is held. This routine
18097  * is only called when the driver is loading and after all IO has been
18098  * stopped.
18099  **/
18100 static int
18101 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
18102 			    struct list_head *post_sgl_list,
18103 			    int post_cnt)
18104 {
18105 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
18106 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18107 	struct sgl_page_pairs *sgl_pg_pairs;
18108 	void *viraddr;
18109 	LPFC_MBOXQ_t *mbox;
18110 	uint32_t reqlen, alloclen, pg_pairs;
18111 	uint32_t mbox_tmo;
18112 	uint16_t xritag_start = 0;
18113 	int rc = 0;
18114 	uint32_t shdr_status, shdr_add_status;
18115 	union lpfc_sli4_cfg_shdr *shdr;
18116 
18117 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
18118 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18119 	if (reqlen > SLI4_PAGE_SIZE) {
18120 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18121 				"2559 Block sgl registration required DMA "
18122 				"size (%d) great than a page\n", reqlen);
18123 		return -ENOMEM;
18124 	}
18125 
18126 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18127 	if (!mbox)
18128 		return -ENOMEM;
18129 
18130 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18131 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18132 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
18133 			 LPFC_SLI4_MBX_NEMBED);
18134 
18135 	if (alloclen < reqlen) {
18136 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18137 				"0285 Allocated DMA memory size (%d) is "
18138 				"less than the requested DMA memory "
18139 				"size (%d)\n", alloclen, reqlen);
18140 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18141 		return -ENOMEM;
18142 	}
18143 	/* Set up the SGL pages in the non-embedded DMA pages */
18144 	viraddr = mbox->sge_array->addr[0];
18145 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18146 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18147 
18148 	pg_pairs = 0;
18149 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
18150 		/* Set up the sge entry */
18151 		sgl_pg_pairs->sgl_pg0_addr_lo =
18152 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
18153 		sgl_pg_pairs->sgl_pg0_addr_hi =
18154 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
18155 		sgl_pg_pairs->sgl_pg1_addr_lo =
18156 				cpu_to_le32(putPaddrLow(0));
18157 		sgl_pg_pairs->sgl_pg1_addr_hi =
18158 				cpu_to_le32(putPaddrHigh(0));
18159 
18160 		/* Keep the first xritag on the list */
18161 		if (pg_pairs == 0)
18162 			xritag_start = sglq_entry->sli4_xritag;
18163 		sgl_pg_pairs++;
18164 		pg_pairs++;
18165 	}
18166 
18167 	/* Complete initialization and perform endian conversion. */
18168 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18169 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
18170 	sgl->word0 = cpu_to_le32(sgl->word0);
18171 
18172 	if (!phba->sli4_hba.intr_enable)
18173 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18174 	else {
18175 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18176 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18177 	}
18178 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
18179 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18180 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18181 	if (!phba->sli4_hba.intr_enable)
18182 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18183 	else if (rc != MBX_TIMEOUT)
18184 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18185 	if (shdr_status || shdr_add_status || rc) {
18186 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18187 				"2513 POST_SGL_BLOCK mailbox command failed "
18188 				"status x%x add_status x%x mbx status x%x\n",
18189 				shdr_status, shdr_add_status, rc);
18190 		rc = -ENXIO;
18191 	}
18192 	return rc;
18193 }
18194 
18195 /**
18196  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
18197  * @phba: pointer to lpfc hba data structure.
18198  * @nblist: pointer to nvme buffer list.
18199  * @count: number of scsi buffers on the list.
18200  *
18201  * This routine is invoked to post a block of @count scsi sgl pages from a
18202  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
18203  * No Lock is held.
18204  *
18205  **/
18206 static int
18207 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
18208 			    int count)
18209 {
18210 	struct lpfc_io_buf *lpfc_ncmd;
18211 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18212 	struct sgl_page_pairs *sgl_pg_pairs;
18213 	void *viraddr;
18214 	LPFC_MBOXQ_t *mbox;
18215 	uint32_t reqlen, alloclen, pg_pairs;
18216 	uint32_t mbox_tmo;
18217 	uint16_t xritag_start = 0;
18218 	int rc = 0;
18219 	uint32_t shdr_status, shdr_add_status;
18220 	dma_addr_t pdma_phys_bpl1;
18221 	union lpfc_sli4_cfg_shdr *shdr;
18222 
18223 	/* Calculate the requested length of the dma memory */
18224 	reqlen = count * sizeof(struct sgl_page_pairs) +
18225 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18226 	if (reqlen > SLI4_PAGE_SIZE) {
18227 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
18228 				"6118 Block sgl registration required DMA "
18229 				"size (%d) great than a page\n", reqlen);
18230 		return -ENOMEM;
18231 	}
18232 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18233 	if (!mbox) {
18234 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18235 				"6119 Failed to allocate mbox cmd memory\n");
18236 		return -ENOMEM;
18237 	}
18238 
18239 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18240 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18241 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
18242 				    reqlen, LPFC_SLI4_MBX_NEMBED);
18243 
18244 	if (alloclen < reqlen) {
18245 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18246 				"6120 Allocated DMA memory size (%d) is "
18247 				"less than the requested DMA memory "
18248 				"size (%d)\n", alloclen, reqlen);
18249 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18250 		return -ENOMEM;
18251 	}
18252 
18253 	/* Get the first SGE entry from the non-embedded DMA memory */
18254 	viraddr = mbox->sge_array->addr[0];
18255 
18256 	/* Set up the SGL pages in the non-embedded DMA pages */
18257 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18258 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18259 
18260 	pg_pairs = 0;
18261 	list_for_each_entry(lpfc_ncmd, nblist, list) {
18262 		/* Set up the sge entry */
18263 		sgl_pg_pairs->sgl_pg0_addr_lo =
18264 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
18265 		sgl_pg_pairs->sgl_pg0_addr_hi =
18266 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
18267 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
18268 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
18269 						SGL_PAGE_SIZE;
18270 		else
18271 			pdma_phys_bpl1 = 0;
18272 		sgl_pg_pairs->sgl_pg1_addr_lo =
18273 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
18274 		sgl_pg_pairs->sgl_pg1_addr_hi =
18275 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
18276 		/* Keep the first xritag on the list */
18277 		if (pg_pairs == 0)
18278 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
18279 		sgl_pg_pairs++;
18280 		pg_pairs++;
18281 	}
18282 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18283 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
18284 	/* Perform endian conversion if necessary */
18285 	sgl->word0 = cpu_to_le32(sgl->word0);
18286 
18287 	if (!phba->sli4_hba.intr_enable) {
18288 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18289 	} else {
18290 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18291 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18292 	}
18293 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
18294 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18295 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18296 	if (!phba->sli4_hba.intr_enable)
18297 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18298 	else if (rc != MBX_TIMEOUT)
18299 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18300 	if (shdr_status || shdr_add_status || rc) {
18301 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18302 				"6125 POST_SGL_BLOCK mailbox command failed "
18303 				"status x%x add_status x%x mbx status x%x\n",
18304 				shdr_status, shdr_add_status, rc);
18305 		rc = -ENXIO;
18306 	}
18307 	return rc;
18308 }
18309 
18310 /**
18311  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
18312  * @phba: pointer to lpfc hba data structure.
18313  * @post_nblist: pointer to the nvme buffer list.
18314  * @sb_count: number of nvme buffers.
18315  *
18316  * This routine walks a list of nvme buffers that was passed in. It attempts
18317  * to construct blocks of nvme buffer sgls which contains contiguous xris and
18318  * uses the non-embedded SGL block post mailbox commands to post to the port.
18319  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
18320  * embedded SGL post mailbox command for posting. The @post_nblist passed in
18321  * must be local list, thus no lock is needed when manipulate the list.
18322  *
18323  * Returns: 0 = failure, non-zero number of successfully posted buffers.
18324  **/
18325 int
18326 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
18327 			   struct list_head *post_nblist, int sb_count)
18328 {
18329 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
18330 	int status, sgl_size;
18331 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
18332 	dma_addr_t pdma_phys_sgl1;
18333 	int last_xritag = NO_XRI;
18334 	int cur_xritag;
18335 	LIST_HEAD(prep_nblist);
18336 	LIST_HEAD(blck_nblist);
18337 	LIST_HEAD(nvme_nblist);
18338 
18339 	/* sanity check */
18340 	if (sb_count <= 0)
18341 		return -EINVAL;
18342 
18343 	sgl_size = phba->cfg_sg_dma_buf_size;
18344 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
18345 		list_del_init(&lpfc_ncmd->list);
18346 		block_cnt++;
18347 		if ((last_xritag != NO_XRI) &&
18348 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
18349 			/* a hole in xri block, form a sgl posting block */
18350 			list_splice_init(&prep_nblist, &blck_nblist);
18351 			post_cnt = block_cnt - 1;
18352 			/* prepare list for next posting block */
18353 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18354 			block_cnt = 1;
18355 		} else {
18356 			/* prepare list for next posting block */
18357 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18358 			/* enough sgls for non-embed sgl mbox command */
18359 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
18360 				list_splice_init(&prep_nblist, &blck_nblist);
18361 				post_cnt = block_cnt;
18362 				block_cnt = 0;
18363 			}
18364 		}
18365 		num_posting++;
18366 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18367 
18368 		/* end of repost sgl list condition for NVME buffers */
18369 		if (num_posting == sb_count) {
18370 			if (post_cnt == 0) {
18371 				/* last sgl posting block */
18372 				list_splice_init(&prep_nblist, &blck_nblist);
18373 				post_cnt = block_cnt;
18374 			} else if (block_cnt == 1) {
18375 				/* last single sgl with non-contiguous xri */
18376 				if (sgl_size > SGL_PAGE_SIZE)
18377 					pdma_phys_sgl1 =
18378 						lpfc_ncmd->dma_phys_sgl +
18379 						SGL_PAGE_SIZE;
18380 				else
18381 					pdma_phys_sgl1 = 0;
18382 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18383 				status = lpfc_sli4_post_sgl(
18384 						phba, lpfc_ncmd->dma_phys_sgl,
18385 						pdma_phys_sgl1, cur_xritag);
18386 				if (status) {
18387 					/* Post error.  Buffer unavailable. */
18388 					lpfc_ncmd->flags |=
18389 						LPFC_SBUF_NOT_POSTED;
18390 				} else {
18391 					/* Post success. Bffer available. */
18392 					lpfc_ncmd->flags &=
18393 						~LPFC_SBUF_NOT_POSTED;
18394 					lpfc_ncmd->status = IOSTAT_SUCCESS;
18395 					num_posted++;
18396 				}
18397 				/* success, put on NVME buffer sgl list */
18398 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18399 			}
18400 		}
18401 
18402 		/* continue until a nembed page worth of sgls */
18403 		if (post_cnt == 0)
18404 			continue;
18405 
18406 		/* post block of NVME buffer list sgls */
18407 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
18408 						     post_cnt);
18409 
18410 		/* don't reset xirtag due to hole in xri block */
18411 		if (block_cnt == 0)
18412 			last_xritag = NO_XRI;
18413 
18414 		/* reset NVME buffer post count for next round of posting */
18415 		post_cnt = 0;
18416 
18417 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
18418 		while (!list_empty(&blck_nblist)) {
18419 			list_remove_head(&blck_nblist, lpfc_ncmd,
18420 					 struct lpfc_io_buf, list);
18421 			if (status) {
18422 				/* Post error.  Mark buffer unavailable. */
18423 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
18424 			} else {
18425 				/* Post success, Mark buffer available. */
18426 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
18427 				lpfc_ncmd->status = IOSTAT_SUCCESS;
18428 				num_posted++;
18429 			}
18430 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18431 		}
18432 	}
18433 	/* Push NVME buffers with sgl posted to the available list */
18434 	lpfc_io_buf_replenish(phba, &nvme_nblist);
18435 
18436 	return num_posted;
18437 }
18438 
18439 /**
18440  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
18441  * @phba: pointer to lpfc_hba struct that the frame was received on
18442  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18443  *
18444  * This function checks the fields in the @fc_hdr to see if the FC frame is a
18445  * valid type of frame that the LPFC driver will handle. This function will
18446  * return a zero if the frame is a valid frame or a non zero value when the
18447  * frame does not pass the check.
18448  **/
18449 static int
18450 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
18451 {
18452 	/*  make rctl_names static to save stack space */
18453 	struct fc_vft_header *fc_vft_hdr;
18454 	struct fc_app_header *fc_app_hdr;
18455 	uint32_t *header = (uint32_t *) fc_hdr;
18456 
18457 #define FC_RCTL_MDS_DIAGS	0xF4
18458 
18459 	switch (fc_hdr->fh_r_ctl) {
18460 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
18461 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
18462 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
18463 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
18464 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
18465 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
18466 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
18467 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
18468 	case FC_RCTL_ELS_REQ:	/* extended link services request */
18469 	case FC_RCTL_ELS_REP:	/* extended link services reply */
18470 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
18471 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
18472 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
18473 	case FC_RCTL_BA_RMC: 	/* remove connection */
18474 	case FC_RCTL_BA_ACC:	/* basic accept */
18475 	case FC_RCTL_BA_RJT:	/* basic reject */
18476 	case FC_RCTL_BA_PRMT:
18477 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
18478 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
18479 	case FC_RCTL_P_RJT:	/* port reject */
18480 	case FC_RCTL_F_RJT:	/* fabric reject */
18481 	case FC_RCTL_P_BSY:	/* port busy */
18482 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
18483 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
18484 	case FC_RCTL_LCR:	/* link credit reset */
18485 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
18486 	case FC_RCTL_END:	/* end */
18487 		break;
18488 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
18489 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18490 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
18491 		return lpfc_fc_frame_check(phba, fc_hdr);
18492 	case FC_RCTL_BA_NOP:	/* basic link service NOP */
18493 	default:
18494 		goto drop;
18495 	}
18496 
18497 	switch (fc_hdr->fh_type) {
18498 	case FC_TYPE_BLS:
18499 	case FC_TYPE_ELS:
18500 	case FC_TYPE_FCP:
18501 	case FC_TYPE_CT:
18502 	case FC_TYPE_NVME:
18503 		break;
18504 	case FC_TYPE_IP:
18505 	case FC_TYPE_ILS:
18506 	default:
18507 		goto drop;
18508 	}
18509 
18510 	if (unlikely(phba->link_flag == LS_LOOPBACK_MODE &&
18511 				phba->cfg_vmid_app_header)) {
18512 		/* Application header is 16B device header */
18513 		if (fc_hdr->fh_df_ctl & LPFC_FC_16B_DEVICE_HEADER) {
18514 			fc_app_hdr = (struct fc_app_header *) (fc_hdr + 1);
18515 			if (be32_to_cpu(fc_app_hdr->src_app_id) !=
18516 					LOOPBACK_SRC_APPID) {
18517 				lpfc_printf_log(phba, KERN_WARNING,
18518 						LOG_ELS | LOG_LIBDFC,
18519 						"1932 Loopback src app id "
18520 						"not matched, app_id:x%x\n",
18521 						be32_to_cpu(fc_app_hdr->src_app_id));
18522 
18523 				goto drop;
18524 			}
18525 		} else {
18526 			lpfc_printf_log(phba, KERN_WARNING,
18527 					LOG_ELS | LOG_LIBDFC,
18528 					"1933 Loopback df_ctl bit not set, "
18529 					"df_ctl:x%x\n",
18530 					fc_hdr->fh_df_ctl);
18531 
18532 			goto drop;
18533 		}
18534 	}
18535 
18536 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
18537 			"2538 Received frame rctl:x%x, type:x%x, "
18538 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
18539 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
18540 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
18541 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
18542 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
18543 			be32_to_cpu(header[6]));
18544 	return 0;
18545 drop:
18546 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
18547 			"2539 Dropped frame rctl:x%x type:x%x\n",
18548 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18549 	return 1;
18550 }
18551 
18552 /**
18553  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
18554  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18555  *
18556  * This function processes the FC header to retrieve the VFI from the VF
18557  * header, if one exists. This function will return the VFI if one exists
18558  * or 0 if no VSAN Header exists.
18559  **/
18560 static uint32_t
18561 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
18562 {
18563 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18564 
18565 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
18566 		return 0;
18567 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
18568 }
18569 
18570 /**
18571  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
18572  * @phba: Pointer to the HBA structure to search for the vport on
18573  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18574  * @fcfi: The FC Fabric ID that the frame came from
18575  * @did: Destination ID to match against
18576  *
18577  * This function searches the @phba for a vport that matches the content of the
18578  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
18579  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
18580  * returns the matching vport pointer or NULL if unable to match frame to a
18581  * vport.
18582  **/
18583 static struct lpfc_vport *
18584 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
18585 		       uint16_t fcfi, uint32_t did)
18586 {
18587 	struct lpfc_vport **vports;
18588 	struct lpfc_vport *vport = NULL;
18589 	int i;
18590 
18591 	if (did == Fabric_DID)
18592 		return phba->pport;
18593 	if (test_bit(FC_PT2PT, &phba->pport->fc_flag) &&
18594 	    phba->link_state != LPFC_HBA_READY)
18595 		return phba->pport;
18596 
18597 	vports = lpfc_create_vport_work_array(phba);
18598 	if (vports != NULL) {
18599 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
18600 			if (phba->fcf.fcfi == fcfi &&
18601 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
18602 			    vports[i]->fc_myDID == did) {
18603 				vport = vports[i];
18604 				break;
18605 			}
18606 		}
18607 	}
18608 	lpfc_destroy_vport_work_array(phba, vports);
18609 	return vport;
18610 }
18611 
18612 /**
18613  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
18614  * @vport: The vport to work on.
18615  *
18616  * This function updates the receive sequence time stamp for this vport. The
18617  * receive sequence time stamp indicates the time that the last frame of the
18618  * the sequence that has been idle for the longest amount of time was received.
18619  * the driver uses this time stamp to indicate if any received sequences have
18620  * timed out.
18621  **/
18622 static void
18623 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
18624 {
18625 	struct lpfc_dmabuf *h_buf;
18626 	struct hbq_dmabuf *dmabuf = NULL;
18627 
18628 	/* get the oldest sequence on the rcv list */
18629 	h_buf = list_get_first(&vport->rcv_buffer_list,
18630 			       struct lpfc_dmabuf, list);
18631 	if (!h_buf)
18632 		return;
18633 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18634 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
18635 }
18636 
18637 /**
18638  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
18639  * @vport: The vport that the received sequences were sent to.
18640  *
18641  * This function cleans up all outstanding received sequences. This is called
18642  * by the driver when a link event or user action invalidates all the received
18643  * sequences.
18644  **/
18645 void
18646 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
18647 {
18648 	struct lpfc_dmabuf *h_buf, *hnext;
18649 	struct lpfc_dmabuf *d_buf, *dnext;
18650 	struct hbq_dmabuf *dmabuf = NULL;
18651 
18652 	/* start with the oldest sequence on the rcv list */
18653 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18654 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18655 		list_del_init(&dmabuf->hbuf.list);
18656 		list_for_each_entry_safe(d_buf, dnext,
18657 					 &dmabuf->dbuf.list, list) {
18658 			list_del_init(&d_buf->list);
18659 			lpfc_in_buf_free(vport->phba, d_buf);
18660 		}
18661 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18662 	}
18663 }
18664 
18665 /**
18666  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
18667  * @vport: The vport that the received sequences were sent to.
18668  *
18669  * This function determines whether any received sequences have timed out by
18670  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
18671  * indicates that there is at least one timed out sequence this routine will
18672  * go through the received sequences one at a time from most inactive to most
18673  * active to determine which ones need to be cleaned up. Once it has determined
18674  * that a sequence needs to be cleaned up it will simply free up the resources
18675  * without sending an abort.
18676  **/
18677 void
18678 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
18679 {
18680 	struct lpfc_dmabuf *h_buf, *hnext;
18681 	struct lpfc_dmabuf *d_buf, *dnext;
18682 	struct hbq_dmabuf *dmabuf = NULL;
18683 	unsigned long timeout;
18684 	int abort_count = 0;
18685 
18686 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18687 		   vport->rcv_buffer_time_stamp);
18688 	if (list_empty(&vport->rcv_buffer_list) ||
18689 	    time_before(jiffies, timeout))
18690 		return;
18691 	/* start with the oldest sequence on the rcv list */
18692 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18693 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18694 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18695 			   dmabuf->time_stamp);
18696 		if (time_before(jiffies, timeout))
18697 			break;
18698 		abort_count++;
18699 		list_del_init(&dmabuf->hbuf.list);
18700 		list_for_each_entry_safe(d_buf, dnext,
18701 					 &dmabuf->dbuf.list, list) {
18702 			list_del_init(&d_buf->list);
18703 			lpfc_in_buf_free(vport->phba, d_buf);
18704 		}
18705 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18706 	}
18707 	if (abort_count)
18708 		lpfc_update_rcv_time_stamp(vport);
18709 }
18710 
18711 /**
18712  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
18713  * @vport: pointer to a vitural port
18714  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
18715  *
18716  * This function searches through the existing incomplete sequences that have
18717  * been sent to this @vport. If the frame matches one of the incomplete
18718  * sequences then the dbuf in the @dmabuf is added to the list of frames that
18719  * make up that sequence. If no sequence is found that matches this frame then
18720  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
18721  * This function returns a pointer to the first dmabuf in the sequence list that
18722  * the frame was linked to.
18723  **/
18724 static struct hbq_dmabuf *
18725 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18726 {
18727 	struct fc_frame_header *new_hdr;
18728 	struct fc_frame_header *temp_hdr;
18729 	struct lpfc_dmabuf *d_buf;
18730 	struct lpfc_dmabuf *h_buf;
18731 	struct hbq_dmabuf *seq_dmabuf = NULL;
18732 	struct hbq_dmabuf *temp_dmabuf = NULL;
18733 	uint8_t	found = 0;
18734 
18735 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18736 	dmabuf->time_stamp = jiffies;
18737 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18738 
18739 	/* Use the hdr_buf to find the sequence that this frame belongs to */
18740 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18741 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18742 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18743 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18744 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18745 			continue;
18746 		/* found a pending sequence that matches this frame */
18747 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18748 		break;
18749 	}
18750 	if (!seq_dmabuf) {
18751 		/*
18752 		 * This indicates first frame received for this sequence.
18753 		 * Queue the buffer on the vport's rcv_buffer_list.
18754 		 */
18755 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18756 		lpfc_update_rcv_time_stamp(vport);
18757 		return dmabuf;
18758 	}
18759 	temp_hdr = seq_dmabuf->hbuf.virt;
18760 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
18761 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18762 		list_del_init(&seq_dmabuf->hbuf.list);
18763 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18764 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18765 		lpfc_update_rcv_time_stamp(vport);
18766 		return dmabuf;
18767 	}
18768 	/* move this sequence to the tail to indicate a young sequence */
18769 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
18770 	seq_dmabuf->time_stamp = jiffies;
18771 	lpfc_update_rcv_time_stamp(vport);
18772 	if (list_empty(&seq_dmabuf->dbuf.list)) {
18773 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18774 		return seq_dmabuf;
18775 	}
18776 	/* find the correct place in the sequence to insert this frame */
18777 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
18778 	while (!found) {
18779 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18780 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
18781 		/*
18782 		 * If the frame's sequence count is greater than the frame on
18783 		 * the list then insert the frame right after this frame
18784 		 */
18785 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
18786 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18787 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
18788 			found = 1;
18789 			break;
18790 		}
18791 
18792 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
18793 			break;
18794 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
18795 	}
18796 
18797 	if (found)
18798 		return seq_dmabuf;
18799 	return NULL;
18800 }
18801 
18802 /**
18803  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
18804  * @vport: pointer to a vitural port
18805  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18806  *
18807  * This function tries to abort from the partially assembed sequence, described
18808  * by the information from basic abbort @dmabuf. It checks to see whether such
18809  * partially assembled sequence held by the driver. If so, it shall free up all
18810  * the frames from the partially assembled sequence.
18811  *
18812  * Return
18813  * true  -- if there is matching partially assembled sequence present and all
18814  *          the frames freed with the sequence;
18815  * false -- if there is no matching partially assembled sequence present so
18816  *          nothing got aborted in the lower layer driver
18817  **/
18818 static bool
18819 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
18820 			    struct hbq_dmabuf *dmabuf)
18821 {
18822 	struct fc_frame_header *new_hdr;
18823 	struct fc_frame_header *temp_hdr;
18824 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
18825 	struct hbq_dmabuf *seq_dmabuf = NULL;
18826 
18827 	/* Use the hdr_buf to find the sequence that matches this frame */
18828 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18829 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
18830 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18831 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18832 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18833 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18834 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18835 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18836 			continue;
18837 		/* found a pending sequence that matches this frame */
18838 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18839 		break;
18840 	}
18841 
18842 	/* Free up all the frames from the partially assembled sequence */
18843 	if (seq_dmabuf) {
18844 		list_for_each_entry_safe(d_buf, n_buf,
18845 					 &seq_dmabuf->dbuf.list, list) {
18846 			list_del_init(&d_buf->list);
18847 			lpfc_in_buf_free(vport->phba, d_buf);
18848 		}
18849 		return true;
18850 	}
18851 	return false;
18852 }
18853 
18854 /**
18855  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18856  * @vport: pointer to a vitural port
18857  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18858  *
18859  * This function tries to abort from the assembed sequence from upper level
18860  * protocol, described by the information from basic abbort @dmabuf. It
18861  * checks to see whether such pending context exists at upper level protocol.
18862  * If so, it shall clean up the pending context.
18863  *
18864  * Return
18865  * true  -- if there is matching pending context of the sequence cleaned
18866  *          at ulp;
18867  * false -- if there is no matching pending context of the sequence present
18868  *          at ulp.
18869  **/
18870 static bool
18871 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18872 {
18873 	struct lpfc_hba *phba = vport->phba;
18874 	int handled;
18875 
18876 	/* Accepting abort at ulp with SLI4 only */
18877 	if (phba->sli_rev < LPFC_SLI_REV4)
18878 		return false;
18879 
18880 	/* Register all caring upper level protocols to attend abort */
18881 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18882 	if (handled)
18883 		return true;
18884 
18885 	return false;
18886 }
18887 
18888 /**
18889  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18890  * @phba: Pointer to HBA context object.
18891  * @cmd_iocbq: pointer to the command iocbq structure.
18892  * @rsp_iocbq: pointer to the response iocbq structure.
18893  *
18894  * This function handles the sequence abort response iocb command complete
18895  * event. It properly releases the memory allocated to the sequence abort
18896  * accept iocb.
18897  **/
18898 static void
18899 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18900 			     struct lpfc_iocbq *cmd_iocbq,
18901 			     struct lpfc_iocbq *rsp_iocbq)
18902 {
18903 	if (cmd_iocbq) {
18904 		lpfc_nlp_put(cmd_iocbq->ndlp);
18905 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
18906 	}
18907 
18908 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
18909 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18910 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18911 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
18912 			get_job_ulpstatus(phba, rsp_iocbq),
18913 			get_job_word4(phba, rsp_iocbq));
18914 }
18915 
18916 /**
18917  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
18918  * @phba: Pointer to HBA context object.
18919  * @xri: xri id in transaction.
18920  *
18921  * This function validates the xri maps to the known range of XRIs allocated an
18922  * used by the driver.
18923  **/
18924 uint16_t
18925 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
18926 		      uint16_t xri)
18927 {
18928 	uint16_t i;
18929 
18930 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
18931 		if (xri == phba->sli4_hba.xri_ids[i])
18932 			return i;
18933 	}
18934 	return NO_XRI;
18935 }
18936 
18937 /**
18938  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
18939  * @vport: pointer to a virtual port.
18940  * @fc_hdr: pointer to a FC frame header.
18941  * @aborted: was the partially assembled receive sequence successfully aborted
18942  *
18943  * This function sends a basic response to a previous unsol sequence abort
18944  * event after aborting the sequence handling.
18945  **/
18946 void
18947 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
18948 			struct fc_frame_header *fc_hdr, bool aborted)
18949 {
18950 	struct lpfc_hba *phba = vport->phba;
18951 	struct lpfc_iocbq *ctiocb = NULL;
18952 	struct lpfc_nodelist *ndlp;
18953 	uint16_t oxid, rxid, xri, lxri;
18954 	uint32_t sid, fctl;
18955 	union lpfc_wqe128 *icmd;
18956 	int rc;
18957 
18958 	if (!lpfc_is_link_up(phba))
18959 		return;
18960 
18961 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18962 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
18963 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
18964 
18965 	ndlp = lpfc_findnode_did(vport, sid);
18966 	if (!ndlp) {
18967 		ndlp = lpfc_nlp_init(vport, sid);
18968 		if (!ndlp) {
18969 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
18970 					 "1268 Failed to allocate ndlp for "
18971 					 "oxid:x%x SID:x%x\n", oxid, sid);
18972 			return;
18973 		}
18974 		/* Put ndlp onto vport node list */
18975 		lpfc_enqueue_node(vport, ndlp);
18976 	}
18977 
18978 	/* Allocate buffer for rsp iocb */
18979 	ctiocb = lpfc_sli_get_iocbq(phba);
18980 	if (!ctiocb)
18981 		return;
18982 
18983 	icmd = &ctiocb->wqe;
18984 
18985 	/* Extract the F_CTL field from FC_HDR */
18986 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
18987 
18988 	ctiocb->ndlp = lpfc_nlp_get(ndlp);
18989 	if (!ctiocb->ndlp) {
18990 		lpfc_sli_release_iocbq(phba, ctiocb);
18991 		return;
18992 	}
18993 
18994 	ctiocb->vport = vport;
18995 	ctiocb->cmd_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
18996 	ctiocb->sli4_lxritag = NO_XRI;
18997 	ctiocb->sli4_xritag = NO_XRI;
18998 	ctiocb->abort_rctl = FC_RCTL_BA_ACC;
18999 
19000 	if (fctl & FC_FC_EX_CTX)
19001 		/* Exchange responder sent the abort so we
19002 		 * own the oxid.
19003 		 */
19004 		xri = oxid;
19005 	else
19006 		xri = rxid;
19007 	lxri = lpfc_sli4_xri_inrange(phba, xri);
19008 	if (lxri != NO_XRI)
19009 		lpfc_set_rrq_active(phba, ndlp, lxri,
19010 			(xri == oxid) ? rxid : oxid, 0);
19011 	/* For BA_ABTS from exchange responder, if the logical xri with
19012 	 * the oxid maps to the FCP XRI range, the port no longer has
19013 	 * that exchange context, send a BLS_RJT. Override the IOCB for
19014 	 * a BA_RJT.
19015 	 */
19016 	if ((fctl & FC_FC_EX_CTX) &&
19017 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
19018 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
19019 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
19020 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
19021 		       FC_BA_RJT_INV_XID);
19022 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
19023 		       FC_BA_RJT_UNABLE);
19024 	}
19025 
19026 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
19027 	 * the driver no longer has that exchange, send a BLS_RJT. Override
19028 	 * the IOCB for a BA_RJT.
19029 	 */
19030 	if (aborted == false) {
19031 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
19032 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
19033 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
19034 		       FC_BA_RJT_INV_XID);
19035 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
19036 		       FC_BA_RJT_UNABLE);
19037 	}
19038 
19039 	if (fctl & FC_FC_EX_CTX) {
19040 		/* ABTS sent by responder to CT exchange, construction
19041 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
19042 		 * field and RX_ID from ABTS for RX_ID field.
19043 		 */
19044 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_RSP;
19045 		bf_set(xmit_bls_rsp64_rxid, &icmd->xmit_bls_rsp, rxid);
19046 	} else {
19047 		/* ABTS sent by initiator to CT exchange, construction
19048 		 * of BA_ACC will need to allocate a new XRI as for the
19049 		 * XRI_TAG field.
19050 		 */
19051 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_INT;
19052 	}
19053 
19054 	/* OX_ID is invariable to who sent ABTS to CT exchange */
19055 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, oxid);
19056 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, rxid);
19057 
19058 	/* Use CT=VPI */
19059 	bf_set(wqe_els_did, &icmd->xmit_bls_rsp.wqe_dest,
19060 	       ndlp->nlp_DID);
19061 	bf_set(xmit_bls_rsp64_temprpi, &icmd->xmit_bls_rsp,
19062 	       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
19063 	bf_set(wqe_cmnd, &icmd->generic.wqe_com, CMD_XMIT_BLS_RSP64_CX);
19064 
19065 	/* Xmit CT abts response on exchange <xid> */
19066 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
19067 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
19068 			 ctiocb->abort_rctl, oxid, phba->link_state);
19069 
19070 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
19071 	if (rc == IOCB_ERROR) {
19072 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19073 				 "2925 Failed to issue CT ABTS RSP x%x on "
19074 				 "xri x%x, Data x%x\n",
19075 				 ctiocb->abort_rctl, oxid,
19076 				 phba->link_state);
19077 		lpfc_nlp_put(ndlp);
19078 		ctiocb->ndlp = NULL;
19079 		lpfc_sli_release_iocbq(phba, ctiocb);
19080 	}
19081 
19082 	/* if only usage of this nodelist is BLS response, release initial ref
19083 	 * to free ndlp when transmit completes
19084 	 */
19085 	if (ndlp->nlp_state == NLP_STE_UNUSED_NODE &&
19086 	    !test_bit(NLP_DROPPED, &ndlp->nlp_flag) &&
19087 	    !(ndlp->fc4_xpt_flags & (NVME_XPT_REGD | SCSI_XPT_REGD))) {
19088 		set_bit(NLP_DROPPED, &ndlp->nlp_flag);
19089 		lpfc_nlp_put(ndlp);
19090 	}
19091 }
19092 
19093 /**
19094  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
19095  * @vport: Pointer to the vport on which this sequence was received
19096  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19097  *
19098  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
19099  * receive sequence is only partially assembed by the driver, it shall abort
19100  * the partially assembled frames for the sequence. Otherwise, if the
19101  * unsolicited receive sequence has been completely assembled and passed to
19102  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
19103  * unsolicited sequence has been aborted. After that, it will issue a basic
19104  * accept to accept the abort.
19105  **/
19106 static void
19107 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
19108 			     struct hbq_dmabuf *dmabuf)
19109 {
19110 	struct lpfc_hba *phba = vport->phba;
19111 	struct fc_frame_header fc_hdr;
19112 	uint32_t fctl;
19113 	bool aborted;
19114 
19115 	/* Make a copy of fc_hdr before the dmabuf being released */
19116 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
19117 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
19118 
19119 	if (fctl & FC_FC_EX_CTX) {
19120 		/* ABTS by responder to exchange, no cleanup needed */
19121 		aborted = true;
19122 	} else {
19123 		/* ABTS by initiator to exchange, need to do cleanup */
19124 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
19125 		if (aborted == false)
19126 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
19127 	}
19128 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19129 
19130 	if (phba->nvmet_support) {
19131 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
19132 		return;
19133 	}
19134 
19135 	/* Respond with BA_ACC or BA_RJT accordingly */
19136 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
19137 }
19138 
19139 /**
19140  * lpfc_seq_complete - Indicates if a sequence is complete
19141  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19142  *
19143  * This function checks the sequence, starting with the frame described by
19144  * @dmabuf, to see if all the frames associated with this sequence are present.
19145  * the frames associated with this sequence are linked to the @dmabuf using the
19146  * dbuf list. This function looks for two major things. 1) That the first frame
19147  * has a sequence count of zero. 2) There is a frame with last frame of sequence
19148  * set. 3) That there are no holes in the sequence count. The function will
19149  * return 1 when the sequence is complete, otherwise it will return 0.
19150  **/
19151 static int
19152 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
19153 {
19154 	struct fc_frame_header *hdr;
19155 	struct lpfc_dmabuf *d_buf;
19156 	struct hbq_dmabuf *seq_dmabuf;
19157 	uint32_t fctl;
19158 	int seq_count = 0;
19159 
19160 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19161 	/* make sure first fame of sequence has a sequence count of zero */
19162 	if (hdr->fh_seq_cnt != seq_count)
19163 		return 0;
19164 	fctl = (hdr->fh_f_ctl[0] << 16 |
19165 		hdr->fh_f_ctl[1] << 8 |
19166 		hdr->fh_f_ctl[2]);
19167 	/* If last frame of sequence we can return success. */
19168 	if (fctl & FC_FC_END_SEQ)
19169 		return 1;
19170 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
19171 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19172 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19173 		/* If there is a hole in the sequence count then fail. */
19174 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
19175 			return 0;
19176 		fctl = (hdr->fh_f_ctl[0] << 16 |
19177 			hdr->fh_f_ctl[1] << 8 |
19178 			hdr->fh_f_ctl[2]);
19179 		/* If last frame of sequence we can return success. */
19180 		if (fctl & FC_FC_END_SEQ)
19181 			return 1;
19182 	}
19183 	return 0;
19184 }
19185 
19186 /**
19187  * lpfc_prep_seq - Prep sequence for ULP processing
19188  * @vport: Pointer to the vport on which this sequence was received
19189  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
19190  *
19191  * This function takes a sequence, described by a list of frames, and creates
19192  * a list of iocbq structures to describe the sequence. This iocbq list will be
19193  * used to issue to the generic unsolicited sequence handler. This routine
19194  * returns a pointer to the first iocbq in the list. If the function is unable
19195  * to allocate an iocbq then it throw out the received frames that were not
19196  * able to be described and return a pointer to the first iocbq. If unable to
19197  * allocate any iocbqs (including the first) this function will return NULL.
19198  **/
19199 static struct lpfc_iocbq *
19200 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
19201 {
19202 	struct hbq_dmabuf *hbq_buf;
19203 	struct lpfc_dmabuf *d_buf, *n_buf;
19204 	struct lpfc_iocbq *first_iocbq, *iocbq;
19205 	struct fc_frame_header *fc_hdr;
19206 	uint32_t sid;
19207 	uint32_t len, tot_len;
19208 
19209 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19210 	/* remove from receive buffer list */
19211 	list_del_init(&seq_dmabuf->hbuf.list);
19212 	lpfc_update_rcv_time_stamp(vport);
19213 	/* get the Remote Port's SID */
19214 	sid = sli4_sid_from_fc_hdr(fc_hdr);
19215 	tot_len = 0;
19216 	/* Get an iocbq struct to fill in. */
19217 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
19218 	if (first_iocbq) {
19219 		/* Initialize the first IOCB. */
19220 		first_iocbq->wcqe_cmpl.total_data_placed = 0;
19221 		bf_set(lpfc_wcqe_c_status, &first_iocbq->wcqe_cmpl,
19222 		       IOSTAT_SUCCESS);
19223 		first_iocbq->vport = vport;
19224 
19225 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
19226 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
19227 			bf_set(els_rsp64_sid, &first_iocbq->wqe.xmit_els_rsp,
19228 			       sli4_did_from_fc_hdr(fc_hdr));
19229 		}
19230 
19231 		bf_set(wqe_ctxt_tag, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19232 		       NO_XRI);
19233 		bf_set(wqe_rcvoxid, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19234 		       be16_to_cpu(fc_hdr->fh_ox_id));
19235 
19236 		/* put the first buffer into the first iocb */
19237 		tot_len = bf_get(lpfc_rcqe_length,
19238 				 &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
19239 
19240 		first_iocbq->cmd_dmabuf = &seq_dmabuf->dbuf;
19241 		first_iocbq->bpl_dmabuf = NULL;
19242 		/* Keep track of the BDE count */
19243 		first_iocbq->wcqe_cmpl.word3 = 1;
19244 
19245 		if (tot_len > LPFC_DATA_BUF_SIZE)
19246 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize =
19247 				LPFC_DATA_BUF_SIZE;
19248 		else
19249 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize = tot_len;
19250 
19251 		first_iocbq->wcqe_cmpl.total_data_placed = tot_len;
19252 		bf_set(wqe_els_did, &first_iocbq->wqe.xmit_els_rsp.wqe_dest,
19253 		       sid);
19254 	}
19255 	iocbq = first_iocbq;
19256 	/*
19257 	 * Each IOCBq can have two Buffers assigned, so go through the list
19258 	 * of buffers for this sequence and save two buffers in each IOCBq
19259 	 */
19260 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
19261 		if (!iocbq) {
19262 			lpfc_in_buf_free(vport->phba, d_buf);
19263 			continue;
19264 		}
19265 		if (!iocbq->bpl_dmabuf) {
19266 			iocbq->bpl_dmabuf = d_buf;
19267 			iocbq->wcqe_cmpl.word3++;
19268 			/* We need to get the size out of the right CQE */
19269 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19270 			len = bf_get(lpfc_rcqe_length,
19271 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19272 			iocbq->unsol_rcv_len = len;
19273 			iocbq->wcqe_cmpl.total_data_placed += len;
19274 			tot_len += len;
19275 		} else {
19276 			iocbq = lpfc_sli_get_iocbq(vport->phba);
19277 			if (!iocbq) {
19278 				if (first_iocbq) {
19279 					bf_set(lpfc_wcqe_c_status,
19280 					       &first_iocbq->wcqe_cmpl,
19281 					       IOSTAT_SUCCESS);
19282 					first_iocbq->wcqe_cmpl.parameter =
19283 						IOERR_NO_RESOURCES;
19284 				}
19285 				lpfc_in_buf_free(vport->phba, d_buf);
19286 				continue;
19287 			}
19288 			/* We need to get the size out of the right CQE */
19289 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19290 			len = bf_get(lpfc_rcqe_length,
19291 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19292 			iocbq->cmd_dmabuf = d_buf;
19293 			iocbq->bpl_dmabuf = NULL;
19294 			iocbq->wcqe_cmpl.word3 = 1;
19295 
19296 			if (len > LPFC_DATA_BUF_SIZE)
19297 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19298 					LPFC_DATA_BUF_SIZE;
19299 			else
19300 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19301 					len;
19302 
19303 			tot_len += len;
19304 			iocbq->wcqe_cmpl.total_data_placed = tot_len;
19305 			bf_set(wqe_els_did, &iocbq->wqe.xmit_els_rsp.wqe_dest,
19306 			       sid);
19307 			list_add_tail(&iocbq->list, &first_iocbq->list);
19308 		}
19309 	}
19310 	/* Free the sequence's header buffer */
19311 	if (!first_iocbq)
19312 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
19313 
19314 	return first_iocbq;
19315 }
19316 
19317 static void
19318 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
19319 			  struct hbq_dmabuf *seq_dmabuf)
19320 {
19321 	struct fc_frame_header *fc_hdr;
19322 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
19323 	struct lpfc_hba *phba = vport->phba;
19324 
19325 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19326 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
19327 	if (!iocbq) {
19328 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19329 				"2707 Ring %d handler: Failed to allocate "
19330 				"iocb Rctl x%x Type x%x received\n",
19331 				LPFC_ELS_RING,
19332 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19333 		return;
19334 	}
19335 	if (!lpfc_complete_unsol_iocb(phba,
19336 				      phba->sli4_hba.els_wq->pring,
19337 				      iocbq, fc_hdr->fh_r_ctl,
19338 				      fc_hdr->fh_type)) {
19339 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19340 				"2540 Ring %d handler: unexpected Rctl "
19341 				"x%x Type x%x received\n",
19342 				LPFC_ELS_RING,
19343 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19344 		lpfc_in_buf_free(phba, &seq_dmabuf->dbuf);
19345 	}
19346 
19347 	/* Free iocb created in lpfc_prep_seq */
19348 	list_for_each_entry_safe(curr_iocb, next_iocb,
19349 				 &iocbq->list, list) {
19350 		list_del_init(&curr_iocb->list);
19351 		lpfc_sli_release_iocbq(phba, curr_iocb);
19352 	}
19353 	lpfc_sli_release_iocbq(phba, iocbq);
19354 }
19355 
19356 static void
19357 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
19358 			    struct lpfc_iocbq *rspiocb)
19359 {
19360 	struct lpfc_dmabuf *pcmd = cmdiocb->cmd_dmabuf;
19361 
19362 	if (pcmd && pcmd->virt)
19363 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19364 	kfree(pcmd);
19365 	lpfc_sli_release_iocbq(phba, cmdiocb);
19366 	lpfc_drain_txq(phba);
19367 }
19368 
19369 static void
19370 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
19371 			      struct hbq_dmabuf *dmabuf)
19372 {
19373 	struct fc_frame_header *fc_hdr;
19374 	struct lpfc_hba *phba = vport->phba;
19375 	struct lpfc_iocbq *iocbq = NULL;
19376 	union  lpfc_wqe128 *pwqe;
19377 	struct lpfc_dmabuf *pcmd = NULL;
19378 	uint32_t frame_len;
19379 	int rc;
19380 	unsigned long iflags;
19381 
19382 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19383 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
19384 
19385 	/* Send the received frame back */
19386 	iocbq = lpfc_sli_get_iocbq(phba);
19387 	if (!iocbq) {
19388 		/* Queue cq event and wakeup worker thread to process it */
19389 		spin_lock_irqsave(&phba->hbalock, iflags);
19390 		list_add_tail(&dmabuf->cq_event.list,
19391 			      &phba->sli4_hba.sp_queue_event);
19392 		spin_unlock_irqrestore(&phba->hbalock, iflags);
19393 		set_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
19394 		lpfc_worker_wake_up(phba);
19395 		return;
19396 	}
19397 
19398 	/* Allocate buffer for command payload */
19399 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
19400 	if (pcmd)
19401 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
19402 					    &pcmd->phys);
19403 	if (!pcmd || !pcmd->virt)
19404 		goto exit;
19405 
19406 	INIT_LIST_HEAD(&pcmd->list);
19407 
19408 	/* copyin the payload */
19409 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
19410 
19411 	iocbq->cmd_dmabuf = pcmd;
19412 	iocbq->vport = vport;
19413 	iocbq->cmd_flag &= ~LPFC_FIP_ELS_ID_MASK;
19414 	iocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
19415 	iocbq->num_bdes = 0;
19416 
19417 	pwqe = &iocbq->wqe;
19418 	/* fill in BDE's for command */
19419 	pwqe->gen_req.bde.addrHigh = putPaddrHigh(pcmd->phys);
19420 	pwqe->gen_req.bde.addrLow = putPaddrLow(pcmd->phys);
19421 	pwqe->gen_req.bde.tus.f.bdeSize = frame_len;
19422 	pwqe->gen_req.bde.tus.f.bdeFlags = BUFF_TYPE_BDE_64;
19423 
19424 	pwqe->send_frame.frame_len = frame_len;
19425 	pwqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((__be32 *)fc_hdr));
19426 	pwqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((__be32 *)fc_hdr + 1));
19427 	pwqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((__be32 *)fc_hdr + 2));
19428 	pwqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((__be32 *)fc_hdr + 3));
19429 	pwqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((__be32 *)fc_hdr + 4));
19430 	pwqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((__be32 *)fc_hdr + 5));
19431 
19432 	pwqe->generic.wqe_com.word7 = 0;
19433 	pwqe->generic.wqe_com.word10 = 0;
19434 
19435 	bf_set(wqe_cmnd, &pwqe->generic.wqe_com, CMD_SEND_FRAME);
19436 	bf_set(wqe_sof, &pwqe->generic.wqe_com, 0x2E); /* SOF byte */
19437 	bf_set(wqe_eof, &pwqe->generic.wqe_com, 0x41); /* EOF byte */
19438 	bf_set(wqe_lenloc, &pwqe->generic.wqe_com, 1);
19439 	bf_set(wqe_xbl, &pwqe->generic.wqe_com, 1);
19440 	bf_set(wqe_dbde, &pwqe->generic.wqe_com, 1);
19441 	bf_set(wqe_xc, &pwqe->generic.wqe_com, 1);
19442 	bf_set(wqe_cmd_type, &pwqe->generic.wqe_com, 0xA);
19443 	bf_set(wqe_cqid, &pwqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
19444 	bf_set(wqe_xri_tag, &pwqe->generic.wqe_com, iocbq->sli4_xritag);
19445 	bf_set(wqe_reqtag, &pwqe->generic.wqe_com, iocbq->iotag);
19446 	bf_set(wqe_class, &pwqe->generic.wqe_com, CLASS3);
19447 	pwqe->generic.wqe_com.abort_tag = iocbq->iotag;
19448 
19449 	iocbq->cmd_cmpl = lpfc_sli4_mds_loopback_cmpl;
19450 
19451 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
19452 	if (rc == IOCB_ERROR)
19453 		goto exit;
19454 
19455 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19456 	return;
19457 
19458 exit:
19459 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
19460 			"2023 Unable to process MDS loopback frame\n");
19461 	if (pcmd && pcmd->virt)
19462 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19463 	kfree(pcmd);
19464 	if (iocbq)
19465 		lpfc_sli_release_iocbq(phba, iocbq);
19466 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19467 }
19468 
19469 /**
19470  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
19471  * @phba: Pointer to HBA context object.
19472  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
19473  *
19474  * This function is called with no lock held. This function processes all
19475  * the received buffers and gives it to upper layers when a received buffer
19476  * indicates that it is the final frame in the sequence. The interrupt
19477  * service routine processes received buffers at interrupt contexts.
19478  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
19479  * appropriate receive function when the final frame in a sequence is received.
19480  **/
19481 void
19482 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
19483 				 struct hbq_dmabuf *dmabuf)
19484 {
19485 	struct hbq_dmabuf *seq_dmabuf;
19486 	struct fc_frame_header *fc_hdr;
19487 	struct lpfc_vport *vport;
19488 	uint32_t fcfi;
19489 	uint32_t did;
19490 
19491 	/* Process each received buffer */
19492 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19493 
19494 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
19495 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
19496 		vport = phba->pport;
19497 		/* Handle MDS Loopback frames */
19498 		if  (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
19499 			lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19500 		else
19501 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19502 		return;
19503 	}
19504 
19505 	/* check to see if this a valid type of frame */
19506 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
19507 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19508 		return;
19509 	}
19510 
19511 	if ((bf_get(lpfc_cqe_code,
19512 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
19513 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
19514 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19515 	else
19516 		fcfi = bf_get(lpfc_rcqe_fcf_id,
19517 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19518 
19519 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
19520 		vport = phba->pport;
19521 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
19522 				"2023 MDS Loopback %d bytes\n",
19523 				bf_get(lpfc_rcqe_length,
19524 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
19525 		/* Handle MDS Loopback frames */
19526 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19527 		return;
19528 	}
19529 
19530 	/* d_id this frame is directed to */
19531 	did = sli4_did_from_fc_hdr(fc_hdr);
19532 
19533 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
19534 	if (!vport) {
19535 		/* throw out the frame */
19536 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19537 		return;
19538 	}
19539 
19540 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
19541 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
19542 		(did != Fabric_DID)) {
19543 		/*
19544 		 * Throw out the frame if we are not pt2pt.
19545 		 * The pt2pt protocol allows for discovery frames
19546 		 * to be received without a registered VPI.
19547 		 */
19548 		if (!test_bit(FC_PT2PT, &vport->fc_flag) ||
19549 		    phba->link_state == LPFC_HBA_READY) {
19550 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19551 			return;
19552 		}
19553 	}
19554 
19555 	/* Handle the basic abort sequence (BA_ABTS) event */
19556 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
19557 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
19558 		return;
19559 	}
19560 
19561 	/* Link this frame */
19562 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
19563 	if (!seq_dmabuf) {
19564 		/* unable to add frame to vport - throw it out */
19565 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19566 		return;
19567 	}
19568 	/* If not last frame in sequence continue processing frames. */
19569 	if (!lpfc_seq_complete(seq_dmabuf))
19570 		return;
19571 
19572 	/* Send the complete sequence to the upper layer protocol */
19573 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
19574 }
19575 
19576 /**
19577  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
19578  * @phba: pointer to lpfc hba data structure.
19579  *
19580  * This routine is invoked to post rpi header templates to the
19581  * HBA consistent with the SLI-4 interface spec.  This routine
19582  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19583  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19584  *
19585  * This routine does not require any locks.  It's usage is expected
19586  * to be driver load or reset recovery when the driver is
19587  * sequential.
19588  *
19589  * Return codes
19590  * 	0 - successful
19591  *      -EIO - The mailbox failed to complete successfully.
19592  * 	When this error occurs, the driver is not guaranteed
19593  *	to have any rpi regions posted to the device and
19594  *	must either attempt to repost the regions or take a
19595  *	fatal error.
19596  **/
19597 int
19598 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
19599 {
19600 	struct lpfc_rpi_hdr *rpi_page;
19601 	uint32_t rc = 0;
19602 	uint16_t lrpi = 0;
19603 
19604 	/* SLI4 ports that support extents do not require RPI headers. */
19605 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19606 		goto exit;
19607 	if (phba->sli4_hba.extents_in_use)
19608 		return -EIO;
19609 
19610 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
19611 		/*
19612 		 * Assign the rpi headers a physical rpi only if the driver
19613 		 * has not initialized those resources.  A port reset only
19614 		 * needs the headers posted.
19615 		 */
19616 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
19617 		    LPFC_RPI_RSRC_RDY)
19618 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19619 
19620 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
19621 		if (rc != MBX_SUCCESS) {
19622 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19623 					"2008 Error %d posting all rpi "
19624 					"headers\n", rc);
19625 			rc = -EIO;
19626 			break;
19627 		}
19628 	}
19629 
19630  exit:
19631 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
19632 	       LPFC_RPI_RSRC_RDY);
19633 	return rc;
19634 }
19635 
19636 /**
19637  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
19638  * @phba: pointer to lpfc hba data structure.
19639  * @rpi_page:  pointer to the rpi memory region.
19640  *
19641  * This routine is invoked to post a single rpi header to the
19642  * HBA consistent with the SLI-4 interface spec.  This memory region
19643  * maps up to 64 rpi context regions.
19644  *
19645  * Return codes
19646  * 	0 - successful
19647  * 	-ENOMEM - No available memory
19648  *      -EIO - The mailbox failed to complete successfully.
19649  **/
19650 int
19651 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
19652 {
19653 	LPFC_MBOXQ_t *mboxq;
19654 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
19655 	uint32_t rc = 0;
19656 	uint32_t shdr_status, shdr_add_status;
19657 	union lpfc_sli4_cfg_shdr *shdr;
19658 
19659 	/* SLI4 ports that support extents do not require RPI headers. */
19660 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19661 		return rc;
19662 	if (phba->sli4_hba.extents_in_use)
19663 		return -EIO;
19664 
19665 	/* The port is notified of the header region via a mailbox command. */
19666 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19667 	if (!mboxq) {
19668 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19669 				"2001 Unable to allocate memory for issuing "
19670 				"SLI_CONFIG_SPECIAL mailbox command\n");
19671 		return -ENOMEM;
19672 	}
19673 
19674 	/* Post all rpi memory regions to the port. */
19675 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
19676 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19677 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
19678 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
19679 			 sizeof(struct lpfc_sli4_cfg_mhdr),
19680 			 LPFC_SLI4_MBX_EMBED);
19681 
19682 
19683 	/* Post the physical rpi to the port for this rpi header. */
19684 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
19685 	       rpi_page->start_rpi);
19686 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
19687 	       hdr_tmpl, rpi_page->page_count);
19688 
19689 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
19690 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
19691 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19692 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
19693 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19694 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19695 	mempool_free(mboxq, phba->mbox_mem_pool);
19696 	if (shdr_status || shdr_add_status || rc) {
19697 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19698 				"2514 POST_RPI_HDR mailbox failed with "
19699 				"status x%x add_status x%x, mbx status x%x\n",
19700 				shdr_status, shdr_add_status, rc);
19701 		rc = -ENXIO;
19702 	} else {
19703 		/*
19704 		 * The next_rpi stores the next logical module-64 rpi value used
19705 		 * to post physical rpis in subsequent rpi postings.
19706 		 */
19707 		spin_lock_irq(&phba->hbalock);
19708 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
19709 		spin_unlock_irq(&phba->hbalock);
19710 	}
19711 	return rc;
19712 }
19713 
19714 /**
19715  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
19716  * @phba: pointer to lpfc hba data structure.
19717  *
19718  * This routine is invoked to post rpi header templates to the
19719  * HBA consistent with the SLI-4 interface spec.  This routine
19720  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19721  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19722  *
19723  * Returns
19724  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
19725  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
19726  **/
19727 int
19728 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
19729 {
19730 	unsigned long rpi;
19731 	uint16_t max_rpi, rpi_limit;
19732 	uint16_t rpi_remaining, lrpi = 0;
19733 	struct lpfc_rpi_hdr *rpi_hdr;
19734 	unsigned long iflag;
19735 
19736 	/*
19737 	 * Fetch the next logical rpi.  Because this index is logical,
19738 	 * the  driver starts at 0 each time.
19739 	 */
19740 	spin_lock_irqsave(&phba->hbalock, iflag);
19741 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
19742 	rpi_limit = phba->sli4_hba.next_rpi;
19743 
19744 	rpi = find_first_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit);
19745 	if (rpi >= rpi_limit)
19746 		rpi = LPFC_RPI_ALLOC_ERROR;
19747 	else {
19748 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
19749 		phba->sli4_hba.max_cfg_param.rpi_used++;
19750 		phba->sli4_hba.rpi_count++;
19751 	}
19752 	lpfc_printf_log(phba, KERN_INFO,
19753 			LOG_NODE | LOG_DISCOVERY,
19754 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
19755 			(int) rpi, max_rpi, rpi_limit);
19756 
19757 	/*
19758 	 * Don't try to allocate more rpi header regions if the device limit
19759 	 * has been exhausted.
19760 	 */
19761 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
19762 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
19763 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19764 		return rpi;
19765 	}
19766 
19767 	/*
19768 	 * RPI header postings are not required for SLI4 ports capable of
19769 	 * extents.
19770 	 */
19771 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
19772 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19773 		return rpi;
19774 	}
19775 
19776 	/*
19777 	 * If the driver is running low on rpi resources, allocate another
19778 	 * page now.  Note that the next_rpi value is used because
19779 	 * it represents how many are actually in use whereas max_rpi notes
19780 	 * how many are supported max by the device.
19781 	 */
19782 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
19783 	spin_unlock_irqrestore(&phba->hbalock, iflag);
19784 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
19785 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
19786 		if (!rpi_hdr) {
19787 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19788 					"2002 Error Could not grow rpi "
19789 					"count\n");
19790 		} else {
19791 			lrpi = rpi_hdr->start_rpi;
19792 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19793 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
19794 		}
19795 	}
19796 
19797 	return rpi;
19798 }
19799 
19800 /**
19801  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
19802  * @phba: pointer to lpfc hba data structure.
19803  * @rpi: rpi to free
19804  *
19805  * This routine is invoked to release an rpi to the pool of
19806  * available rpis maintained by the driver.
19807  **/
19808 static void
19809 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19810 {
19811 	/*
19812 	 * if the rpi value indicates a prior unreg has already
19813 	 * been done, skip the unreg.
19814 	 */
19815 	if (rpi == LPFC_RPI_ALLOC_ERROR)
19816 		return;
19817 
19818 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
19819 		phba->sli4_hba.rpi_count--;
19820 		phba->sli4_hba.max_cfg_param.rpi_used--;
19821 	} else {
19822 		lpfc_printf_log(phba, KERN_INFO,
19823 				LOG_NODE | LOG_DISCOVERY,
19824 				"2016 rpi %x not inuse\n",
19825 				rpi);
19826 	}
19827 }
19828 
19829 /**
19830  * lpfc_sli4_free_rpi - Release an rpi for reuse.
19831  * @phba: pointer to lpfc hba data structure.
19832  * @rpi: rpi to free
19833  *
19834  * This routine is invoked to release an rpi to the pool of
19835  * available rpis maintained by the driver.
19836  **/
19837 void
19838 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19839 {
19840 	spin_lock_irq(&phba->hbalock);
19841 	__lpfc_sli4_free_rpi(phba, rpi);
19842 	spin_unlock_irq(&phba->hbalock);
19843 }
19844 
19845 /**
19846  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19847  * @phba: pointer to lpfc hba data structure.
19848  *
19849  * This routine is invoked to remove the memory region that
19850  * provided rpi via a bitmask.
19851  **/
19852 void
19853 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19854 {
19855 	kfree(phba->sli4_hba.rpi_bmask);
19856 	kfree(phba->sli4_hba.rpi_ids);
19857 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19858 }
19859 
19860 /**
19861  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
19862  * @ndlp: pointer to lpfc nodelist data structure.
19863  * @cmpl: completion call-back.
19864  * @iocbq: data to load as mbox ctx_u information
19865  *
19866  * This routine is invoked to remove the memory region that
19867  * provided rpi via a bitmask.
19868  **/
19869 int
19870 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19871 		     void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *),
19872 		     struct lpfc_iocbq *iocbq)
19873 {
19874 	LPFC_MBOXQ_t *mboxq;
19875 	struct lpfc_hba *phba = ndlp->phba;
19876 	int rc;
19877 
19878 	/* The port is notified of the header region via a mailbox command. */
19879 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19880 	if (!mboxq)
19881 		return -ENOMEM;
19882 
19883 	/* If cmpl assigned, then this nlp_get pairs with
19884 	 * lpfc_mbx_cmpl_resume_rpi.
19885 	 *
19886 	 * Else cmpl is NULL, then this nlp_get pairs with
19887 	 * lpfc_sli_def_mbox_cmpl.
19888 	 */
19889 	if (!lpfc_nlp_get(ndlp)) {
19890 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19891 				"2122 %s: Failed to get nlp ref\n",
19892 				__func__);
19893 		mempool_free(mboxq, phba->mbox_mem_pool);
19894 		return -EIO;
19895 	}
19896 
19897 	/* Post all rpi memory regions to the port. */
19898 	lpfc_resume_rpi(mboxq, ndlp);
19899 	if (cmpl) {
19900 		mboxq->mbox_cmpl = cmpl;
19901 		mboxq->ctx_u.save_iocb = iocbq;
19902 	} else
19903 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19904 	mboxq->ctx_ndlp = ndlp;
19905 	mboxq->vport = ndlp->vport;
19906 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19907 	if (rc == MBX_NOT_FINISHED) {
19908 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19909 				"2010 Resume RPI Mailbox failed "
19910 				"status %d, mbxStatus x%x\n", rc,
19911 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19912 		lpfc_nlp_put(ndlp);
19913 		mempool_free(mboxq, phba->mbox_mem_pool);
19914 		return -EIO;
19915 	}
19916 	return 0;
19917 }
19918 
19919 /**
19920  * lpfc_sli4_init_vpi - Initialize a vpi with the port
19921  * @vport: Pointer to the vport for which the vpi is being initialized
19922  *
19923  * This routine is invoked to activate a vpi with the port.
19924  *
19925  * Returns:
19926  *    0 success
19927  *    -Evalue otherwise
19928  **/
19929 int
19930 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
19931 {
19932 	LPFC_MBOXQ_t *mboxq;
19933 	int rc = 0;
19934 	int retval = MBX_SUCCESS;
19935 	uint32_t mbox_tmo;
19936 	struct lpfc_hba *phba = vport->phba;
19937 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19938 	if (!mboxq)
19939 		return -ENOMEM;
19940 	lpfc_init_vpi(phba, mboxq, vport->vpi);
19941 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
19942 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
19943 	if (rc != MBX_SUCCESS) {
19944 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19945 				"2022 INIT VPI Mailbox failed "
19946 				"status %d, mbxStatus x%x\n", rc,
19947 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19948 		retval = -EIO;
19949 	}
19950 	if (rc != MBX_TIMEOUT)
19951 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
19952 
19953 	return retval;
19954 }
19955 
19956 /**
19957  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
19958  * @phba: pointer to lpfc hba data structure.
19959  * @mboxq: Pointer to mailbox object.
19960  *
19961  * This routine is invoked to manually add a single FCF record. The caller
19962  * must pass a completely initialized FCF_Record.  This routine takes
19963  * care of the nonembedded mailbox operations.
19964  **/
19965 static void
19966 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
19967 {
19968 	void *virt_addr;
19969 	union lpfc_sli4_cfg_shdr *shdr;
19970 	uint32_t shdr_status, shdr_add_status;
19971 
19972 	virt_addr = mboxq->sge_array->addr[0];
19973 	/* The IOCTL status is embedded in the mailbox subheader. */
19974 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
19975 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19976 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19977 
19978 	if ((shdr_status || shdr_add_status) &&
19979 		(shdr_status != STATUS_FCF_IN_USE))
19980 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19981 			"2558 ADD_FCF_RECORD mailbox failed with "
19982 			"status x%x add_status x%x\n",
19983 			shdr_status, shdr_add_status);
19984 
19985 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
19986 }
19987 
19988 /**
19989  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
19990  * @phba: pointer to lpfc hba data structure.
19991  * @fcf_record:  pointer to the initialized fcf record to add.
19992  *
19993  * This routine is invoked to manually add a single FCF record. The caller
19994  * must pass a completely initialized FCF_Record.  This routine takes
19995  * care of the nonembedded mailbox operations.
19996  **/
19997 int
19998 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
19999 {
20000 	int rc = 0;
20001 	LPFC_MBOXQ_t *mboxq;
20002 	uint8_t *bytep;
20003 	void *virt_addr;
20004 	struct lpfc_mbx_sge sge;
20005 	uint32_t alloc_len, req_len;
20006 	uint32_t fcfindex;
20007 
20008 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20009 	if (!mboxq) {
20010 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20011 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
20012 		return -ENOMEM;
20013 	}
20014 
20015 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
20016 		  sizeof(uint32_t);
20017 
20018 	/* Allocate DMA memory and set up the non-embedded mailbox command */
20019 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
20020 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
20021 				     req_len, LPFC_SLI4_MBX_NEMBED);
20022 	if (alloc_len < req_len) {
20023 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20024 			"2523 Allocated DMA memory size (x%x) is "
20025 			"less than the requested DMA memory "
20026 			"size (x%x)\n", alloc_len, req_len);
20027 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20028 		return -ENOMEM;
20029 	}
20030 
20031 	/*
20032 	 * Get the first SGE entry from the non-embedded DMA memory.  This
20033 	 * routine only uses a single SGE.
20034 	 */
20035 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
20036 	virt_addr = mboxq->sge_array->addr[0];
20037 	/*
20038 	 * Configure the FCF record for FCFI 0.  This is the driver's
20039 	 * hardcoded default and gets used in nonFIP mode.
20040 	 */
20041 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
20042 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
20043 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
20044 
20045 	/*
20046 	 * Copy the fcf_index and the FCF Record Data. The data starts after
20047 	 * the FCoE header plus word10. The data copy needs to be endian
20048 	 * correct.
20049 	 */
20050 	bytep += sizeof(uint32_t);
20051 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
20052 	mboxq->vport = phba->pport;
20053 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
20054 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20055 	if (rc == MBX_NOT_FINISHED) {
20056 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20057 			"2515 ADD_FCF_RECORD mailbox failed with "
20058 			"status 0x%x\n", rc);
20059 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20060 		rc = -EIO;
20061 	} else
20062 		rc = 0;
20063 
20064 	return rc;
20065 }
20066 
20067 /**
20068  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
20069  * @phba: pointer to lpfc hba data structure.
20070  * @fcf_record:  pointer to the fcf record to write the default data.
20071  * @fcf_index: FCF table entry index.
20072  *
20073  * This routine is invoked to build the driver's default FCF record.  The
20074  * values used are hardcoded.  This routine handles memory initialization.
20075  *
20076  **/
20077 void
20078 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
20079 				struct fcf_record *fcf_record,
20080 				uint16_t fcf_index)
20081 {
20082 	memset(fcf_record, 0, sizeof(struct fcf_record));
20083 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
20084 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
20085 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
20086 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
20087 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
20088 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
20089 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
20090 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
20091 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
20092 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
20093 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
20094 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
20095 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
20096 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
20097 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
20098 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
20099 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
20100 	/* Set the VLAN bit map */
20101 	if (phba->valid_vlan) {
20102 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
20103 			= 1 << (phba->vlan_id % 8);
20104 	}
20105 }
20106 
20107 /**
20108  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
20109  * @phba: pointer to lpfc hba data structure.
20110  * @fcf_index: FCF table entry offset.
20111  *
20112  * This routine is invoked to scan the entire FCF table by reading FCF
20113  * record and processing it one at a time starting from the @fcf_index
20114  * for initial FCF discovery or fast FCF failover rediscovery.
20115  *
20116  * Return 0 if the mailbox command is submitted successfully, none 0
20117  * otherwise.
20118  **/
20119 int
20120 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20121 {
20122 	int rc = 0, error;
20123 	LPFC_MBOXQ_t *mboxq;
20124 
20125 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
20126 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
20127 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20128 	if (!mboxq) {
20129 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20130 				"2000 Failed to allocate mbox for "
20131 				"READ_FCF cmd\n");
20132 		error = -ENOMEM;
20133 		goto fail_fcf_scan;
20134 	}
20135 	/* Construct the read FCF record mailbox command */
20136 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20137 	if (rc) {
20138 		error = -EINVAL;
20139 		goto fail_fcf_scan;
20140 	}
20141 	/* Issue the mailbox command asynchronously */
20142 	mboxq->vport = phba->pport;
20143 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
20144 
20145 	set_bit(FCF_TS_INPROG, &phba->hba_flag);
20146 
20147 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20148 	if (rc == MBX_NOT_FINISHED)
20149 		error = -EIO;
20150 	else {
20151 		/* Reset eligible FCF count for new scan */
20152 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
20153 			phba->fcf.eligible_fcf_cnt = 0;
20154 		error = 0;
20155 	}
20156 fail_fcf_scan:
20157 	if (error) {
20158 		if (mboxq)
20159 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
20160 		/* FCF scan failed, clear FCF_TS_INPROG flag */
20161 		clear_bit(FCF_TS_INPROG, &phba->hba_flag);
20162 	}
20163 	return error;
20164 }
20165 
20166 /**
20167  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
20168  * @phba: pointer to lpfc hba data structure.
20169  * @fcf_index: FCF table entry offset.
20170  *
20171  * This routine is invoked to read an FCF record indicated by @fcf_index
20172  * and to use it for FLOGI roundrobin FCF failover.
20173  *
20174  * Return 0 if the mailbox command is submitted successfully, none 0
20175  * otherwise.
20176  **/
20177 int
20178 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20179 {
20180 	int rc = 0, error;
20181 	LPFC_MBOXQ_t *mboxq;
20182 
20183 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20184 	if (!mboxq) {
20185 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20186 				"2763 Failed to allocate mbox for "
20187 				"READ_FCF cmd\n");
20188 		error = -ENOMEM;
20189 		goto fail_fcf_read;
20190 	}
20191 	/* Construct the read FCF record mailbox command */
20192 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20193 	if (rc) {
20194 		error = -EINVAL;
20195 		goto fail_fcf_read;
20196 	}
20197 	/* Issue the mailbox command asynchronously */
20198 	mboxq->vport = phba->pport;
20199 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
20200 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20201 	if (rc == MBX_NOT_FINISHED)
20202 		error = -EIO;
20203 	else
20204 		error = 0;
20205 
20206 fail_fcf_read:
20207 	if (error && mboxq)
20208 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20209 	return error;
20210 }
20211 
20212 /**
20213  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
20214  * @phba: pointer to lpfc hba data structure.
20215  * @fcf_index: FCF table entry offset.
20216  *
20217  * This routine is invoked to read an FCF record indicated by @fcf_index to
20218  * determine whether it's eligible for FLOGI roundrobin failover list.
20219  *
20220  * Return 0 if the mailbox command is submitted successfully, none 0
20221  * otherwise.
20222  **/
20223 int
20224 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20225 {
20226 	int rc = 0, error;
20227 	LPFC_MBOXQ_t *mboxq;
20228 
20229 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20230 	if (!mboxq) {
20231 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20232 				"2758 Failed to allocate mbox for "
20233 				"READ_FCF cmd\n");
20234 				error = -ENOMEM;
20235 				goto fail_fcf_read;
20236 	}
20237 	/* Construct the read FCF record mailbox command */
20238 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20239 	if (rc) {
20240 		error = -EINVAL;
20241 		goto fail_fcf_read;
20242 	}
20243 	/* Issue the mailbox command asynchronously */
20244 	mboxq->vport = phba->pport;
20245 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
20246 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20247 	if (rc == MBX_NOT_FINISHED)
20248 		error = -EIO;
20249 	else
20250 		error = 0;
20251 
20252 fail_fcf_read:
20253 	if (error && mboxq)
20254 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20255 	return error;
20256 }
20257 
20258 /**
20259  * lpfc_check_next_fcf_pri_level
20260  * @phba: pointer to the lpfc_hba struct for this port.
20261  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
20262  * routine when the rr_bmask is empty. The FCF indecies are put into the
20263  * rr_bmask based on their priority level. Starting from the highest priority
20264  * to the lowest. The most likely FCF candidate will be in the highest
20265  * priority group. When this routine is called it searches the fcf_pri list for
20266  * next lowest priority group and repopulates the rr_bmask with only those
20267  * fcf_indexes.
20268  * returns:
20269  * 1=success 0=failure
20270  **/
20271 static int
20272 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
20273 {
20274 	uint16_t next_fcf_pri;
20275 	uint16_t last_index;
20276 	struct lpfc_fcf_pri *fcf_pri;
20277 	int rc;
20278 	int ret = 0;
20279 
20280 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20281 			LPFC_SLI4_FCF_TBL_INDX_MAX);
20282 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20283 			"3060 Last IDX %d\n", last_index);
20284 
20285 	/* Verify the priority list has 2 or more entries */
20286 	spin_lock_irq(&phba->hbalock);
20287 	if (list_empty(&phba->fcf.fcf_pri_list) ||
20288 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
20289 		spin_unlock_irq(&phba->hbalock);
20290 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20291 			"3061 Last IDX %d\n", last_index);
20292 		return 0; /* Empty rr list */
20293 	}
20294 	spin_unlock_irq(&phba->hbalock);
20295 
20296 	next_fcf_pri = 0;
20297 	/*
20298 	 * Clear the rr_bmask and set all of the bits that are at this
20299 	 * priority.
20300 	 */
20301 	memset(phba->fcf.fcf_rr_bmask, 0,
20302 			sizeof(*phba->fcf.fcf_rr_bmask));
20303 	spin_lock_irq(&phba->hbalock);
20304 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20305 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
20306 			continue;
20307 		/*
20308 		 * the 1st priority that has not FLOGI failed
20309 		 * will be the highest.
20310 		 */
20311 		if (!next_fcf_pri)
20312 			next_fcf_pri = fcf_pri->fcf_rec.priority;
20313 		spin_unlock_irq(&phba->hbalock);
20314 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20315 			rc = lpfc_sli4_fcf_rr_index_set(phba,
20316 						fcf_pri->fcf_rec.fcf_index);
20317 			if (rc)
20318 				return 0;
20319 		}
20320 		spin_lock_irq(&phba->hbalock);
20321 	}
20322 	/*
20323 	 * if next_fcf_pri was not set above and the list is not empty then
20324 	 * we have failed flogis on all of them. So reset flogi failed
20325 	 * and start at the beginning.
20326 	 */
20327 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
20328 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20329 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
20330 			/*
20331 			 * the 1st priority that has not FLOGI failed
20332 			 * will be the highest.
20333 			 */
20334 			if (!next_fcf_pri)
20335 				next_fcf_pri = fcf_pri->fcf_rec.priority;
20336 			spin_unlock_irq(&phba->hbalock);
20337 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20338 				rc = lpfc_sli4_fcf_rr_index_set(phba,
20339 						fcf_pri->fcf_rec.fcf_index);
20340 				if (rc)
20341 					return 0;
20342 			}
20343 			spin_lock_irq(&phba->hbalock);
20344 		}
20345 	} else
20346 		ret = 1;
20347 	spin_unlock_irq(&phba->hbalock);
20348 
20349 	return ret;
20350 }
20351 /**
20352  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
20353  * @phba: pointer to lpfc hba data structure.
20354  *
20355  * This routine is to get the next eligible FCF record index in a round
20356  * robin fashion. If the next eligible FCF record index equals to the
20357  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
20358  * shall be returned, otherwise, the next eligible FCF record's index
20359  * shall be returned.
20360  **/
20361 uint16_t
20362 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
20363 {
20364 	uint16_t next_fcf_index;
20365 
20366 initial_priority:
20367 	/* Search start from next bit of currently registered FCF index */
20368 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
20369 
20370 next_priority:
20371 	/* Determine the next fcf index to check */
20372 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
20373 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
20374 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
20375 				       next_fcf_index);
20376 
20377 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
20378 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20379 		/*
20380 		 * If we have wrapped then we need to clear the bits that
20381 		 * have been tested so that we can detect when we should
20382 		 * change the priority level.
20383 		 */
20384 		next_fcf_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20385 					       LPFC_SLI4_FCF_TBL_INDX_MAX);
20386 	}
20387 
20388 
20389 	/* Check roundrobin failover list empty condition */
20390 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
20391 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
20392 		/*
20393 		 * If next fcf index is not found check if there are lower
20394 		 * Priority level fcf's in the fcf_priority list.
20395 		 * Set up the rr_bmask with all of the avaiable fcf bits
20396 		 * at that level and continue the selection process.
20397 		 */
20398 		if (lpfc_check_next_fcf_pri_level(phba))
20399 			goto initial_priority;
20400 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
20401 				"2844 No roundrobin failover FCF available\n");
20402 
20403 		return LPFC_FCOE_FCF_NEXT_NONE;
20404 	}
20405 
20406 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
20407 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
20408 		LPFC_FCF_FLOGI_FAILED) {
20409 		if (list_is_singular(&phba->fcf.fcf_pri_list))
20410 			return LPFC_FCOE_FCF_NEXT_NONE;
20411 
20412 		goto next_priority;
20413 	}
20414 
20415 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20416 			"2845 Get next roundrobin failover FCF (x%x)\n",
20417 			next_fcf_index);
20418 
20419 	return next_fcf_index;
20420 }
20421 
20422 /**
20423  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
20424  * @phba: pointer to lpfc hba data structure.
20425  * @fcf_index: index into the FCF table to 'set'
20426  *
20427  * This routine sets the FCF record index in to the eligible bmask for
20428  * roundrobin failover search. It checks to make sure that the index
20429  * does not go beyond the range of the driver allocated bmask dimension
20430  * before setting the bit.
20431  *
20432  * Returns 0 if the index bit successfully set, otherwise, it returns
20433  * -EINVAL.
20434  **/
20435 int
20436 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
20437 {
20438 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20439 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20440 				"2610 FCF (x%x) reached driver's book "
20441 				"keeping dimension:x%x\n",
20442 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20443 		return -EINVAL;
20444 	}
20445 	/* Set the eligible FCF record index bmask */
20446 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20447 
20448 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20449 			"2790 Set FCF (x%x) to roundrobin FCF failover "
20450 			"bmask\n", fcf_index);
20451 
20452 	return 0;
20453 }
20454 
20455 /**
20456  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
20457  * @phba: pointer to lpfc hba data structure.
20458  * @fcf_index: index into the FCF table to 'clear'
20459  *
20460  * This routine clears the FCF record index from the eligible bmask for
20461  * roundrobin failover search. It checks to make sure that the index
20462  * does not go beyond the range of the driver allocated bmask dimension
20463  * before clearing the bit.
20464  **/
20465 void
20466 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
20467 {
20468 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
20469 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20470 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20471 				"2762 FCF (x%x) reached driver's book "
20472 				"keeping dimension:x%x\n",
20473 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20474 		return;
20475 	}
20476 	/* Clear the eligible FCF record index bmask */
20477 	spin_lock_irq(&phba->hbalock);
20478 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
20479 				 list) {
20480 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
20481 			list_del_init(&fcf_pri->list);
20482 			break;
20483 		}
20484 	}
20485 	spin_unlock_irq(&phba->hbalock);
20486 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20487 
20488 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20489 			"2791 Clear FCF (x%x) from roundrobin failover "
20490 			"bmask\n", fcf_index);
20491 }
20492 
20493 /**
20494  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
20495  * @phba: pointer to lpfc hba data structure.
20496  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
20497  *
20498  * This routine is the completion routine for the rediscover FCF table mailbox
20499  * command. If the mailbox command returned failure, it will try to stop the
20500  * FCF rediscover wait timer.
20501  **/
20502 static void
20503 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
20504 {
20505 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20506 	uint32_t shdr_status, shdr_add_status;
20507 
20508 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20509 
20510 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20511 			     &redisc_fcf->header.cfg_shdr.response);
20512 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20513 			     &redisc_fcf->header.cfg_shdr.response);
20514 	if (shdr_status || shdr_add_status) {
20515 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20516 				"2746 Requesting for FCF rediscovery failed "
20517 				"status x%x add_status x%x\n",
20518 				shdr_status, shdr_add_status);
20519 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
20520 			spin_lock_irq(&phba->hbalock);
20521 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
20522 			spin_unlock_irq(&phba->hbalock);
20523 			/*
20524 			 * CVL event triggered FCF rediscover request failed,
20525 			 * last resort to re-try current registered FCF entry.
20526 			 */
20527 			lpfc_retry_pport_discovery(phba);
20528 		} else {
20529 			spin_lock_irq(&phba->hbalock);
20530 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
20531 			spin_unlock_irq(&phba->hbalock);
20532 			/*
20533 			 * DEAD FCF event triggered FCF rediscover request
20534 			 * failed, last resort to fail over as a link down
20535 			 * to FCF registration.
20536 			 */
20537 			lpfc_sli4_fcf_dead_failthrough(phba);
20538 		}
20539 	} else {
20540 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20541 				"2775 Start FCF rediscover quiescent timer\n");
20542 		/*
20543 		 * Start FCF rediscovery wait timer for pending FCF
20544 		 * before rescan FCF record table.
20545 		 */
20546 		lpfc_fcf_redisc_wait_start_timer(phba);
20547 	}
20548 
20549 	mempool_free(mbox, phba->mbox_mem_pool);
20550 }
20551 
20552 /**
20553  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
20554  * @phba: pointer to lpfc hba data structure.
20555  *
20556  * This routine is invoked to request for rediscovery of the entire FCF table
20557  * by the port.
20558  **/
20559 int
20560 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
20561 {
20562 	LPFC_MBOXQ_t *mbox;
20563 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20564 	int rc, length;
20565 
20566 	/* Cancel retry delay timers to all vports before FCF rediscover */
20567 	lpfc_cancel_all_vport_retry_delay_timer(phba);
20568 
20569 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20570 	if (!mbox) {
20571 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20572 				"2745 Failed to allocate mbox for "
20573 				"requesting FCF rediscover.\n");
20574 		return -ENOMEM;
20575 	}
20576 
20577 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
20578 		  sizeof(struct lpfc_sli4_cfg_mhdr));
20579 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
20580 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
20581 			 length, LPFC_SLI4_MBX_EMBED);
20582 
20583 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20584 	/* Set count to 0 for invalidating the entire FCF database */
20585 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
20586 
20587 	/* Issue the mailbox command asynchronously */
20588 	mbox->vport = phba->pport;
20589 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
20590 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
20591 
20592 	if (rc == MBX_NOT_FINISHED) {
20593 		mempool_free(mbox, phba->mbox_mem_pool);
20594 		return -EIO;
20595 	}
20596 	return 0;
20597 }
20598 
20599 /**
20600  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
20601  * @phba: pointer to lpfc hba data structure.
20602  *
20603  * This function is the failover routine as a last resort to the FCF DEAD
20604  * event when driver failed to perform fast FCF failover.
20605  **/
20606 void
20607 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
20608 {
20609 	uint32_t link_state;
20610 
20611 	/*
20612 	 * Last resort as FCF DEAD event failover will treat this as
20613 	 * a link down, but save the link state because we don't want
20614 	 * it to be changed to Link Down unless it is already down.
20615 	 */
20616 	link_state = phba->link_state;
20617 	lpfc_linkdown(phba);
20618 	phba->link_state = link_state;
20619 
20620 	/* Unregister FCF if no devices connected to it */
20621 	lpfc_unregister_unused_fcf(phba);
20622 }
20623 
20624 /**
20625  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
20626  * @phba: pointer to lpfc hba data structure.
20627  * @rgn23_data: pointer to configure region 23 data.
20628  *
20629  * This function gets SLI3 port configure region 23 data through memory dump
20630  * mailbox command. When it successfully retrieves data, the size of the data
20631  * will be returned, otherwise, 0 will be returned.
20632  **/
20633 static uint32_t
20634 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20635 {
20636 	LPFC_MBOXQ_t *pmb = NULL;
20637 	MAILBOX_t *mb;
20638 	uint32_t offset = 0;
20639 	int rc;
20640 
20641 	if (!rgn23_data)
20642 		return 0;
20643 
20644 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20645 	if (!pmb) {
20646 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20647 				"2600 failed to allocate mailbox memory\n");
20648 		return 0;
20649 	}
20650 	mb = &pmb->u.mb;
20651 
20652 	do {
20653 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
20654 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
20655 
20656 		if (rc != MBX_SUCCESS) {
20657 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20658 					"2601 failed to read config "
20659 					"region 23, rc 0x%x Status 0x%x\n",
20660 					rc, mb->mbxStatus);
20661 			mb->un.varDmp.word_cnt = 0;
20662 		}
20663 		/*
20664 		 * dump mem may return a zero when finished or we got a
20665 		 * mailbox error, either way we are done.
20666 		 */
20667 		if (mb->un.varDmp.word_cnt == 0)
20668 			break;
20669 
20670 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
20671 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
20672 
20673 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
20674 				       rgn23_data + offset,
20675 				       mb->un.varDmp.word_cnt);
20676 		offset += mb->un.varDmp.word_cnt;
20677 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
20678 
20679 	mempool_free(pmb, phba->mbox_mem_pool);
20680 	return offset;
20681 }
20682 
20683 /**
20684  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
20685  * @phba: pointer to lpfc hba data structure.
20686  * @rgn23_data: pointer to configure region 23 data.
20687  *
20688  * This function gets SLI4 port configure region 23 data through memory dump
20689  * mailbox command. When it successfully retrieves data, the size of the data
20690  * will be returned, otherwise, 0 will be returned.
20691  **/
20692 static uint32_t
20693 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20694 {
20695 	LPFC_MBOXQ_t *mboxq = NULL;
20696 	struct lpfc_dmabuf *mp = NULL;
20697 	struct lpfc_mqe *mqe;
20698 	uint32_t data_length = 0;
20699 	int rc;
20700 
20701 	if (!rgn23_data)
20702 		return 0;
20703 
20704 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20705 	if (!mboxq) {
20706 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20707 				"3105 failed to allocate mailbox memory\n");
20708 		return 0;
20709 	}
20710 
20711 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
20712 		goto out;
20713 	mqe = &mboxq->u.mqe;
20714 	mp = mboxq->ctx_buf;
20715 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
20716 	if (rc)
20717 		goto out;
20718 	data_length = mqe->un.mb_words[5];
20719 	if (data_length == 0)
20720 		goto out;
20721 	if (data_length > DMP_RGN23_SIZE) {
20722 		data_length = 0;
20723 		goto out;
20724 	}
20725 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
20726 out:
20727 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
20728 	return data_length;
20729 }
20730 
20731 /**
20732  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
20733  * @phba: pointer to lpfc hba data structure.
20734  *
20735  * This function read region 23 and parse TLV for port status to
20736  * decide if the user disaled the port. If the TLV indicates the
20737  * port is disabled, the hba_flag is set accordingly.
20738  **/
20739 void
20740 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
20741 {
20742 	uint8_t *rgn23_data = NULL;
20743 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
20744 	uint32_t offset = 0;
20745 
20746 	/* Get adapter Region 23 data */
20747 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
20748 	if (!rgn23_data)
20749 		goto out;
20750 
20751 	if (phba->sli_rev < LPFC_SLI_REV4)
20752 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
20753 	else {
20754 		if_type = bf_get(lpfc_sli_intf_if_type,
20755 				 &phba->sli4_hba.sli_intf);
20756 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
20757 			goto out;
20758 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
20759 	}
20760 
20761 	if (!data_size)
20762 		goto out;
20763 
20764 	/* Check the region signature first */
20765 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
20766 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20767 			"2619 Config region 23 has bad signature\n");
20768 			goto out;
20769 	}
20770 	offset += 4;
20771 
20772 	/* Check the data structure version */
20773 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
20774 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20775 			"2620 Config region 23 has bad version\n");
20776 		goto out;
20777 	}
20778 	offset += 4;
20779 
20780 	/* Parse TLV entries in the region */
20781 	while (offset < data_size) {
20782 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
20783 			break;
20784 		/*
20785 		 * If the TLV is not driver specific TLV or driver id is
20786 		 * not linux driver id, skip the record.
20787 		 */
20788 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
20789 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
20790 		    (rgn23_data[offset + 3] != 0)) {
20791 			offset += rgn23_data[offset + 1] * 4 + 4;
20792 			continue;
20793 		}
20794 
20795 		/* Driver found a driver specific TLV in the config region */
20796 		sub_tlv_len = rgn23_data[offset + 1] * 4;
20797 		offset += 4;
20798 		tlv_offset = 0;
20799 
20800 		/*
20801 		 * Search for configured port state sub-TLV.
20802 		 */
20803 		while ((offset < data_size) &&
20804 			(tlv_offset < sub_tlv_len)) {
20805 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
20806 				offset += 4;
20807 				tlv_offset += 4;
20808 				break;
20809 			}
20810 			if (rgn23_data[offset] != PORT_STE_TYPE) {
20811 				offset += rgn23_data[offset + 1] * 4 + 4;
20812 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
20813 				continue;
20814 			}
20815 
20816 			/* This HBA contains PORT_STE configured */
20817 			if (!rgn23_data[offset + 2])
20818 				set_bit(LINK_DISABLED, &phba->hba_flag);
20819 
20820 			goto out;
20821 		}
20822 	}
20823 
20824 out:
20825 	kfree(rgn23_data);
20826 	return;
20827 }
20828 
20829 /**
20830  * lpfc_log_fw_write_cmpl - logs firmware write completion status
20831  * @phba: pointer to lpfc hba data structure
20832  * @shdr_status: wr_object rsp's status field
20833  * @shdr_add_status: wr_object rsp's add_status field
20834  * @shdr_add_status_2: wr_object rsp's add_status_2 field
20835  * @shdr_change_status: wr_object rsp's change_status field
20836  * @shdr_csf: wr_object rsp's csf bit
20837  *
20838  * This routine is intended to be called after a firmware write completes.
20839  * It will log next action items to be performed by the user to instantiate
20840  * the newly downloaded firmware or reason for incompatibility.
20841  **/
20842 static void
20843 lpfc_log_fw_write_cmpl(struct lpfc_hba *phba, u32 shdr_status,
20844 		       u32 shdr_add_status, u32 shdr_add_status_2,
20845 		       u32 shdr_change_status, u32 shdr_csf)
20846 {
20847 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20848 			"4198 %s: flash_id x%02x, asic_rev x%02x, "
20849 			"status x%02x, add_status x%02x, add_status_2 x%02x, "
20850 			"change_status x%02x, csf %01x\n", __func__,
20851 			phba->sli4_hba.flash_id, phba->sli4_hba.asic_rev,
20852 			shdr_status, shdr_add_status, shdr_add_status_2,
20853 			shdr_change_status, shdr_csf);
20854 
20855 	if (shdr_add_status == LPFC_ADD_STATUS_INCOMPAT_OBJ) {
20856 		switch (shdr_add_status_2) {
20857 		case LPFC_ADD_STATUS_2_INCOMPAT_FLASH:
20858 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20859 				     "4199 Firmware write failed: "
20860 				     "image incompatible with flash x%02x\n",
20861 				     phba->sli4_hba.flash_id);
20862 			break;
20863 		case LPFC_ADD_STATUS_2_INCORRECT_ASIC:
20864 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20865 				     "4200 Firmware write failed: "
20866 				     "image incompatible with ASIC "
20867 				     "architecture x%02x\n",
20868 				     phba->sli4_hba.asic_rev);
20869 			break;
20870 		default:
20871 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20872 				     "4210 Firmware write failed: "
20873 				     "add_status_2 x%02x\n",
20874 				     shdr_add_status_2);
20875 			break;
20876 		}
20877 	} else if (!shdr_status && !shdr_add_status) {
20878 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20879 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20880 			if (shdr_csf)
20881 				shdr_change_status =
20882 						   LPFC_CHANGE_STATUS_PCI_RESET;
20883 		}
20884 
20885 		switch (shdr_change_status) {
20886 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20887 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20888 				     "3198 Firmware write complete: System "
20889 				     "reboot required to instantiate\n");
20890 			break;
20891 		case (LPFC_CHANGE_STATUS_FW_RESET):
20892 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20893 				     "3199 Firmware write complete: "
20894 				     "Firmware reset required to "
20895 				     "instantiate\n");
20896 			break;
20897 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20898 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20899 				     "3200 Firmware write complete: Port "
20900 				     "Migration or PCI Reset required to "
20901 				     "instantiate\n");
20902 			break;
20903 		case (LPFC_CHANGE_STATUS_PCI_RESET):
20904 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20905 				     "3201 Firmware write complete: PCI "
20906 				     "Reset required to instantiate\n");
20907 			break;
20908 		default:
20909 			break;
20910 		}
20911 	}
20912 }
20913 
20914 /**
20915  * lpfc_wr_object - write an object to the firmware
20916  * @phba: HBA structure that indicates port to create a queue on.
20917  * @dmabuf_list: list of dmabufs to write to the port.
20918  * @size: the total byte value of the objects to write to the port.
20919  * @offset: the current offset to be used to start the transfer.
20920  *
20921  * This routine will create a wr_object mailbox command to send to the port.
20922  * the mailbox command will be constructed using the dma buffers described in
20923  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
20924  * BDEs that the imbedded mailbox can support. The @offset variable will be
20925  * used to indicate the starting offset of the transfer and will also return
20926  * the offset after the write object mailbox has completed. @size is used to
20927  * determine the end of the object and whether the eof bit should be set.
20928  *
20929  * Return 0 is successful and offset will contain the new offset to use
20930  * for the next write.
20931  * Return negative value for error cases.
20932  **/
20933 int
20934 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
20935 	       uint32_t size, uint32_t *offset)
20936 {
20937 	struct lpfc_mbx_wr_object *wr_object;
20938 	LPFC_MBOXQ_t *mbox;
20939 	int rc = 0, i = 0;
20940 	int mbox_status = 0;
20941 	uint32_t shdr_status, shdr_add_status, shdr_add_status_2;
20942 	uint32_t shdr_change_status = 0, shdr_csf = 0;
20943 	uint32_t mbox_tmo;
20944 	struct lpfc_dmabuf *dmabuf;
20945 	uint32_t written = 0;
20946 	bool check_change_status = false;
20947 
20948 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20949 	if (!mbox)
20950 		return -ENOMEM;
20951 
20952 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
20953 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
20954 			sizeof(struct lpfc_mbx_wr_object) -
20955 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
20956 
20957 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
20958 	wr_object->u.request.write_offset = *offset;
20959 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
20960 	wr_object->u.request.object_name[0] =
20961 		cpu_to_le32(wr_object->u.request.object_name[0]);
20962 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
20963 	list_for_each_entry(dmabuf, dmabuf_list, list) {
20964 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
20965 			break;
20966 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
20967 		wr_object->u.request.bde[i].addrHigh =
20968 			putPaddrHigh(dmabuf->phys);
20969 		if (written + SLI4_PAGE_SIZE >= size) {
20970 			wr_object->u.request.bde[i].tus.f.bdeSize =
20971 				(size - written);
20972 			written += (size - written);
20973 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
20974 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
20975 			check_change_status = true;
20976 		} else {
20977 			wr_object->u.request.bde[i].tus.f.bdeSize =
20978 				SLI4_PAGE_SIZE;
20979 			written += SLI4_PAGE_SIZE;
20980 		}
20981 		i++;
20982 	}
20983 	wr_object->u.request.bde_count = i;
20984 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
20985 	if (!phba->sli4_hba.intr_enable)
20986 		mbox_status = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
20987 	else {
20988 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
20989 		mbox_status = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
20990 	}
20991 
20992 	/* The mbox status needs to be maintained to detect MBOX_TIMEOUT. */
20993 	rc = mbox_status;
20994 
20995 	/* The IOCTL status is embedded in the mailbox subheader. */
20996 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20997 			     &wr_object->header.cfg_shdr.response);
20998 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20999 				 &wr_object->header.cfg_shdr.response);
21000 	shdr_add_status_2 = bf_get(lpfc_mbox_hdr_add_status_2,
21001 				   &wr_object->header.cfg_shdr.response);
21002 	if (check_change_status) {
21003 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
21004 					    &wr_object->u.response);
21005 		shdr_csf = bf_get(lpfc_wr_object_csf,
21006 				  &wr_object->u.response);
21007 	}
21008 
21009 	if (shdr_status || shdr_add_status || shdr_add_status_2 || rc) {
21010 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21011 				"3025 Write Object mailbox failed with "
21012 				"status x%x add_status x%x, add_status_2 x%x, "
21013 				"mbx status x%x\n",
21014 				shdr_status, shdr_add_status, shdr_add_status_2,
21015 				rc);
21016 		rc = -ENXIO;
21017 		*offset = shdr_add_status;
21018 	} else {
21019 		*offset += wr_object->u.response.actual_write_length;
21020 	}
21021 
21022 	if (rc || check_change_status)
21023 		lpfc_log_fw_write_cmpl(phba, shdr_status, shdr_add_status,
21024 				       shdr_add_status_2, shdr_change_status,
21025 				       shdr_csf);
21026 
21027 	if (!phba->sli4_hba.intr_enable)
21028 		mempool_free(mbox, phba->mbox_mem_pool);
21029 	else if (mbox_status != MBX_TIMEOUT)
21030 		mempool_free(mbox, phba->mbox_mem_pool);
21031 
21032 	return rc;
21033 }
21034 
21035 /**
21036  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
21037  * @vport: pointer to vport data structure.
21038  *
21039  * This function iterate through the mailboxq and clean up all REG_LOGIN
21040  * and REG_VPI mailbox commands associated with the vport. This function
21041  * is called when driver want to restart discovery of the vport due to
21042  * a Clear Virtual Link event.
21043  **/
21044 void
21045 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
21046 {
21047 	struct lpfc_hba *phba = vport->phba;
21048 	LPFC_MBOXQ_t *mb, *nextmb;
21049 	struct lpfc_nodelist *ndlp;
21050 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
21051 	LIST_HEAD(mbox_cmd_list);
21052 	uint8_t restart_loop;
21053 
21054 	/* Clean up internally queued mailbox commands with the vport */
21055 	spin_lock_irq(&phba->hbalock);
21056 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
21057 		if (mb->vport != vport)
21058 			continue;
21059 
21060 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21061 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
21062 			continue;
21063 
21064 		list_move_tail(&mb->list, &mbox_cmd_list);
21065 	}
21066 	/* Clean up active mailbox command with the vport */
21067 	mb = phba->sli.mbox_active;
21068 	if (mb && (mb->vport == vport)) {
21069 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
21070 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
21071 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21072 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21073 			act_mbx_ndlp = mb->ctx_ndlp;
21074 
21075 			/* This reference is local to this routine.  The
21076 			 * reference is removed at routine exit.
21077 			 */
21078 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
21079 
21080 			/* Unregister the RPI when mailbox complete */
21081 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21082 		}
21083 	}
21084 	/* Cleanup any mailbox completions which are not yet processed */
21085 	do {
21086 		restart_loop = 0;
21087 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
21088 			/*
21089 			 * If this mailox is already processed or it is
21090 			 * for another vport ignore it.
21091 			 */
21092 			if ((mb->vport != vport) ||
21093 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
21094 				continue;
21095 
21096 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21097 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
21098 				continue;
21099 
21100 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21101 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21102 				ndlp = mb->ctx_ndlp;
21103 				/* Unregister the RPI when mailbox complete */
21104 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21105 				restart_loop = 1;
21106 				clear_bit(NLP_IGNR_REG_CMPL, &ndlp->nlp_flag);
21107 				break;
21108 			}
21109 		}
21110 	} while (restart_loop);
21111 
21112 	spin_unlock_irq(&phba->hbalock);
21113 
21114 	/* Release the cleaned-up mailbox commands */
21115 	while (!list_empty(&mbox_cmd_list)) {
21116 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
21117 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21118 			ndlp = mb->ctx_ndlp;
21119 			mb->ctx_ndlp = NULL;
21120 			if (ndlp) {
21121 				clear_bit(NLP_IGNR_REG_CMPL, &ndlp->nlp_flag);
21122 				lpfc_nlp_put(ndlp);
21123 			}
21124 		}
21125 		lpfc_mbox_rsrc_cleanup(phba, mb, MBOX_THD_UNLOCKED);
21126 	}
21127 
21128 	/* Release the ndlp with the cleaned-up active mailbox command */
21129 	if (act_mbx_ndlp) {
21130 		clear_bit(NLP_IGNR_REG_CMPL, &act_mbx_ndlp->nlp_flag);
21131 		lpfc_nlp_put(act_mbx_ndlp);
21132 	}
21133 }
21134 
21135 /**
21136  * lpfc_drain_txq - Drain the txq
21137  * @phba: Pointer to HBA context object.
21138  *
21139  * This function attempt to submit IOCBs on the txq
21140  * to the adapter.  For SLI4 adapters, the txq contains
21141  * ELS IOCBs that have been deferred because the there
21142  * are no SGLs.  This congestion can occur with large
21143  * vport counts during node discovery.
21144  **/
21145 
21146 uint32_t
21147 lpfc_drain_txq(struct lpfc_hba *phba)
21148 {
21149 	LIST_HEAD(completions);
21150 	struct lpfc_sli_ring *pring;
21151 	struct lpfc_iocbq *piocbq = NULL;
21152 	unsigned long iflags = 0;
21153 	char *fail_msg = NULL;
21154 	uint32_t txq_cnt = 0;
21155 	struct lpfc_queue *wq;
21156 	int ret = 0;
21157 
21158 	if (phba->link_flag & LS_MDS_LOOPBACK) {
21159 		/* MDS WQE are posted only to first WQ*/
21160 		wq = phba->sli4_hba.hdwq[0].io_wq;
21161 		if (unlikely(!wq))
21162 			return 0;
21163 		pring = wq->pring;
21164 	} else {
21165 		wq = phba->sli4_hba.els_wq;
21166 		if (unlikely(!wq))
21167 			return 0;
21168 		pring = lpfc_phba_elsring(phba);
21169 	}
21170 
21171 	if (unlikely(!pring) || list_empty(&pring->txq))
21172 		return 0;
21173 
21174 	spin_lock_irqsave(&pring->ring_lock, iflags);
21175 	list_for_each_entry(piocbq, &pring->txq, list) {
21176 		txq_cnt++;
21177 	}
21178 
21179 	if (txq_cnt > pring->txq_max)
21180 		pring->txq_max = txq_cnt;
21181 
21182 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
21183 
21184 	while (!list_empty(&pring->txq)) {
21185 		spin_lock_irqsave(&pring->ring_lock, iflags);
21186 
21187 		piocbq = lpfc_sli_ringtx_get(phba, pring);
21188 		if (!piocbq) {
21189 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21190 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21191 				"2823 txq empty and txq_cnt is %d\n",
21192 				txq_cnt);
21193 			break;
21194 		}
21195 		txq_cnt--;
21196 
21197 		ret = __lpfc_sli_issue_iocb(phba, pring->ringno, piocbq, 0);
21198 
21199 		if (ret && ret != IOCB_BUSY) {
21200 			fail_msg = " - Cannot send IO ";
21201 			piocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21202 		}
21203 		if (fail_msg) {
21204 			piocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
21205 			/* Failed means we can't issue and need to cancel */
21206 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21207 					"2822 IOCB failed %s iotag 0x%x "
21208 					"xri 0x%x %d flg x%x\n",
21209 					fail_msg, piocbq->iotag,
21210 					piocbq->sli4_xritag, ret,
21211 					piocbq->cmd_flag);
21212 			list_add_tail(&piocbq->list, &completions);
21213 			fail_msg = NULL;
21214 		}
21215 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21216 		if (txq_cnt == 0 || ret == IOCB_BUSY)
21217 			break;
21218 	}
21219 	/* Cancel all the IOCBs that cannot be issued */
21220 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
21221 			      IOERR_SLI_ABORTED);
21222 
21223 	return txq_cnt;
21224 }
21225 
21226 /**
21227  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
21228  * @phba: Pointer to HBA context object.
21229  * @pwqeq: Pointer to command WQE.
21230  * @sglq: Pointer to the scatter gather queue object.
21231  *
21232  * This routine converts the bpl or bde that is in the WQE
21233  * to a sgl list for the sli4 hardware. The physical address
21234  * of the bpl/bde is converted back to a virtual address.
21235  * If the WQE contains a BPL then the list of BDE's is
21236  * converted to sli4_sge's. If the WQE contains a single
21237  * BDE then it is converted to a single sli_sge.
21238  * The WQE is still in cpu endianness so the contents of
21239  * the bpl can be used without byte swapping.
21240  *
21241  * Returns valid XRI = Success, NO_XRI = Failure.
21242  */
21243 static uint16_t
21244 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
21245 		 struct lpfc_sglq *sglq)
21246 {
21247 	uint16_t xritag = NO_XRI;
21248 	struct ulp_bde64 *bpl = NULL;
21249 	struct ulp_bde64 bde;
21250 	struct sli4_sge *sgl  = NULL;
21251 	struct lpfc_dmabuf *dmabuf;
21252 	union lpfc_wqe128 *wqe;
21253 	int numBdes = 0;
21254 	int i = 0;
21255 	uint32_t offset = 0; /* accumulated offset in the sg request list */
21256 	int inbound = 0; /* number of sg reply entries inbound from firmware */
21257 	uint32_t cmd;
21258 
21259 	if (!pwqeq || !sglq)
21260 		return xritag;
21261 
21262 	sgl  = (struct sli4_sge *)sglq->sgl;
21263 	wqe = &pwqeq->wqe;
21264 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
21265 
21266 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
21267 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
21268 		return sglq->sli4_xritag;
21269 	numBdes = pwqeq->num_bdes;
21270 	if (numBdes) {
21271 		/* The addrHigh and addrLow fields within the WQE
21272 		 * have not been byteswapped yet so there is no
21273 		 * need to swap them back.
21274 		 */
21275 		if (pwqeq->bpl_dmabuf)
21276 			dmabuf = pwqeq->bpl_dmabuf;
21277 		else
21278 			return xritag;
21279 
21280 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
21281 		if (!bpl)
21282 			return xritag;
21283 
21284 		for (i = 0; i < numBdes; i++) {
21285 			/* Should already be byte swapped. */
21286 			sgl->addr_hi = bpl->addrHigh;
21287 			sgl->addr_lo = bpl->addrLow;
21288 
21289 			sgl->word2 = le32_to_cpu(sgl->word2);
21290 			if ((i+1) == numBdes)
21291 				bf_set(lpfc_sli4_sge_last, sgl, 1);
21292 			else
21293 				bf_set(lpfc_sli4_sge_last, sgl, 0);
21294 			/* swap the size field back to the cpu so we
21295 			 * can assign it to the sgl.
21296 			 */
21297 			bde.tus.w = le32_to_cpu(bpl->tus.w);
21298 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
21299 			/* The offsets in the sgl need to be accumulated
21300 			 * separately for the request and reply lists.
21301 			 * The request is always first, the reply follows.
21302 			 */
21303 			switch (cmd) {
21304 			case CMD_GEN_REQUEST64_WQE:
21305 				/* add up the reply sg entries */
21306 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
21307 					inbound++;
21308 				/* first inbound? reset the offset */
21309 				if (inbound == 1)
21310 					offset = 0;
21311 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21312 				bf_set(lpfc_sli4_sge_type, sgl,
21313 					LPFC_SGE_TYPE_DATA);
21314 				offset += bde.tus.f.bdeSize;
21315 				break;
21316 			case CMD_FCP_TRSP64_WQE:
21317 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
21318 				bf_set(lpfc_sli4_sge_type, sgl,
21319 					LPFC_SGE_TYPE_DATA);
21320 				break;
21321 			case CMD_FCP_TSEND64_WQE:
21322 			case CMD_FCP_TRECEIVE64_WQE:
21323 				bf_set(lpfc_sli4_sge_type, sgl,
21324 					bpl->tus.f.bdeFlags);
21325 				if (i < 3)
21326 					offset = 0;
21327 				else
21328 					offset += bde.tus.f.bdeSize;
21329 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21330 				break;
21331 			}
21332 			sgl->word2 = cpu_to_le32(sgl->word2);
21333 			bpl++;
21334 			sgl++;
21335 		}
21336 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
21337 		/* The addrHigh and addrLow fields of the BDE have not
21338 		 * been byteswapped yet so they need to be swapped
21339 		 * before putting them in the sgl.
21340 		 */
21341 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
21342 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
21343 		sgl->word2 = le32_to_cpu(sgl->word2);
21344 		bf_set(lpfc_sli4_sge_last, sgl, 1);
21345 		sgl->word2 = cpu_to_le32(sgl->word2);
21346 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
21347 	}
21348 	return sglq->sli4_xritag;
21349 }
21350 
21351 /**
21352  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
21353  * @phba: Pointer to HBA context object.
21354  * @qp: Pointer to HDW queue.
21355  * @pwqe: Pointer to command WQE.
21356  **/
21357 int
21358 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21359 		    struct lpfc_iocbq *pwqe)
21360 {
21361 	union lpfc_wqe128 *wqe = &pwqe->wqe;
21362 	struct lpfc_async_xchg_ctx *ctxp;
21363 	struct lpfc_queue *wq;
21364 	struct lpfc_sglq *sglq;
21365 	struct lpfc_sli_ring *pring;
21366 	unsigned long iflags;
21367 	int ret = 0;
21368 
21369 	/* NVME_LS and NVME_LS ABTS requests. */
21370 	if (pwqe->cmd_flag & LPFC_IO_NVME_LS) {
21371 		pring =  phba->sli4_hba.nvmels_wq->pring;
21372 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21373 					  qp, wq_access);
21374 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
21375 		if (!sglq) {
21376 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21377 			return WQE_BUSY;
21378 		}
21379 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
21380 		pwqe->sli4_xritag = sglq->sli4_xritag;
21381 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
21382 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21383 			return WQE_ERROR;
21384 		}
21385 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21386 		       pwqe->sli4_xritag);
21387 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
21388 		if (ret) {
21389 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21390 			return ret;
21391 		}
21392 
21393 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21394 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21395 
21396 		lpfc_sli4_poll_eq(qp->hba_eq);
21397 		return 0;
21398 	}
21399 
21400 	/* NVME_FCREQ and NVME_ABTS requests */
21401 	if (pwqe->cmd_flag & (LPFC_IO_NVME | LPFC_IO_FCP | LPFC_IO_CMF)) {
21402 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21403 		wq = qp->io_wq;
21404 		pring = wq->pring;
21405 
21406 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21407 
21408 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21409 					  qp, wq_access);
21410 		ret = lpfc_sli4_wq_put(wq, wqe);
21411 		if (ret) {
21412 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21413 			return ret;
21414 		}
21415 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21416 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21417 
21418 		lpfc_sli4_poll_eq(qp->hba_eq);
21419 		return 0;
21420 	}
21421 
21422 	/* NVMET requests */
21423 	if (pwqe->cmd_flag & LPFC_IO_NVMET) {
21424 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21425 		wq = qp->io_wq;
21426 		pring = wq->pring;
21427 
21428 		ctxp = pwqe->context_un.axchg;
21429 		sglq = ctxp->ctxbuf->sglq;
21430 		if (pwqe->sli4_xritag ==  NO_XRI) {
21431 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
21432 			pwqe->sli4_xritag = sglq->sli4_xritag;
21433 		}
21434 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21435 		       pwqe->sli4_xritag);
21436 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21437 
21438 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21439 					  qp, wq_access);
21440 		ret = lpfc_sli4_wq_put(wq, wqe);
21441 		if (ret) {
21442 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21443 			return ret;
21444 		}
21445 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21446 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21447 
21448 		lpfc_sli4_poll_eq(qp->hba_eq);
21449 		return 0;
21450 	}
21451 	return WQE_ERROR;
21452 }
21453 
21454 /**
21455  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
21456  * @phba: Pointer to HBA context object.
21457  * @cmdiocb: Pointer to driver command iocb object.
21458  * @cmpl: completion function.
21459  *
21460  * Fill the appropriate fields for the abort WQE and call
21461  * internal routine lpfc_sli4_issue_wqe to send the WQE
21462  * This function is called with hbalock held and no ring_lock held.
21463  *
21464  * RETURNS 0 - SUCCESS
21465  **/
21466 
21467 int
21468 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
21469 			    void *cmpl)
21470 {
21471 	struct lpfc_vport *vport = cmdiocb->vport;
21472 	struct lpfc_iocbq *abtsiocb = NULL;
21473 	union lpfc_wqe128 *abtswqe;
21474 	struct lpfc_io_buf *lpfc_cmd;
21475 	int retval = IOCB_ERROR;
21476 	u16 xritag = cmdiocb->sli4_xritag;
21477 
21478 	/*
21479 	 * The scsi command can not be in txq and it is in flight because the
21480 	 * pCmd is still pointing at the SCSI command we have to abort. There
21481 	 * is no need to search the txcmplq. Just send an abort to the FW.
21482 	 */
21483 
21484 	abtsiocb = __lpfc_sli_get_iocbq(phba);
21485 	if (!abtsiocb)
21486 		return WQE_NORESOURCE;
21487 
21488 	/* Indicate the IO is being aborted by the driver. */
21489 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
21490 
21491 	abtswqe = &abtsiocb->wqe;
21492 	memset(abtswqe, 0, sizeof(*abtswqe));
21493 
21494 	if (!lpfc_is_link_up(phba) || (phba->link_flag & LS_EXTERNAL_LOOPBACK))
21495 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
21496 	bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
21497 	abtswqe->abort_cmd.rsrvd5 = 0;
21498 	abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
21499 	bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
21500 	bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
21501 	bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
21502 	bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
21503 	bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
21504 	bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
21505 
21506 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
21507 	abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
21508 	abtsiocb->cmd_flag |= LPFC_USE_FCPWQIDX;
21509 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
21510 		abtsiocb->cmd_flag |= LPFC_IO_FCP;
21511 	if (cmdiocb->cmd_flag & LPFC_IO_NVME)
21512 		abtsiocb->cmd_flag |= LPFC_IO_NVME;
21513 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
21514 		abtsiocb->cmd_flag |= LPFC_IO_FOF;
21515 	abtsiocb->vport = vport;
21516 	abtsiocb->cmd_cmpl = cmpl;
21517 
21518 	lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
21519 	retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
21520 
21521 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21522 			 "0359 Abort xri x%x, original iotag x%x, "
21523 			 "abort cmd iotag x%x retval x%x\n",
21524 			 xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
21525 
21526 	if (retval) {
21527 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21528 		__lpfc_sli_release_iocbq(phba, abtsiocb);
21529 	}
21530 
21531 	return retval;
21532 }
21533 
21534 #ifdef LPFC_MXP_STAT
21535 /**
21536  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
21537  * @phba: pointer to lpfc hba data structure.
21538  * @hwqid: belong to which HWQ.
21539  *
21540  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
21541  * 15 seconds after a test case is running.
21542  *
21543  * The user should call lpfc_debugfs_multixripools_write before running a test
21544  * case to clear stat_snapshot_taken. Then the user starts a test case. During
21545  * test case is running, stat_snapshot_taken is incremented by 1 every time when
21546  * this routine is called from heartbeat timer. When stat_snapshot_taken is
21547  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
21548  **/
21549 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
21550 {
21551 	struct lpfc_sli4_hdw_queue *qp;
21552 	struct lpfc_multixri_pool *multixri_pool;
21553 	struct lpfc_pvt_pool *pvt_pool;
21554 	struct lpfc_pbl_pool *pbl_pool;
21555 	u32 txcmplq_cnt;
21556 
21557 	qp = &phba->sli4_hba.hdwq[hwqid];
21558 	multixri_pool = qp->p_multixri_pool;
21559 	if (!multixri_pool)
21560 		return;
21561 
21562 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
21563 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21564 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21565 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21566 
21567 		multixri_pool->stat_pbl_count = pbl_pool->count;
21568 		multixri_pool->stat_pvt_count = pvt_pool->count;
21569 		multixri_pool->stat_busy_count = txcmplq_cnt;
21570 	}
21571 
21572 	multixri_pool->stat_snapshot_taken++;
21573 }
21574 #endif
21575 
21576 /**
21577  * lpfc_adjust_pvt_pool_count - Adjust private pool count
21578  * @phba: pointer to lpfc hba data structure.
21579  * @hwqid: belong to which HWQ.
21580  *
21581  * This routine moves some XRIs from private to public pool when private pool
21582  * is not busy.
21583  **/
21584 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
21585 {
21586 	struct lpfc_multixri_pool *multixri_pool;
21587 	u32 io_req_count;
21588 	u32 prev_io_req_count;
21589 
21590 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21591 	if (!multixri_pool)
21592 		return;
21593 	io_req_count = multixri_pool->io_req_count;
21594 	prev_io_req_count = multixri_pool->prev_io_req_count;
21595 
21596 	if (prev_io_req_count != io_req_count) {
21597 		/* Private pool is busy */
21598 		multixri_pool->prev_io_req_count = io_req_count;
21599 	} else {
21600 		/* Private pool is not busy.
21601 		 * Move XRIs from private to public pool.
21602 		 */
21603 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
21604 	}
21605 }
21606 
21607 /**
21608  * lpfc_adjust_high_watermark - Adjust high watermark
21609  * @phba: pointer to lpfc hba data structure.
21610  * @hwqid: belong to which HWQ.
21611  *
21612  * This routine sets high watermark as number of outstanding XRIs,
21613  * but make sure the new value is between xri_limit/2 and xri_limit.
21614  **/
21615 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
21616 {
21617 	u32 new_watermark;
21618 	u32 watermark_max;
21619 	u32 watermark_min;
21620 	u32 xri_limit;
21621 	u32 txcmplq_cnt;
21622 	u32 abts_io_bufs;
21623 	struct lpfc_multixri_pool *multixri_pool;
21624 	struct lpfc_sli4_hdw_queue *qp;
21625 
21626 	qp = &phba->sli4_hba.hdwq[hwqid];
21627 	multixri_pool = qp->p_multixri_pool;
21628 	if (!multixri_pool)
21629 		return;
21630 	xri_limit = multixri_pool->xri_limit;
21631 
21632 	watermark_max = xri_limit;
21633 	watermark_min = xri_limit / 2;
21634 
21635 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21636 	abts_io_bufs = qp->abts_scsi_io_bufs;
21637 	abts_io_bufs += qp->abts_nvme_io_bufs;
21638 
21639 	new_watermark = txcmplq_cnt + abts_io_bufs;
21640 	new_watermark = min(watermark_max, new_watermark);
21641 	new_watermark = max(watermark_min, new_watermark);
21642 	multixri_pool->pvt_pool.high_watermark = new_watermark;
21643 
21644 #ifdef LPFC_MXP_STAT
21645 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
21646 					  new_watermark);
21647 #endif
21648 }
21649 
21650 /**
21651  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
21652  * @phba: pointer to lpfc hba data structure.
21653  * @hwqid: belong to which HWQ.
21654  *
21655  * This routine is called from hearbeat timer when pvt_pool is idle.
21656  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
21657  * The first step moves (all - low_watermark) amount of XRIs.
21658  * The second step moves the rest of XRIs.
21659  **/
21660 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
21661 {
21662 	struct lpfc_pbl_pool *pbl_pool;
21663 	struct lpfc_pvt_pool *pvt_pool;
21664 	struct lpfc_sli4_hdw_queue *qp;
21665 	struct lpfc_io_buf *lpfc_ncmd;
21666 	struct lpfc_io_buf *lpfc_ncmd_next;
21667 	unsigned long iflag;
21668 	struct list_head tmp_list;
21669 	u32 tmp_count;
21670 
21671 	qp = &phba->sli4_hba.hdwq[hwqid];
21672 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
21673 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
21674 	tmp_count = 0;
21675 
21676 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
21677 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
21678 
21679 	if (pvt_pool->count > pvt_pool->low_watermark) {
21680 		/* Step 1: move (all - low_watermark) from pvt_pool
21681 		 * to pbl_pool
21682 		 */
21683 
21684 		/* Move low watermark of bufs from pvt_pool to tmp_list */
21685 		INIT_LIST_HEAD(&tmp_list);
21686 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21687 					 &pvt_pool->list, list) {
21688 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
21689 			tmp_count++;
21690 			if (tmp_count >= pvt_pool->low_watermark)
21691 				break;
21692 		}
21693 
21694 		/* Move all bufs from pvt_pool to pbl_pool */
21695 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21696 
21697 		/* Move all bufs from tmp_list to pvt_pool */
21698 		list_splice(&tmp_list, &pvt_pool->list);
21699 
21700 		pbl_pool->count += (pvt_pool->count - tmp_count);
21701 		pvt_pool->count = tmp_count;
21702 	} else {
21703 		/* Step 2: move the rest from pvt_pool to pbl_pool */
21704 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21705 		pbl_pool->count += pvt_pool->count;
21706 		pvt_pool->count = 0;
21707 	}
21708 
21709 	spin_unlock(&pvt_pool->lock);
21710 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21711 }
21712 
21713 /**
21714  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21715  * @phba: pointer to lpfc hba data structure
21716  * @qp: pointer to HDW queue
21717  * @pbl_pool: specified public free XRI pool
21718  * @pvt_pool: specified private free XRI pool
21719  * @count: number of XRIs to move
21720  *
21721  * This routine tries to move some free common bufs from the specified pbl_pool
21722  * to the specified pvt_pool. It might move less than count XRIs if there's not
21723  * enough in public pool.
21724  *
21725  * Return:
21726  *   true - if XRIs are successfully moved from the specified pbl_pool to the
21727  *          specified pvt_pool
21728  *   false - if the specified pbl_pool is empty or locked by someone else
21729  **/
21730 static bool
21731 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21732 			  struct lpfc_pbl_pool *pbl_pool,
21733 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
21734 {
21735 	struct lpfc_io_buf *lpfc_ncmd;
21736 	struct lpfc_io_buf *lpfc_ncmd_next;
21737 	unsigned long iflag;
21738 	int ret;
21739 
21740 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
21741 	if (ret) {
21742 		if (pbl_pool->count) {
21743 			/* Move a batch of XRIs from public to private pool */
21744 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
21745 			list_for_each_entry_safe(lpfc_ncmd,
21746 						 lpfc_ncmd_next,
21747 						 &pbl_pool->list,
21748 						 list) {
21749 				list_move_tail(&lpfc_ncmd->list,
21750 					       &pvt_pool->list);
21751 				pvt_pool->count++;
21752 				pbl_pool->count--;
21753 				count--;
21754 				if (count == 0)
21755 					break;
21756 			}
21757 
21758 			spin_unlock(&pvt_pool->lock);
21759 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21760 			return true;
21761 		}
21762 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21763 	}
21764 
21765 	return false;
21766 }
21767 
21768 /**
21769  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21770  * @phba: pointer to lpfc hba data structure.
21771  * @hwqid: belong to which HWQ.
21772  * @count: number of XRIs to move
21773  *
21774  * This routine tries to find some free common bufs in one of public pools with
21775  * Round Robin method. The search always starts from local hwqid, then the next
21776  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
21777  * a batch of free common bufs are moved to private pool on hwqid.
21778  * It might move less than count XRIs if there's not enough in public pool.
21779  **/
21780 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
21781 {
21782 	struct lpfc_multixri_pool *multixri_pool;
21783 	struct lpfc_multixri_pool *next_multixri_pool;
21784 	struct lpfc_pvt_pool *pvt_pool;
21785 	struct lpfc_pbl_pool *pbl_pool;
21786 	struct lpfc_sli4_hdw_queue *qp;
21787 	u32 next_hwqid;
21788 	u32 hwq_count;
21789 	int ret;
21790 
21791 	qp = &phba->sli4_hba.hdwq[hwqid];
21792 	multixri_pool = qp->p_multixri_pool;
21793 	pvt_pool = &multixri_pool->pvt_pool;
21794 	pbl_pool = &multixri_pool->pbl_pool;
21795 
21796 	/* Check if local pbl_pool is available */
21797 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
21798 	if (ret) {
21799 #ifdef LPFC_MXP_STAT
21800 		multixri_pool->local_pbl_hit_count++;
21801 #endif
21802 		return;
21803 	}
21804 
21805 	hwq_count = phba->cfg_hdw_queue;
21806 
21807 	/* Get the next hwqid which was found last time */
21808 	next_hwqid = multixri_pool->rrb_next_hwqid;
21809 
21810 	do {
21811 		/* Go to next hwq */
21812 		next_hwqid = (next_hwqid + 1) % hwq_count;
21813 
21814 		next_multixri_pool =
21815 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
21816 		pbl_pool = &next_multixri_pool->pbl_pool;
21817 
21818 		/* Check if the public free xri pool is available */
21819 		ret = _lpfc_move_xri_pbl_to_pvt(
21820 			phba, qp, pbl_pool, pvt_pool, count);
21821 
21822 		/* Exit while-loop if success or all hwqid are checked */
21823 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
21824 
21825 	/* Starting point for the next time */
21826 	multixri_pool->rrb_next_hwqid = next_hwqid;
21827 
21828 	if (!ret) {
21829 		/* stats: all public pools are empty*/
21830 		multixri_pool->pbl_empty_count++;
21831 	}
21832 
21833 #ifdef LPFC_MXP_STAT
21834 	if (ret) {
21835 		if (next_hwqid == hwqid)
21836 			multixri_pool->local_pbl_hit_count++;
21837 		else
21838 			multixri_pool->other_pbl_hit_count++;
21839 	}
21840 #endif
21841 }
21842 
21843 /**
21844  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
21845  * @phba: pointer to lpfc hba data structure.
21846  * @hwqid: belong to which HWQ.
21847  *
21848  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
21849  * low watermark.
21850  **/
21851 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
21852 {
21853 	struct lpfc_multixri_pool *multixri_pool;
21854 	struct lpfc_pvt_pool *pvt_pool;
21855 
21856 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21857 	pvt_pool = &multixri_pool->pvt_pool;
21858 
21859 	if (pvt_pool->count < pvt_pool->low_watermark)
21860 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21861 }
21862 
21863 /**
21864  * lpfc_release_io_buf - Return one IO buf back to free pool
21865  * @phba: pointer to lpfc hba data structure.
21866  * @lpfc_ncmd: IO buf to be returned.
21867  * @qp: belong to which HWQ.
21868  *
21869  * This routine returns one IO buf back to free pool. If this is an urgent IO,
21870  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
21871  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
21872  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
21873  * lpfc_io_buf_list_put.
21874  **/
21875 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
21876 			 struct lpfc_sli4_hdw_queue *qp)
21877 {
21878 	unsigned long iflag;
21879 	struct lpfc_pbl_pool *pbl_pool;
21880 	struct lpfc_pvt_pool *pvt_pool;
21881 	struct lpfc_epd_pool *epd_pool;
21882 	u32 txcmplq_cnt;
21883 	u32 xri_owned;
21884 	u32 xri_limit;
21885 	u32 abts_io_bufs;
21886 
21887 	/* MUST zero fields if buffer is reused by another protocol */
21888 	lpfc_ncmd->nvmeCmd = NULL;
21889 	lpfc_ncmd->cur_iocbq.cmd_cmpl = NULL;
21890 
21891 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
21892 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
21893 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
21894 
21895 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
21896 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
21897 
21898 	if (phba->cfg_xri_rebalancing) {
21899 		if (lpfc_ncmd->expedite) {
21900 			/* Return to expedite pool */
21901 			epd_pool = &phba->epd_pool;
21902 			spin_lock_irqsave(&epd_pool->lock, iflag);
21903 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21904 			epd_pool->count++;
21905 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
21906 			return;
21907 		}
21908 
21909 		/* Avoid invalid access if an IO sneaks in and is being rejected
21910 		 * just _after_ xri pools are destroyed in lpfc_offline.
21911 		 * Nothing much can be done at this point.
21912 		 */
21913 		if (!qp->p_multixri_pool)
21914 			return;
21915 
21916 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21917 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21918 
21919 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21920 		abts_io_bufs = qp->abts_scsi_io_bufs;
21921 		abts_io_bufs += qp->abts_nvme_io_bufs;
21922 
21923 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21924 		xri_limit = qp->p_multixri_pool->xri_limit;
21925 
21926 #ifdef LPFC_MXP_STAT
21927 		if (xri_owned <= xri_limit)
21928 			qp->p_multixri_pool->below_limit_count++;
21929 		else
21930 			qp->p_multixri_pool->above_limit_count++;
21931 #endif
21932 
21933 		/* XRI goes to either public or private free xri pool
21934 		 *     based on watermark and xri_limit
21935 		 */
21936 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
21937 		    (xri_owned < xri_limit &&
21938 		     pvt_pool->count < pvt_pool->high_watermark)) {
21939 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
21940 						  qp, free_pvt_pool);
21941 			list_add_tail(&lpfc_ncmd->list,
21942 				      &pvt_pool->list);
21943 			pvt_pool->count++;
21944 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21945 		} else {
21946 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
21947 						  qp, free_pub_pool);
21948 			list_add_tail(&lpfc_ncmd->list,
21949 				      &pbl_pool->list);
21950 			pbl_pool->count++;
21951 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21952 		}
21953 	} else {
21954 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
21955 					  qp, free_xri);
21956 		list_add_tail(&lpfc_ncmd->list,
21957 			      &qp->lpfc_io_buf_list_put);
21958 		qp->put_io_bufs++;
21959 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
21960 				       iflag);
21961 	}
21962 }
21963 
21964 /**
21965  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
21966  * @phba: pointer to lpfc hba data structure.
21967  * @qp: pointer to HDW queue
21968  * @pvt_pool: pointer to private pool data structure.
21969  * @ndlp: pointer to lpfc nodelist data structure.
21970  *
21971  * This routine tries to get one free IO buf from private pool.
21972  *
21973  * Return:
21974  *   pointer to one free IO buf - if private pool is not empty
21975  *   NULL - if private pool is empty
21976  **/
21977 static struct lpfc_io_buf *
21978 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
21979 				  struct lpfc_sli4_hdw_queue *qp,
21980 				  struct lpfc_pvt_pool *pvt_pool,
21981 				  struct lpfc_nodelist *ndlp)
21982 {
21983 	struct lpfc_io_buf *lpfc_ncmd;
21984 	struct lpfc_io_buf *lpfc_ncmd_next;
21985 	unsigned long iflag;
21986 
21987 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
21988 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21989 				 &pvt_pool->list, list) {
21990 		if (lpfc_test_rrq_active(
21991 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
21992 			continue;
21993 		list_del(&lpfc_ncmd->list);
21994 		pvt_pool->count--;
21995 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21996 		return lpfc_ncmd;
21997 	}
21998 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21999 
22000 	return NULL;
22001 }
22002 
22003 /**
22004  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
22005  * @phba: pointer to lpfc hba data structure.
22006  *
22007  * This routine tries to get one free IO buf from expedite pool.
22008  *
22009  * Return:
22010  *   pointer to one free IO buf - if expedite pool is not empty
22011  *   NULL - if expedite pool is empty
22012  **/
22013 static struct lpfc_io_buf *
22014 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
22015 {
22016 	struct lpfc_io_buf *lpfc_ncmd = NULL, *iter;
22017 	struct lpfc_io_buf *lpfc_ncmd_next;
22018 	unsigned long iflag;
22019 	struct lpfc_epd_pool *epd_pool;
22020 
22021 	epd_pool = &phba->epd_pool;
22022 
22023 	spin_lock_irqsave(&epd_pool->lock, iflag);
22024 	if (epd_pool->count > 0) {
22025 		list_for_each_entry_safe(iter, lpfc_ncmd_next,
22026 					 &epd_pool->list, list) {
22027 			list_del(&iter->list);
22028 			epd_pool->count--;
22029 			lpfc_ncmd = iter;
22030 			break;
22031 		}
22032 	}
22033 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
22034 
22035 	return lpfc_ncmd;
22036 }
22037 
22038 /**
22039  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
22040  * @phba: pointer to lpfc hba data structure.
22041  * @ndlp: pointer to lpfc nodelist data structure.
22042  * @hwqid: belong to which HWQ
22043  * @expedite: 1 means this request is urgent.
22044  *
22045  * This routine will do the following actions and then return a pointer to
22046  * one free IO buf.
22047  *
22048  * 1. If private free xri count is empty, move some XRIs from public to
22049  *    private pool.
22050  * 2. Get one XRI from private free xri pool.
22051  * 3. If we fail to get one from pvt_pool and this is an expedite request,
22052  *    get one free xri from expedite pool.
22053  *
22054  * Note: ndlp is only used on SCSI side for RRQ testing.
22055  *       The caller should pass NULL for ndlp on NVME side.
22056  *
22057  * Return:
22058  *   pointer to one free IO buf - if private pool is not empty
22059  *   NULL - if private pool is empty
22060  **/
22061 static struct lpfc_io_buf *
22062 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
22063 				    struct lpfc_nodelist *ndlp,
22064 				    int hwqid, int expedite)
22065 {
22066 	struct lpfc_sli4_hdw_queue *qp;
22067 	struct lpfc_multixri_pool *multixri_pool;
22068 	struct lpfc_pvt_pool *pvt_pool;
22069 	struct lpfc_io_buf *lpfc_ncmd;
22070 
22071 	qp = &phba->sli4_hba.hdwq[hwqid];
22072 	lpfc_ncmd = NULL;
22073 	if (!qp) {
22074 		lpfc_printf_log(phba, KERN_INFO,
22075 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22076 				"5556 NULL qp for hwqid  x%x\n", hwqid);
22077 		return lpfc_ncmd;
22078 	}
22079 	multixri_pool = qp->p_multixri_pool;
22080 	if (!multixri_pool) {
22081 		lpfc_printf_log(phba, KERN_INFO,
22082 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22083 				"5557 NULL multixri for hwqid  x%x\n", hwqid);
22084 		return lpfc_ncmd;
22085 	}
22086 	pvt_pool = &multixri_pool->pvt_pool;
22087 	if (!pvt_pool) {
22088 		lpfc_printf_log(phba, KERN_INFO,
22089 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22090 				"5558 NULL pvt_pool for hwqid  x%x\n", hwqid);
22091 		return lpfc_ncmd;
22092 	}
22093 	multixri_pool->io_req_count++;
22094 
22095 	/* If pvt_pool is empty, move some XRIs from public to private pool */
22096 	if (pvt_pool->count == 0)
22097 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
22098 
22099 	/* Get one XRI from private free xri pool */
22100 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
22101 
22102 	if (lpfc_ncmd) {
22103 		lpfc_ncmd->hdwq = qp;
22104 		lpfc_ncmd->hdwq_no = hwqid;
22105 	} else if (expedite) {
22106 		/* If we fail to get one from pvt_pool and this is an expedite
22107 		 * request, get one free xri from expedite pool.
22108 		 */
22109 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
22110 	}
22111 
22112 	return lpfc_ncmd;
22113 }
22114 
22115 static inline struct lpfc_io_buf *
22116 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
22117 {
22118 	struct lpfc_sli4_hdw_queue *qp;
22119 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
22120 
22121 	qp = &phba->sli4_hba.hdwq[idx];
22122 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
22123 				 &qp->lpfc_io_buf_list_get, list) {
22124 		if (lpfc_test_rrq_active(phba, ndlp,
22125 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
22126 			continue;
22127 
22128 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
22129 			continue;
22130 
22131 		list_del_init(&lpfc_cmd->list);
22132 		qp->get_io_bufs--;
22133 		lpfc_cmd->hdwq = qp;
22134 		lpfc_cmd->hdwq_no = idx;
22135 		return lpfc_cmd;
22136 	}
22137 	return NULL;
22138 }
22139 
22140 /**
22141  * lpfc_get_io_buf - Get one IO buffer from free pool
22142  * @phba: The HBA for which this call is being executed.
22143  * @ndlp: pointer to lpfc nodelist data structure.
22144  * @hwqid: belong to which HWQ
22145  * @expedite: 1 means this request is urgent.
22146  *
22147  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
22148  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
22149  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
22150  *
22151  * Note: ndlp is only used on SCSI side for RRQ testing.
22152  *       The caller should pass NULL for ndlp on NVME side.
22153  *
22154  * Return codes:
22155  *   NULL - Error
22156  *   Pointer to lpfc_io_buf - Success
22157  **/
22158 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
22159 				    struct lpfc_nodelist *ndlp,
22160 				    u32 hwqid, int expedite)
22161 {
22162 	struct lpfc_sli4_hdw_queue *qp;
22163 	unsigned long iflag;
22164 	struct lpfc_io_buf *lpfc_cmd;
22165 
22166 	qp = &phba->sli4_hba.hdwq[hwqid];
22167 	lpfc_cmd = NULL;
22168 	if (!qp) {
22169 		lpfc_printf_log(phba, KERN_WARNING,
22170 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22171 				"5555 NULL qp for hwqid  x%x\n", hwqid);
22172 		return lpfc_cmd;
22173 	}
22174 
22175 	if (phba->cfg_xri_rebalancing)
22176 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
22177 			phba, ndlp, hwqid, expedite);
22178 	else {
22179 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
22180 					  qp, alloc_xri_get);
22181 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
22182 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22183 		if (!lpfc_cmd) {
22184 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
22185 					  qp, alloc_xri_put);
22186 			list_splice(&qp->lpfc_io_buf_list_put,
22187 				    &qp->lpfc_io_buf_list_get);
22188 			qp->get_io_bufs += qp->put_io_bufs;
22189 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
22190 			qp->put_io_bufs = 0;
22191 			spin_unlock(&qp->io_buf_list_put_lock);
22192 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
22193 			    expedite)
22194 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22195 		}
22196 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
22197 	}
22198 
22199 	return lpfc_cmd;
22200 }
22201 
22202 /**
22203  * lpfc_read_object - Retrieve object data from HBA
22204  * @phba: The HBA for which this call is being executed.
22205  * @rdobject: Pathname of object data we want to read.
22206  * @datap: Pointer to where data will be copied to.
22207  * @datasz: size of data area
22208  *
22209  * This routine is limited to object sizes of LPFC_BPL_SIZE (1024) or less.
22210  * The data will be truncated if datasz is not large enough.
22211  * Version 1 is not supported with Embedded mbox cmd, so we must use version 0.
22212  * Returns the actual bytes read from the object.
22213  *
22214  * This routine is hard coded to use a poll completion.  Unlike other
22215  * sli4_config mailboxes, it uses lpfc_mbuf memory which is not
22216  * cleaned up in lpfc_sli4_cmd_mbox_free.  If this routine is modified
22217  * to use interrupt-based completions, code is needed to fully cleanup
22218  * the memory.
22219  */
22220 int
22221 lpfc_read_object(struct lpfc_hba *phba, char *rdobject, uint32_t *datap,
22222 		 uint32_t datasz)
22223 {
22224 	struct lpfc_mbx_read_object *read_object;
22225 	LPFC_MBOXQ_t *mbox;
22226 	int rc, length, eof, j, byte_cnt = 0;
22227 	uint32_t shdr_status, shdr_add_status;
22228 	union lpfc_sli4_cfg_shdr *shdr;
22229 	struct lpfc_dmabuf *pcmd;
22230 	u32 rd_object_name[LPFC_MBX_OBJECT_NAME_LEN_DW] = {0};
22231 
22232 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
22233 	if (!mbox)
22234 		return -ENOMEM;
22235 	length = (sizeof(struct lpfc_mbx_read_object) -
22236 		  sizeof(struct lpfc_sli4_cfg_mhdr));
22237 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
22238 			 LPFC_MBOX_OPCODE_READ_OBJECT,
22239 			 length, LPFC_SLI4_MBX_EMBED);
22240 	read_object = &mbox->u.mqe.un.read_object;
22241 	shdr = (union lpfc_sli4_cfg_shdr *)&read_object->header.cfg_shdr;
22242 
22243 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_0);
22244 	bf_set(lpfc_mbx_rd_object_rlen, &read_object->u.request, datasz);
22245 	read_object->u.request.rd_object_offset = 0;
22246 	read_object->u.request.rd_object_cnt = 1;
22247 
22248 	memset((void *)read_object->u.request.rd_object_name, 0,
22249 	       LPFC_OBJ_NAME_SZ);
22250 	scnprintf((char *)rd_object_name, sizeof(rd_object_name), rdobject);
22251 	for (j = 0; j < strlen(rdobject); j++)
22252 		read_object->u.request.rd_object_name[j] =
22253 			cpu_to_le32(rd_object_name[j]);
22254 
22255 	pcmd = kmalloc(sizeof(*pcmd), GFP_KERNEL);
22256 	if (pcmd)
22257 		pcmd->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &pcmd->phys);
22258 	if (!pcmd || !pcmd->virt) {
22259 		kfree(pcmd);
22260 		mempool_free(mbox, phba->mbox_mem_pool);
22261 		return -ENOMEM;
22262 	}
22263 	memset((void *)pcmd->virt, 0, LPFC_BPL_SIZE);
22264 	read_object->u.request.rd_object_hbuf[0].pa_lo =
22265 		putPaddrLow(pcmd->phys);
22266 	read_object->u.request.rd_object_hbuf[0].pa_hi =
22267 		putPaddrHigh(pcmd->phys);
22268 	read_object->u.request.rd_object_hbuf[0].length = LPFC_BPL_SIZE;
22269 
22270 	mbox->vport = phba->pport;
22271 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
22272 	mbox->ctx_ndlp = NULL;
22273 
22274 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
22275 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
22276 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
22277 
22278 	if (shdr_status == STATUS_FAILED &&
22279 	    shdr_add_status == ADD_STATUS_INVALID_OBJECT_NAME) {
22280 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22281 				"4674 No port cfg file in FW.\n");
22282 		byte_cnt = -ENOENT;
22283 	} else if (shdr_status || shdr_add_status || rc) {
22284 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22285 				"2625 READ_OBJECT mailbox failed with "
22286 				"status x%x add_status x%x, mbx status x%x\n",
22287 				shdr_status, shdr_add_status, rc);
22288 		byte_cnt = -ENXIO;
22289 	} else {
22290 		/* Success */
22291 		length = read_object->u.response.rd_object_actual_rlen;
22292 		eof = bf_get(lpfc_mbx_rd_object_eof, &read_object->u.response);
22293 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_CGN_MGMT,
22294 				"2626 READ_OBJECT Success len %d:%d, EOF %d\n",
22295 				length, datasz, eof);
22296 
22297 		/* Detect the port config file exists but is empty */
22298 		if (!length && eof) {
22299 			byte_cnt = 0;
22300 			goto exit;
22301 		}
22302 
22303 		byte_cnt = length;
22304 		lpfc_sli_pcimem_bcopy(pcmd->virt, datap, byte_cnt);
22305 	}
22306 
22307  exit:
22308 	/* This is an embedded SLI4 mailbox with an external buffer allocated.
22309 	 * Free the pcmd and then cleanup with the correct routine.
22310 	 */
22311 	lpfc_mbuf_free(phba, pcmd->virt, pcmd->phys);
22312 	kfree(pcmd);
22313 	lpfc_sli4_mbox_cmd_free(phba, mbox);
22314 	return byte_cnt;
22315 }
22316 
22317 /**
22318  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
22319  * @phba: The HBA for which this call is being executed.
22320  * @lpfc_buf: IO buf structure to append the SGL chunk
22321  *
22322  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
22323  * and will allocate an SGL chunk if the pool is empty.
22324  *
22325  * Return codes:
22326  *   NULL - Error
22327  *   Pointer to sli4_hybrid_sgl - Success
22328  **/
22329 struct sli4_hybrid_sgl *
22330 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22331 {
22332 	struct sli4_hybrid_sgl *list_entry = NULL;
22333 	struct sli4_hybrid_sgl *tmp = NULL;
22334 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
22335 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22336 	struct list_head *buf_list = &hdwq->sgl_list;
22337 	unsigned long iflags;
22338 
22339 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22340 
22341 	if (likely(!list_empty(buf_list))) {
22342 		/* break off 1 chunk from the sgl_list */
22343 		list_for_each_entry_safe(list_entry, tmp,
22344 					 buf_list, list_node) {
22345 			list_move_tail(&list_entry->list_node,
22346 				       &lpfc_buf->dma_sgl_xtra_list);
22347 			break;
22348 		}
22349 	} else {
22350 		/* allocate more */
22351 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22352 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22353 				   cpu_to_node(hdwq->io_wq->chann));
22354 		if (!tmp) {
22355 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22356 					"8353 error kmalloc memory for HDWQ "
22357 					"%d %s\n",
22358 					lpfc_buf->hdwq_no, __func__);
22359 			return NULL;
22360 		}
22361 
22362 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
22363 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
22364 		if (!tmp->dma_sgl) {
22365 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22366 					"8354 error pool_alloc memory for HDWQ "
22367 					"%d %s\n",
22368 					lpfc_buf->hdwq_no, __func__);
22369 			kfree(tmp);
22370 			return NULL;
22371 		}
22372 
22373 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22374 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
22375 	}
22376 
22377 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
22378 					struct sli4_hybrid_sgl,
22379 					list_node);
22380 
22381 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22382 
22383 	return allocated_sgl;
22384 }
22385 
22386 /**
22387  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
22388  * @phba: The HBA for which this call is being executed.
22389  * @lpfc_buf: IO buf structure with the SGL chunk
22390  *
22391  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
22392  *
22393  * Return codes:
22394  *   0 - Success
22395  *   -EINVAL - Error
22396  **/
22397 int
22398 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22399 {
22400 	int rc = 0;
22401 	struct sli4_hybrid_sgl *list_entry = NULL;
22402 	struct sli4_hybrid_sgl *tmp = NULL;
22403 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22404 	struct list_head *buf_list = &hdwq->sgl_list;
22405 	unsigned long iflags;
22406 
22407 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22408 
22409 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
22410 		list_for_each_entry_safe(list_entry, tmp,
22411 					 &lpfc_buf->dma_sgl_xtra_list,
22412 					 list_node) {
22413 			list_move_tail(&list_entry->list_node,
22414 				       buf_list);
22415 		}
22416 	} else {
22417 		rc = -EINVAL;
22418 	}
22419 
22420 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22421 	return rc;
22422 }
22423 
22424 /**
22425  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
22426  * @phba: phba object
22427  * @hdwq: hdwq to cleanup sgl buff resources on
22428  *
22429  * This routine frees all SGL chunks of hdwq SGL chunk pool.
22430  *
22431  * Return codes:
22432  *   None
22433  **/
22434 void
22435 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
22436 		       struct lpfc_sli4_hdw_queue *hdwq)
22437 {
22438 	struct list_head *buf_list = &hdwq->sgl_list;
22439 	struct sli4_hybrid_sgl *list_entry = NULL;
22440 	struct sli4_hybrid_sgl *tmp = NULL;
22441 	unsigned long iflags;
22442 
22443 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22444 
22445 	/* Free sgl pool */
22446 	list_for_each_entry_safe(list_entry, tmp,
22447 				 buf_list, list_node) {
22448 		list_del(&list_entry->list_node);
22449 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
22450 			      list_entry->dma_sgl,
22451 			      list_entry->dma_phys_sgl);
22452 		kfree(list_entry);
22453 	}
22454 
22455 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22456 }
22457 
22458 /**
22459  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
22460  * @phba: The HBA for which this call is being executed.
22461  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
22462  *
22463  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
22464  * and will allocate an CMD/RSP buffer if the pool is empty.
22465  *
22466  * Return codes:
22467  *   NULL - Error
22468  *   Pointer to fcp_cmd_rsp_buf - Success
22469  **/
22470 struct fcp_cmd_rsp_buf *
22471 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22472 			      struct lpfc_io_buf *lpfc_buf)
22473 {
22474 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22475 	struct fcp_cmd_rsp_buf *tmp = NULL;
22476 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
22477 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22478 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22479 	unsigned long iflags;
22480 
22481 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22482 
22483 	if (likely(!list_empty(buf_list))) {
22484 		/* break off 1 chunk from the list */
22485 		list_for_each_entry_safe(list_entry, tmp,
22486 					 buf_list,
22487 					 list_node) {
22488 			list_move_tail(&list_entry->list_node,
22489 				       &lpfc_buf->dma_cmd_rsp_list);
22490 			break;
22491 		}
22492 	} else {
22493 		/* allocate more */
22494 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22495 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22496 				   cpu_to_node(hdwq->io_wq->chann));
22497 		if (!tmp) {
22498 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22499 					"8355 error kmalloc memory for HDWQ "
22500 					"%d %s\n",
22501 					lpfc_buf->hdwq_no, __func__);
22502 			return NULL;
22503 		}
22504 
22505 		tmp->fcp_cmnd = dma_pool_zalloc(phba->lpfc_cmd_rsp_buf_pool,
22506 						GFP_ATOMIC,
22507 						&tmp->fcp_cmd_rsp_dma_handle);
22508 
22509 		if (!tmp->fcp_cmnd) {
22510 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22511 					"8356 error pool_alloc memory for HDWQ "
22512 					"%d %s\n",
22513 					lpfc_buf->hdwq_no, __func__);
22514 			kfree(tmp);
22515 			return NULL;
22516 		}
22517 
22518 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
22519 				sizeof(struct fcp_cmnd32));
22520 
22521 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22522 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
22523 	}
22524 
22525 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
22526 					struct fcp_cmd_rsp_buf,
22527 					list_node);
22528 
22529 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22530 
22531 	return allocated_buf;
22532 }
22533 
22534 /**
22535  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
22536  * @phba: The HBA for which this call is being executed.
22537  * @lpfc_buf: IO buf structure with the CMD/RSP buf
22538  *
22539  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
22540  *
22541  * Return codes:
22542  *   0 - Success
22543  *   -EINVAL - Error
22544  **/
22545 int
22546 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22547 			      struct lpfc_io_buf *lpfc_buf)
22548 {
22549 	int rc = 0;
22550 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22551 	struct fcp_cmd_rsp_buf *tmp = NULL;
22552 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22553 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22554 	unsigned long iflags;
22555 
22556 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22557 
22558 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
22559 		list_for_each_entry_safe(list_entry, tmp,
22560 					 &lpfc_buf->dma_cmd_rsp_list,
22561 					 list_node) {
22562 			list_move_tail(&list_entry->list_node,
22563 				       buf_list);
22564 		}
22565 	} else {
22566 		rc = -EINVAL;
22567 	}
22568 
22569 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22570 	return rc;
22571 }
22572 
22573 /**
22574  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
22575  * @phba: phba object
22576  * @hdwq: hdwq to cleanup cmd rsp buff resources on
22577  *
22578  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
22579  *
22580  * Return codes:
22581  *   None
22582  **/
22583 void
22584 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22585 			       struct lpfc_sli4_hdw_queue *hdwq)
22586 {
22587 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22588 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22589 	struct fcp_cmd_rsp_buf *tmp = NULL;
22590 	unsigned long iflags;
22591 
22592 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22593 
22594 	/* Free cmd_rsp buf pool */
22595 	list_for_each_entry_safe(list_entry, tmp,
22596 				 buf_list,
22597 				 list_node) {
22598 		list_del(&list_entry->list_node);
22599 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
22600 			      list_entry->fcp_cmnd,
22601 			      list_entry->fcp_cmd_rsp_dma_handle);
22602 		kfree(list_entry);
22603 	}
22604 
22605 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22606 }
22607 
22608 /**
22609  * lpfc_sli_prep_wqe - Prepare WQE for the command to be posted
22610  * @phba: phba object
22611  * @job: job entry of the command to be posted.
22612  *
22613  * Fill the common fields of the wqe for each of the command.
22614  *
22615  * Return codes:
22616  *	None
22617  **/
22618 void
22619 lpfc_sli_prep_wqe(struct lpfc_hba *phba, struct lpfc_iocbq *job)
22620 {
22621 	u8 cmnd;
22622 	u32 *pcmd;
22623 	u32 if_type = 0;
22624 	u32 abort_tag;
22625 	bool fip;
22626 	struct lpfc_nodelist *ndlp = NULL;
22627 	union lpfc_wqe128 *wqe = &job->wqe;
22628 	u8 command_type = ELS_COMMAND_NON_FIP;
22629 
22630 	fip = test_bit(HBA_FIP_SUPPORT, &phba->hba_flag);
22631 	/* The fcp commands will set command type */
22632 	if (job->cmd_flag &  LPFC_IO_FCP)
22633 		command_type = FCP_COMMAND;
22634 	else if (fip && (job->cmd_flag & LPFC_FIP_ELS_ID_MASK))
22635 		command_type = ELS_COMMAND_FIP;
22636 	else
22637 		command_type = ELS_COMMAND_NON_FIP;
22638 
22639 	abort_tag = job->iotag;
22640 	cmnd = bf_get(wqe_cmnd, &wqe->els_req.wqe_com);
22641 
22642 	switch (cmnd) {
22643 	case CMD_ELS_REQUEST64_WQE:
22644 		ndlp = job->ndlp;
22645 
22646 		if_type = bf_get(lpfc_sli_intf_if_type,
22647 				 &phba->sli4_hba.sli_intf);
22648 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22649 			pcmd = (u32 *)job->cmd_dmabuf->virt;
22650 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
22651 				     *pcmd == ELS_CMD_SCR ||
22652 				     *pcmd == ELS_CMD_RDF ||
22653 				     *pcmd == ELS_CMD_EDC ||
22654 				     *pcmd == ELS_CMD_RSCN_XMT ||
22655 				     *pcmd == ELS_CMD_FDISC ||
22656 				     *pcmd == ELS_CMD_LOGO ||
22657 				     *pcmd == ELS_CMD_QFPA ||
22658 				     *pcmd == ELS_CMD_UVEM ||
22659 				     *pcmd == ELS_CMD_PLOGI)) {
22660 				bf_set(els_req64_sp, &wqe->els_req, 1);
22661 				bf_set(els_req64_sid, &wqe->els_req,
22662 				       job->vport->fc_myDID);
22663 
22664 				if ((*pcmd == ELS_CMD_FLOGI) &&
22665 				    !(phba->fc_topology ==
22666 				      LPFC_TOPOLOGY_LOOP))
22667 					bf_set(els_req64_sid, &wqe->els_req, 0);
22668 
22669 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
22670 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22671 				       phba->vpi_ids[job->vport->vpi]);
22672 			} else if (pcmd) {
22673 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
22674 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22675 				       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22676 			}
22677 		}
22678 
22679 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
22680 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22681 
22682 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
22683 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
22684 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
22685 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22686 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
22687 		break;
22688 	case CMD_XMIT_ELS_RSP64_WQE:
22689 		ndlp = job->ndlp;
22690 
22691 		/* word4 */
22692 		wqe->xmit_els_rsp.word4 = 0;
22693 
22694 		if_type = bf_get(lpfc_sli_intf_if_type,
22695 				 &phba->sli4_hba.sli_intf);
22696 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22697 			if (test_bit(FC_PT2PT, &job->vport->fc_flag)) {
22698 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22699 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22700 				       job->vport->fc_myDID);
22701 				if (job->vport->fc_myDID == Fabric_DID) {
22702 					bf_set(wqe_els_did,
22703 					       &wqe->xmit_els_rsp.wqe_dest, 0);
22704 				}
22705 			}
22706 		}
22707 
22708 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
22709 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
22710 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
22711 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
22712 		       LPFC_WQE_LENLOC_WORD3);
22713 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
22714 
22715 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
22716 			bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22717 			bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22718 			       job->vport->fc_myDID);
22719 			bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
22720 		}
22721 
22722 		if (phba->sli_rev == LPFC_SLI_REV4) {
22723 			bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
22724 			       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22725 
22726 			if (bf_get(wqe_ct, &wqe->xmit_els_rsp.wqe_com))
22727 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
22728 				       phba->vpi_ids[job->vport->vpi]);
22729 		}
22730 		command_type = OTHER_COMMAND;
22731 		break;
22732 	case CMD_GEN_REQUEST64_WQE:
22733 		/* Word 10 */
22734 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
22735 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
22736 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
22737 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22738 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
22739 		command_type = OTHER_COMMAND;
22740 		break;
22741 	case CMD_XMIT_SEQUENCE64_WQE:
22742 		if (phba->link_flag & LS_LOOPBACK_MODE)
22743 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
22744 
22745 		wqe->xmit_sequence.rsvd3 = 0;
22746 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
22747 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
22748 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
22749 		       LPFC_WQE_IOD_WRITE);
22750 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
22751 		       LPFC_WQE_LENLOC_WORD12);
22752 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
22753 		command_type = OTHER_COMMAND;
22754 		break;
22755 	case CMD_XMIT_BLS_RSP64_WQE:
22756 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
22757 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
22758 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
22759 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
22760 		       phba->vpi_ids[phba->pport->vpi]);
22761 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
22762 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
22763 		       LPFC_WQE_LENLOC_NONE);
22764 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
22765 		command_type = OTHER_COMMAND;
22766 		break;
22767 	case CMD_FCP_ICMND64_WQE:	/* task mgmt commands */
22768 	case CMD_ABORT_XRI_WQE:		/* abort iotag */
22769 	case CMD_SEND_FRAME:		/* mds loopback */
22770 		/* cases already formatted for sli4 wqe - no chgs necessary */
22771 		return;
22772 	default:
22773 		dump_stack();
22774 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
22775 				"6207 Invalid command 0x%x\n",
22776 				cmnd);
22777 		break;
22778 	}
22779 
22780 	wqe->generic.wqe_com.abort_tag = abort_tag;
22781 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, job->iotag);
22782 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
22783 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
22784 }
22785