xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision 547840bd)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2020 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.  *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/pci.h>
26 #include <linux/interrupt.h>
27 #include <linux/delay.h>
28 #include <linux/slab.h>
29 #include <linux/lockdep.h>
30 
31 #include <scsi/scsi.h>
32 #include <scsi/scsi_cmnd.h>
33 #include <scsi/scsi_device.h>
34 #include <scsi/scsi_host.h>
35 #include <scsi/scsi_transport_fc.h>
36 #include <scsi/fc/fc_fs.h>
37 #include <linux/aer.h>
38 #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 *lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *,
73 							 struct lpfc_iocbq *);
74 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
75 				      struct hbq_dmabuf *);
76 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
77 					  struct hbq_dmabuf *dmabuf);
78 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
79 				   struct lpfc_queue *cq, struct lpfc_cqe *cqe);
80 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
81 				       int);
82 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
83 				     struct lpfc_queue *eq,
84 				     struct lpfc_eqe *eqe);
85 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
86 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
87 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
88 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
89 				    struct lpfc_queue *cq,
90 				    struct lpfc_cqe *cqe);
91 
92 static IOCB_t *
93 lpfc_get_iocb_from_iocbq(struct lpfc_iocbq *iocbq)
94 {
95 	return &iocbq->iocb;
96 }
97 
98 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
99 /**
100  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
101  * @srcp: Source memory pointer.
102  * @destp: Destination memory pointer.
103  * @cnt: Number of words required to be copied.
104  *       Must be a multiple of sizeof(uint64_t)
105  *
106  * This function is used for copying data between driver memory
107  * and the SLI WQ. This function also changes the endianness
108  * of each word if native endianness is different from SLI
109  * endianness. This function can be called with or without
110  * lock.
111  **/
112 static void
113 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
114 {
115 	uint64_t *src = srcp;
116 	uint64_t *dest = destp;
117 	int i;
118 
119 	for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
120 		*dest++ = *src++;
121 }
122 #else
123 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
124 #endif
125 
126 /**
127  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
128  * @q: The Work Queue to operate on.
129  * @wqe: The work Queue Entry to put on the Work queue.
130  *
131  * This routine will copy the contents of @wqe to the next available entry on
132  * the @q. This function will then ring the Work Queue Doorbell to signal the
133  * HBA to start processing the Work Queue Entry. This function returns 0 if
134  * successful. If no entries are available on @q then this function will return
135  * -ENOMEM.
136  * The caller is expected to hold the hbalock when calling this routine.
137  **/
138 static int
139 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
140 {
141 	union lpfc_wqe *temp_wqe;
142 	struct lpfc_register doorbell;
143 	uint32_t host_index;
144 	uint32_t idx;
145 	uint32_t i = 0;
146 	uint8_t *tmp;
147 	u32 if_type;
148 
149 	/* sanity check on queue memory */
150 	if (unlikely(!q))
151 		return -ENOMEM;
152 	temp_wqe = lpfc_sli4_qe(q, q->host_index);
153 
154 	/* If the host has not yet processed the next entry then we are done */
155 	idx = ((q->host_index + 1) % q->entry_count);
156 	if (idx == q->hba_index) {
157 		q->WQ_overflow++;
158 		return -EBUSY;
159 	}
160 	q->WQ_posted++;
161 	/* set consumption flag every once in a while */
162 	if (!((q->host_index + 1) % q->notify_interval))
163 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
164 	else
165 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
166 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
167 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
168 	lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
169 	if (q->dpp_enable && q->phba->cfg_enable_dpp) {
170 		/* write to DPP aperture taking advatage of Combined Writes */
171 		tmp = (uint8_t *)temp_wqe;
172 #ifdef __raw_writeq
173 		for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
174 			__raw_writeq(*((uint64_t *)(tmp + i)),
175 					q->dpp_regaddr + i);
176 #else
177 		for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
178 			__raw_writel(*((uint32_t *)(tmp + i)),
179 					q->dpp_regaddr + i);
180 #endif
181 	}
182 	/* ensure WQE bcopy and DPP flushed before doorbell write */
183 	wmb();
184 
185 	/* Update the host index before invoking device */
186 	host_index = q->host_index;
187 
188 	q->host_index = idx;
189 
190 	/* Ring Doorbell */
191 	doorbell.word0 = 0;
192 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
193 		if (q->dpp_enable && q->phba->cfg_enable_dpp) {
194 			bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
195 			bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
196 			bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
197 			    q->dpp_id);
198 			bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
199 			    q->queue_id);
200 		} else {
201 			bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
202 			bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
203 
204 			/* Leave bits <23:16> clear for if_type 6 dpp */
205 			if_type = bf_get(lpfc_sli_intf_if_type,
206 					 &q->phba->sli4_hba.sli_intf);
207 			if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
208 				bf_set(lpfc_wq_db_list_fm_index, &doorbell,
209 				       host_index);
210 		}
211 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
212 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
213 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
214 	} else {
215 		return -EINVAL;
216 	}
217 	writel(doorbell.word0, q->db_regaddr);
218 
219 	return 0;
220 }
221 
222 /**
223  * lpfc_sli4_wq_release - Updates internal hba index for WQ
224  * @q: The Work Queue to operate on.
225  * @index: The index to advance the hba index to.
226  *
227  * This routine will update the HBA index of a queue to reflect consumption of
228  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
229  * an entry the host calls this function to update the queue's internal
230  * pointers.
231  **/
232 static void
233 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
234 {
235 	/* sanity check on queue memory */
236 	if (unlikely(!q))
237 		return;
238 
239 	q->hba_index = index;
240 }
241 
242 /**
243  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
244  * @q: The Mailbox Queue to operate on.
245  * @wqe: The Mailbox Queue Entry to put on the Work queue.
246  *
247  * This routine will copy the contents of @mqe to the next available entry on
248  * the @q. This function will then ring the Work Queue Doorbell to signal the
249  * HBA to start processing the Work Queue Entry. This function returns 0 if
250  * successful. If no entries are available on @q then this function will return
251  * -ENOMEM.
252  * The caller is expected to hold the hbalock when calling this routine.
253  **/
254 static uint32_t
255 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
256 {
257 	struct lpfc_mqe *temp_mqe;
258 	struct lpfc_register doorbell;
259 
260 	/* sanity check on queue memory */
261 	if (unlikely(!q))
262 		return -ENOMEM;
263 	temp_mqe = lpfc_sli4_qe(q, q->host_index);
264 
265 	/* If the host has not yet processed the next entry then we are done */
266 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
267 		return -ENOMEM;
268 	lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
269 	/* Save off the mailbox pointer for completion */
270 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
271 
272 	/* Update the host index before invoking device */
273 	q->host_index = ((q->host_index + 1) % q->entry_count);
274 
275 	/* Ring Doorbell */
276 	doorbell.word0 = 0;
277 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
278 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
279 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
280 	return 0;
281 }
282 
283 /**
284  * lpfc_sli4_mq_release - Updates internal hba index for MQ
285  * @q: The Mailbox Queue to operate on.
286  *
287  * This routine will update the HBA index of a queue to reflect consumption of
288  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
289  * an entry the host calls this function to update the queue's internal
290  * pointers. This routine returns the number of entries that were consumed by
291  * the HBA.
292  **/
293 static uint32_t
294 lpfc_sli4_mq_release(struct lpfc_queue *q)
295 {
296 	/* sanity check on queue memory */
297 	if (unlikely(!q))
298 		return 0;
299 
300 	/* Clear the mailbox pointer for completion */
301 	q->phba->mbox = NULL;
302 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
303 	return 1;
304 }
305 
306 /**
307  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
308  * @q: The Event Queue to get the first valid EQE from
309  *
310  * This routine will get the first valid Event Queue Entry from @q, update
311  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
312  * the Queue (no more work to do), or the Queue is full of EQEs that have been
313  * processed, but not popped back to the HBA then this routine will return NULL.
314  **/
315 static struct lpfc_eqe *
316 lpfc_sli4_eq_get(struct lpfc_queue *q)
317 {
318 	struct lpfc_eqe *eqe;
319 
320 	/* sanity check on queue memory */
321 	if (unlikely(!q))
322 		return NULL;
323 	eqe = lpfc_sli4_qe(q, q->host_index);
324 
325 	/* If the next EQE is not valid then we are done */
326 	if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
327 		return NULL;
328 
329 	/*
330 	 * insert barrier for instruction interlock : data from the hardware
331 	 * must have the valid bit checked before it can be copied and acted
332 	 * upon. Speculative instructions were allowing a bcopy at the start
333 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
334 	 * after our return, to copy data before the valid bit check above
335 	 * was done. As such, some of the copied data was stale. The barrier
336 	 * ensures the check is before any data is copied.
337 	 */
338 	mb();
339 	return eqe;
340 }
341 
342 /**
343  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
344  * @q: The Event Queue to disable interrupts
345  *
346  **/
347 void
348 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
349 {
350 	struct lpfc_register doorbell;
351 
352 	doorbell.word0 = 0;
353 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
354 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
355 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
356 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
357 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
358 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
359 }
360 
361 /**
362  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
363  * @q: The Event Queue to disable interrupts
364  *
365  **/
366 void
367 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
368 {
369 	struct lpfc_register doorbell;
370 
371 	doorbell.word0 = 0;
372 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
373 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
374 }
375 
376 /**
377  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
378  * @phba: adapter with EQ
379  * @q: The Event Queue that the host has completed processing for.
380  * @count: Number of elements that have been consumed
381  * @arm: Indicates whether the host wants to arms this CQ.
382  *
383  * This routine will notify the HBA, by ringing the doorbell, that count
384  * number of EQEs have been processed. The @arm parameter indicates whether
385  * the queue should be rearmed when ringing the doorbell.
386  **/
387 void
388 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
389 		     uint32_t count, bool arm)
390 {
391 	struct lpfc_register doorbell;
392 
393 	/* sanity check on queue memory */
394 	if (unlikely(!q || (count == 0 && !arm)))
395 		return;
396 
397 	/* ring doorbell for number popped */
398 	doorbell.word0 = 0;
399 	if (arm) {
400 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
401 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
402 	}
403 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
404 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
405 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
406 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
407 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
408 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
409 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
410 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
411 		readl(q->phba->sli4_hba.EQDBregaddr);
412 }
413 
414 /**
415  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
416  * @phba: adapter with EQ
417  * @q: The Event Queue that the host has completed processing for.
418  * @count: Number of elements that have been consumed
419  * @arm: Indicates whether the host wants to arms this CQ.
420  *
421  * This routine will notify the HBA, by ringing the doorbell, that count
422  * number of EQEs have been processed. The @arm parameter indicates whether
423  * the queue should be rearmed when ringing the doorbell.
424  **/
425 void
426 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
427 			  uint32_t count, bool arm)
428 {
429 	struct lpfc_register doorbell;
430 
431 	/* sanity check on queue memory */
432 	if (unlikely(!q || (count == 0 && !arm)))
433 		return;
434 
435 	/* ring doorbell for number popped */
436 	doorbell.word0 = 0;
437 	if (arm)
438 		bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
439 	bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
440 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
441 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
442 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
443 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
444 		readl(q->phba->sli4_hba.EQDBregaddr);
445 }
446 
447 static void
448 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
449 			struct lpfc_eqe *eqe)
450 {
451 	if (!phba->sli4_hba.pc_sli4_params.eqav)
452 		bf_set_le32(lpfc_eqe_valid, eqe, 0);
453 
454 	eq->host_index = ((eq->host_index + 1) % eq->entry_count);
455 
456 	/* if the index wrapped around, toggle the valid bit */
457 	if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
458 		eq->qe_valid = (eq->qe_valid) ? 0 : 1;
459 }
460 
461 static void
462 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
463 {
464 	struct lpfc_eqe *eqe = NULL;
465 	u32 eq_count = 0, cq_count = 0;
466 	struct lpfc_cqe *cqe = NULL;
467 	struct lpfc_queue *cq = NULL, *childq = NULL;
468 	int cqid = 0;
469 
470 	/* walk all the EQ entries and drop on the floor */
471 	eqe = lpfc_sli4_eq_get(eq);
472 	while (eqe) {
473 		/* Get the reference to the corresponding CQ */
474 		cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
475 		cq = NULL;
476 
477 		list_for_each_entry(childq, &eq->child_list, list) {
478 			if (childq->queue_id == cqid) {
479 				cq = childq;
480 				break;
481 			}
482 		}
483 		/* If CQ is valid, iterate through it and drop all the CQEs */
484 		if (cq) {
485 			cqe = lpfc_sli4_cq_get(cq);
486 			while (cqe) {
487 				__lpfc_sli4_consume_cqe(phba, cq, cqe);
488 				cq_count++;
489 				cqe = lpfc_sli4_cq_get(cq);
490 			}
491 			/* Clear and re-arm the CQ */
492 			phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
493 			    LPFC_QUEUE_REARM);
494 			cq_count = 0;
495 		}
496 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
497 		eq_count++;
498 		eqe = lpfc_sli4_eq_get(eq);
499 	}
500 
501 	/* Clear and re-arm the EQ */
502 	phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
503 }
504 
505 static int
506 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
507 		     uint8_t rearm)
508 {
509 	struct lpfc_eqe *eqe;
510 	int count = 0, consumed = 0;
511 
512 	if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
513 		goto rearm_and_exit;
514 
515 	eqe = lpfc_sli4_eq_get(eq);
516 	while (eqe) {
517 		lpfc_sli4_hba_handle_eqe(phba, eq, eqe);
518 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
519 
520 		consumed++;
521 		if (!(++count % eq->max_proc_limit))
522 			break;
523 
524 		if (!(count % eq->notify_interval)) {
525 			phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
526 							LPFC_QUEUE_NOARM);
527 			consumed = 0;
528 		}
529 
530 		eqe = lpfc_sli4_eq_get(eq);
531 	}
532 	eq->EQ_processed += count;
533 
534 	/* Track the max number of EQEs processed in 1 intr */
535 	if (count > eq->EQ_max_eqe)
536 		eq->EQ_max_eqe = count;
537 
538 	eq->queue_claimed = 0;
539 
540 rearm_and_exit:
541 	/* Always clear the EQ. */
542 	phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
543 
544 	return count;
545 }
546 
547 /**
548  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
549  * @q: The Completion Queue to get the first valid CQE from
550  *
551  * This routine will get the first valid Completion Queue Entry from @q, update
552  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
553  * the Queue (no more work to do), or the Queue is full of CQEs that have been
554  * processed, but not popped back to the HBA then this routine will return NULL.
555  **/
556 static struct lpfc_cqe *
557 lpfc_sli4_cq_get(struct lpfc_queue *q)
558 {
559 	struct lpfc_cqe *cqe;
560 
561 	/* sanity check on queue memory */
562 	if (unlikely(!q))
563 		return NULL;
564 	cqe = lpfc_sli4_qe(q, q->host_index);
565 
566 	/* If the next CQE is not valid then we are done */
567 	if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
568 		return NULL;
569 
570 	/*
571 	 * insert barrier for instruction interlock : data from the hardware
572 	 * must have the valid bit checked before it can be copied and acted
573 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
574 	 * instructions allowing action on content before valid bit checked,
575 	 * add barrier here as well. May not be needed as "content" is a
576 	 * single 32-bit entity here (vs multi word structure for cq's).
577 	 */
578 	mb();
579 	return cqe;
580 }
581 
582 static void
583 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
584 			struct lpfc_cqe *cqe)
585 {
586 	if (!phba->sli4_hba.pc_sli4_params.cqav)
587 		bf_set_le32(lpfc_cqe_valid, cqe, 0);
588 
589 	cq->host_index = ((cq->host_index + 1) % cq->entry_count);
590 
591 	/* if the index wrapped around, toggle the valid bit */
592 	if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
593 		cq->qe_valid = (cq->qe_valid) ? 0 : 1;
594 }
595 
596 /**
597  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
598  * @phba: the adapter with the CQ
599  * @q: The Completion Queue that the host has completed processing for.
600  * @count: the number of elements that were consumed
601  * @arm: Indicates whether the host wants to arms this CQ.
602  *
603  * This routine will notify the HBA, by ringing the doorbell, that the
604  * CQEs have been processed. The @arm parameter specifies whether the
605  * queue should be rearmed when ringing the doorbell.
606  **/
607 void
608 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
609 		     uint32_t count, bool arm)
610 {
611 	struct lpfc_register doorbell;
612 
613 	/* sanity check on queue memory */
614 	if (unlikely(!q || (count == 0 && !arm)))
615 		return;
616 
617 	/* ring doorbell for number popped */
618 	doorbell.word0 = 0;
619 	if (arm)
620 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
621 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
622 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
623 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
624 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
625 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
626 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
627 }
628 
629 /**
630  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
631  * @phba: the adapter with the CQ
632  * @q: The Completion Queue that the host has completed processing for.
633  * @count: the number of elements that were consumed
634  * @arm: Indicates whether the host wants to arms this CQ.
635  *
636  * This routine will notify the HBA, by ringing the doorbell, that the
637  * CQEs have been processed. The @arm parameter specifies whether the
638  * queue should be rearmed when ringing the doorbell.
639  **/
640 void
641 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
642 			 uint32_t count, bool arm)
643 {
644 	struct lpfc_register doorbell;
645 
646 	/* sanity check on queue memory */
647 	if (unlikely(!q || (count == 0 && !arm)))
648 		return;
649 
650 	/* ring doorbell for number popped */
651 	doorbell.word0 = 0;
652 	if (arm)
653 		bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
654 	bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
655 	bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
656 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
657 }
658 
659 /**
660  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
661  * @q: The Header Receive Queue to operate on.
662  * @wqe: The Receive Queue Entry to put on the Receive queue.
663  *
664  * This routine will copy the contents of @wqe to the next available entry on
665  * the @q. This function will then ring the Receive Queue Doorbell to signal the
666  * HBA to start processing the Receive Queue Entry. This function returns the
667  * index that the rqe was copied to if successful. If no entries are available
668  * on @q then this function will return -ENOMEM.
669  * The caller is expected to hold the hbalock when calling this routine.
670  **/
671 int
672 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
673 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
674 {
675 	struct lpfc_rqe *temp_hrqe;
676 	struct lpfc_rqe *temp_drqe;
677 	struct lpfc_register doorbell;
678 	int hq_put_index;
679 	int dq_put_index;
680 
681 	/* sanity check on queue memory */
682 	if (unlikely(!hq) || unlikely(!dq))
683 		return -ENOMEM;
684 	hq_put_index = hq->host_index;
685 	dq_put_index = dq->host_index;
686 	temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
687 	temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
688 
689 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
690 		return -EINVAL;
691 	if (hq_put_index != dq_put_index)
692 		return -EINVAL;
693 	/* If the host has not yet processed the next entry then we are done */
694 	if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
695 		return -EBUSY;
696 	lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
697 	lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
698 
699 	/* Update the host index to point to the next slot */
700 	hq->host_index = ((hq_put_index + 1) % hq->entry_count);
701 	dq->host_index = ((dq_put_index + 1) % dq->entry_count);
702 	hq->RQ_buf_posted++;
703 
704 	/* Ring The Header Receive Queue Doorbell */
705 	if (!(hq->host_index % hq->notify_interval)) {
706 		doorbell.word0 = 0;
707 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
708 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
709 			       hq->notify_interval);
710 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
711 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
712 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
713 			       hq->notify_interval);
714 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
715 			       hq->host_index);
716 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
717 		} else {
718 			return -EINVAL;
719 		}
720 		writel(doorbell.word0, hq->db_regaddr);
721 	}
722 	return hq_put_index;
723 }
724 
725 /**
726  * lpfc_sli4_rq_release - Updates internal hba index for RQ
727  * @q: The Header Receive Queue to operate on.
728  *
729  * This routine will update the HBA index of a queue to reflect consumption of
730  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
731  * consumed an entry the host calls this function to update the queue's
732  * internal pointers. This routine returns the number of entries that were
733  * consumed by the HBA.
734  **/
735 static uint32_t
736 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
737 {
738 	/* sanity check on queue memory */
739 	if (unlikely(!hq) || unlikely(!dq))
740 		return 0;
741 
742 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
743 		return 0;
744 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
745 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
746 	return 1;
747 }
748 
749 /**
750  * lpfc_cmd_iocb - Get next command iocb entry in the ring
751  * @phba: Pointer to HBA context object.
752  * @pring: Pointer to driver SLI ring object.
753  *
754  * This function returns pointer to next command iocb entry
755  * in the command ring. The caller must hold hbalock to prevent
756  * other threads consume the next command iocb.
757  * SLI-2/SLI-3 provide different sized iocbs.
758  **/
759 static inline IOCB_t *
760 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
761 {
762 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
763 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
764 }
765 
766 /**
767  * lpfc_resp_iocb - Get next response iocb entry in the ring
768  * @phba: Pointer to HBA context object.
769  * @pring: Pointer to driver SLI ring object.
770  *
771  * This function returns pointer to next response iocb entry
772  * in the response ring. The caller must hold hbalock to make sure
773  * that no other thread consume the next response iocb.
774  * SLI-2/SLI-3 provide different sized iocbs.
775  **/
776 static inline IOCB_t *
777 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
778 {
779 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
780 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
781 }
782 
783 /**
784  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
785  * @phba: Pointer to HBA context object.
786  *
787  * This function is called with hbalock held. This function
788  * allocates a new driver iocb object from the iocb pool. If the
789  * allocation is successful, it returns pointer to the newly
790  * allocated iocb object else it returns NULL.
791  **/
792 struct lpfc_iocbq *
793 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
794 {
795 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
796 	struct lpfc_iocbq * iocbq = NULL;
797 
798 	lockdep_assert_held(&phba->hbalock);
799 
800 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
801 	if (iocbq)
802 		phba->iocb_cnt++;
803 	if (phba->iocb_cnt > phba->iocb_max)
804 		phba->iocb_max = phba->iocb_cnt;
805 	return iocbq;
806 }
807 
808 /**
809  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
810  * @phba: Pointer to HBA context object.
811  * @xritag: XRI value.
812  *
813  * This function clears the sglq pointer from the array of acive
814  * sglq's. The xritag that is passed in is used to index into the
815  * array. Before the xritag can be used it needs to be adjusted
816  * by subtracting the xribase.
817  *
818  * Returns sglq ponter = success, NULL = Failure.
819  **/
820 struct lpfc_sglq *
821 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
822 {
823 	struct lpfc_sglq *sglq;
824 
825 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
826 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
827 	return sglq;
828 }
829 
830 /**
831  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
832  * @phba: Pointer to HBA context object.
833  * @xritag: XRI value.
834  *
835  * This function returns the sglq pointer from the array of acive
836  * sglq's. The xritag that is passed in is used to index into the
837  * array. Before the xritag can be used it needs to be adjusted
838  * by subtracting the xribase.
839  *
840  * Returns sglq ponter = success, NULL = Failure.
841  **/
842 struct lpfc_sglq *
843 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
844 {
845 	struct lpfc_sglq *sglq;
846 
847 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
848 	return sglq;
849 }
850 
851 /**
852  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
853  * @phba: Pointer to HBA context object.
854  * @xritag: xri used in this exchange.
855  * @rrq: The RRQ to be cleared.
856  *
857  **/
858 void
859 lpfc_clr_rrq_active(struct lpfc_hba *phba,
860 		    uint16_t xritag,
861 		    struct lpfc_node_rrq *rrq)
862 {
863 	struct lpfc_nodelist *ndlp = NULL;
864 
865 	if ((rrq->vport) && NLP_CHK_NODE_ACT(rrq->ndlp))
866 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
867 
868 	/* The target DID could have been swapped (cable swap)
869 	 * we should use the ndlp from the findnode if it is
870 	 * available.
871 	 */
872 	if ((!ndlp) && rrq->ndlp)
873 		ndlp = rrq->ndlp;
874 
875 	if (!ndlp)
876 		goto out;
877 
878 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
879 		rrq->send_rrq = 0;
880 		rrq->xritag = 0;
881 		rrq->rrq_stop_time = 0;
882 	}
883 out:
884 	mempool_free(rrq, phba->rrq_pool);
885 }
886 
887 /**
888  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
889  * @phba: Pointer to HBA context object.
890  *
891  * This function is called with hbalock held. This function
892  * Checks if stop_time (ratov from setting rrq active) has
893  * been reached, if it has and the send_rrq flag is set then
894  * it will call lpfc_send_rrq. If the send_rrq flag is not set
895  * then it will just call the routine to clear the rrq and
896  * free the rrq resource.
897  * The timer is set to the next rrq that is going to expire before
898  * leaving the routine.
899  *
900  **/
901 void
902 lpfc_handle_rrq_active(struct lpfc_hba *phba)
903 {
904 	struct lpfc_node_rrq *rrq;
905 	struct lpfc_node_rrq *nextrrq;
906 	unsigned long next_time;
907 	unsigned long iflags;
908 	LIST_HEAD(send_rrq);
909 
910 	spin_lock_irqsave(&phba->hbalock, iflags);
911 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
912 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
913 	list_for_each_entry_safe(rrq, nextrrq,
914 				 &phba->active_rrq_list, list) {
915 		if (time_after(jiffies, rrq->rrq_stop_time))
916 			list_move(&rrq->list, &send_rrq);
917 		else if (time_before(rrq->rrq_stop_time, next_time))
918 			next_time = rrq->rrq_stop_time;
919 	}
920 	spin_unlock_irqrestore(&phba->hbalock, iflags);
921 	if ((!list_empty(&phba->active_rrq_list)) &&
922 	    (!(phba->pport->load_flag & FC_UNLOADING)))
923 		mod_timer(&phba->rrq_tmr, next_time);
924 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
925 		list_del(&rrq->list);
926 		if (!rrq->send_rrq) {
927 			/* this call will free the rrq */
928 			lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
929 		} else if (lpfc_send_rrq(phba, rrq)) {
930 			/* if we send the rrq then the completion handler
931 			*  will clear the bit in the xribitmap.
932 			*/
933 			lpfc_clr_rrq_active(phba, rrq->xritag,
934 					    rrq);
935 		}
936 	}
937 }
938 
939 /**
940  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
941  * @vport: Pointer to vport context object.
942  * @xri: The xri used in the exchange.
943  * @did: The targets DID for this exchange.
944  *
945  * returns NULL = rrq not found in the phba->active_rrq_list.
946  *         rrq = rrq for this xri and target.
947  **/
948 struct lpfc_node_rrq *
949 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
950 {
951 	struct lpfc_hba *phba = vport->phba;
952 	struct lpfc_node_rrq *rrq;
953 	struct lpfc_node_rrq *nextrrq;
954 	unsigned long iflags;
955 
956 	if (phba->sli_rev != LPFC_SLI_REV4)
957 		return NULL;
958 	spin_lock_irqsave(&phba->hbalock, iflags);
959 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
960 		if (rrq->vport == vport && rrq->xritag == xri &&
961 				rrq->nlp_DID == did){
962 			list_del(&rrq->list);
963 			spin_unlock_irqrestore(&phba->hbalock, iflags);
964 			return rrq;
965 		}
966 	}
967 	spin_unlock_irqrestore(&phba->hbalock, iflags);
968 	return NULL;
969 }
970 
971 /**
972  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
973  * @vport: Pointer to vport context object.
974  * @ndlp: Pointer to the lpfc_node_list structure.
975  * If ndlp is NULL Remove all active RRQs for this vport from the
976  * phba->active_rrq_list and clear the rrq.
977  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
978  **/
979 void
980 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
981 
982 {
983 	struct lpfc_hba *phba = vport->phba;
984 	struct lpfc_node_rrq *rrq;
985 	struct lpfc_node_rrq *nextrrq;
986 	unsigned long iflags;
987 	LIST_HEAD(rrq_list);
988 
989 	if (phba->sli_rev != LPFC_SLI_REV4)
990 		return;
991 	if (!ndlp) {
992 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
993 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
994 	}
995 	spin_lock_irqsave(&phba->hbalock, iflags);
996 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list)
997 		if ((rrq->vport == vport) && (!ndlp  || rrq->ndlp == ndlp))
998 			list_move(&rrq->list, &rrq_list);
999 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1000 
1001 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1002 		list_del(&rrq->list);
1003 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1004 	}
1005 }
1006 
1007 /**
1008  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1009  * @phba: Pointer to HBA context object.
1010  * @ndlp: Targets nodelist pointer for this exchange.
1011  * @xritag the xri in the bitmap to test.
1012  *
1013  * This function returns:
1014  * 0 = rrq not active for this xri
1015  * 1 = rrq is valid for this xri.
1016  **/
1017 int
1018 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1019 			uint16_t  xritag)
1020 {
1021 	if (!ndlp)
1022 		return 0;
1023 	if (!ndlp->active_rrqs_xri_bitmap)
1024 		return 0;
1025 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1026 		return 1;
1027 	else
1028 		return 0;
1029 }
1030 
1031 /**
1032  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1033  * @phba: Pointer to HBA context object.
1034  * @ndlp: nodelist pointer for this target.
1035  * @xritag: xri used in this exchange.
1036  * @rxid: Remote Exchange ID.
1037  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1038  *
1039  * This function takes the hbalock.
1040  * The active bit is always set in the active rrq xri_bitmap even
1041  * if there is no slot avaiable for the other rrq information.
1042  *
1043  * returns 0 rrq actived for this xri
1044  *         < 0 No memory or invalid ndlp.
1045  **/
1046 int
1047 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1048 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1049 {
1050 	unsigned long iflags;
1051 	struct lpfc_node_rrq *rrq;
1052 	int empty;
1053 
1054 	if (!ndlp)
1055 		return -EINVAL;
1056 
1057 	if (!phba->cfg_enable_rrq)
1058 		return -EINVAL;
1059 
1060 	spin_lock_irqsave(&phba->hbalock, iflags);
1061 	if (phba->pport->load_flag & FC_UNLOADING) {
1062 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1063 		goto out;
1064 	}
1065 
1066 	/*
1067 	 * set the active bit even if there is no mem available.
1068 	 */
1069 	if (NLP_CHK_FREE_REQ(ndlp))
1070 		goto out;
1071 
1072 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
1073 		goto out;
1074 
1075 	if (!ndlp->active_rrqs_xri_bitmap)
1076 		goto out;
1077 
1078 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1079 		goto out;
1080 
1081 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1082 	rrq = mempool_alloc(phba->rrq_pool, GFP_KERNEL);
1083 	if (!rrq) {
1084 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1085 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1086 				" DID:0x%x Send:%d\n",
1087 				xritag, rxid, ndlp->nlp_DID, send_rrq);
1088 		return -EINVAL;
1089 	}
1090 	if (phba->cfg_enable_rrq == 1)
1091 		rrq->send_rrq = send_rrq;
1092 	else
1093 		rrq->send_rrq = 0;
1094 	rrq->xritag = xritag;
1095 	rrq->rrq_stop_time = jiffies +
1096 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1097 	rrq->ndlp = ndlp;
1098 	rrq->nlp_DID = ndlp->nlp_DID;
1099 	rrq->vport = ndlp->vport;
1100 	rrq->rxid = rxid;
1101 	spin_lock_irqsave(&phba->hbalock, iflags);
1102 	empty = list_empty(&phba->active_rrq_list);
1103 	list_add_tail(&rrq->list, &phba->active_rrq_list);
1104 	phba->hba_flag |= HBA_RRQ_ACTIVE;
1105 	if (empty)
1106 		lpfc_worker_wake_up(phba);
1107 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1108 	return 0;
1109 out:
1110 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1111 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1112 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
1113 			" DID:0x%x Send:%d\n",
1114 			xritag, rxid, ndlp->nlp_DID, send_rrq);
1115 	return -EINVAL;
1116 }
1117 
1118 /**
1119  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1120  * @phba: Pointer to HBA context object.
1121  * @piocb: Pointer to the iocbq.
1122  *
1123  * The driver calls this function with either the nvme ls ring lock
1124  * or the fc els ring lock held depending on the iocb usage.  This function
1125  * gets a new driver sglq object from the sglq list. If the list is not empty
1126  * then it is successful, it returns pointer to the newly allocated sglq
1127  * object else it returns NULL.
1128  **/
1129 static struct lpfc_sglq *
1130 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1131 {
1132 	struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1133 	struct lpfc_sglq *sglq = NULL;
1134 	struct lpfc_sglq *start_sglq = NULL;
1135 	struct lpfc_io_buf *lpfc_cmd;
1136 	struct lpfc_nodelist *ndlp;
1137 	struct lpfc_sli_ring *pring = NULL;
1138 	int found = 0;
1139 
1140 	if (piocbq->iocb_flag & LPFC_IO_NVME_LS)
1141 		pring =  phba->sli4_hba.nvmels_wq->pring;
1142 	else
1143 		pring = lpfc_phba_elsring(phba);
1144 
1145 	lockdep_assert_held(&pring->ring_lock);
1146 
1147 	if (piocbq->iocb_flag &  LPFC_IO_FCP) {
1148 		lpfc_cmd = (struct lpfc_io_buf *) piocbq->context1;
1149 		ndlp = lpfc_cmd->rdata->pnode;
1150 	} else  if ((piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) &&
1151 			!(piocbq->iocb_flag & LPFC_IO_LIBDFC)) {
1152 		ndlp = piocbq->context_un.ndlp;
1153 	} else  if (piocbq->iocb_flag & LPFC_IO_LIBDFC) {
1154 		if (piocbq->iocb_flag & LPFC_IO_LOOPBACK)
1155 			ndlp = NULL;
1156 		else
1157 			ndlp = piocbq->context_un.ndlp;
1158 	} else {
1159 		ndlp = piocbq->context1;
1160 	}
1161 
1162 	spin_lock(&phba->sli4_hba.sgl_list_lock);
1163 	list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1164 	start_sglq = sglq;
1165 	while (!found) {
1166 		if (!sglq)
1167 			break;
1168 		if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1169 		    test_bit(sglq->sli4_lxritag,
1170 		    ndlp->active_rrqs_xri_bitmap)) {
1171 			/* This xri has an rrq outstanding for this DID.
1172 			 * put it back in the list and get another xri.
1173 			 */
1174 			list_add_tail(&sglq->list, lpfc_els_sgl_list);
1175 			sglq = NULL;
1176 			list_remove_head(lpfc_els_sgl_list, sglq,
1177 						struct lpfc_sglq, list);
1178 			if (sglq == start_sglq) {
1179 				list_add_tail(&sglq->list, lpfc_els_sgl_list);
1180 				sglq = NULL;
1181 				break;
1182 			} else
1183 				continue;
1184 		}
1185 		sglq->ndlp = ndlp;
1186 		found = 1;
1187 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1188 		sglq->state = SGL_ALLOCATED;
1189 	}
1190 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
1191 	return sglq;
1192 }
1193 
1194 /**
1195  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1196  * @phba: Pointer to HBA context object.
1197  * @piocb: Pointer to the iocbq.
1198  *
1199  * This function is called with the sgl_list lock held. This function
1200  * gets a new driver sglq object from the sglq list. If the
1201  * list is not empty then it is successful, it returns pointer to the newly
1202  * allocated sglq object else it returns NULL.
1203  **/
1204 struct lpfc_sglq *
1205 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1206 {
1207 	struct list_head *lpfc_nvmet_sgl_list;
1208 	struct lpfc_sglq *sglq = NULL;
1209 
1210 	lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1211 
1212 	lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1213 
1214 	list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1215 	if (!sglq)
1216 		return NULL;
1217 	phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1218 	sglq->state = SGL_ALLOCATED;
1219 	return sglq;
1220 }
1221 
1222 /**
1223  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1224  * @phba: Pointer to HBA context object.
1225  *
1226  * This function is called with no lock held. This function
1227  * allocates a new driver iocb object from the iocb pool. If the
1228  * allocation is successful, it returns pointer to the newly
1229  * allocated iocb object else it returns NULL.
1230  **/
1231 struct lpfc_iocbq *
1232 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1233 {
1234 	struct lpfc_iocbq * iocbq = NULL;
1235 	unsigned long iflags;
1236 
1237 	spin_lock_irqsave(&phba->hbalock, iflags);
1238 	iocbq = __lpfc_sli_get_iocbq(phba);
1239 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1240 	return iocbq;
1241 }
1242 
1243 /**
1244  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1245  * @phba: Pointer to HBA context object.
1246  * @iocbq: Pointer to driver iocb object.
1247  *
1248  * This function is called with hbalock held to release driver
1249  * iocb object to the iocb pool. The iotag in the iocb object
1250  * does not change for each use of the iocb object. This function
1251  * clears all other fields of the iocb object when it is freed.
1252  * The sqlq structure that holds the xritag and phys and virtual
1253  * mappings for the scatter gather list is retrieved from the
1254  * active array of sglq. The get of the sglq pointer also clears
1255  * the entry in the array. If the status of the IO indiactes that
1256  * this IO was aborted then the sglq entry it put on the
1257  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1258  * IO has good status or fails for any other reason then the sglq
1259  * entry is added to the free list (lpfc_els_sgl_list).
1260  **/
1261 static void
1262 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1263 {
1264 	struct lpfc_sglq *sglq;
1265 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1266 	unsigned long iflag = 0;
1267 	struct lpfc_sli_ring *pring;
1268 
1269 	lockdep_assert_held(&phba->hbalock);
1270 
1271 	if (iocbq->sli4_xritag == NO_XRI)
1272 		sglq = NULL;
1273 	else
1274 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1275 
1276 
1277 	if (sglq)  {
1278 		if (iocbq->iocb_flag & LPFC_IO_NVMET) {
1279 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1280 					  iflag);
1281 			sglq->state = SGL_FREED;
1282 			sglq->ndlp = NULL;
1283 			list_add_tail(&sglq->list,
1284 				      &phba->sli4_hba.lpfc_nvmet_sgl_list);
1285 			spin_unlock_irqrestore(
1286 				&phba->sli4_hba.sgl_list_lock, iflag);
1287 			goto out;
1288 		}
1289 
1290 		pring = phba->sli4_hba.els_wq->pring;
1291 		if ((iocbq->iocb_flag & LPFC_EXCHANGE_BUSY) &&
1292 			(sglq->state != SGL_XRI_ABORTED)) {
1293 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1294 					  iflag);
1295 			list_add(&sglq->list,
1296 				 &phba->sli4_hba.lpfc_abts_els_sgl_list);
1297 			spin_unlock_irqrestore(
1298 				&phba->sli4_hba.sgl_list_lock, iflag);
1299 		} else {
1300 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1301 					  iflag);
1302 			sglq->state = SGL_FREED;
1303 			sglq->ndlp = NULL;
1304 			list_add_tail(&sglq->list,
1305 				      &phba->sli4_hba.lpfc_els_sgl_list);
1306 			spin_unlock_irqrestore(
1307 				&phba->sli4_hba.sgl_list_lock, iflag);
1308 
1309 			/* Check if TXQ queue needs to be serviced */
1310 			if (!list_empty(&pring->txq))
1311 				lpfc_worker_wake_up(phba);
1312 		}
1313 	}
1314 
1315 out:
1316 	/*
1317 	 * Clean all volatile data fields, preserve iotag and node struct.
1318 	 */
1319 	memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1320 	iocbq->sli4_lxritag = NO_XRI;
1321 	iocbq->sli4_xritag = NO_XRI;
1322 	iocbq->iocb_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET |
1323 			      LPFC_IO_NVME_LS);
1324 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1325 }
1326 
1327 
1328 /**
1329  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1330  * @phba: Pointer to HBA context object.
1331  * @iocbq: Pointer to driver iocb object.
1332  *
1333  * This function is called with hbalock held to release driver
1334  * iocb object to the iocb pool. The iotag in the iocb object
1335  * does not change for each use of the iocb object. This function
1336  * clears all other fields of the iocb object when it is freed.
1337  **/
1338 static void
1339 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1340 {
1341 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1342 
1343 	lockdep_assert_held(&phba->hbalock);
1344 
1345 	/*
1346 	 * Clean all volatile data fields, preserve iotag and node struct.
1347 	 */
1348 	memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1349 	iocbq->sli4_xritag = NO_XRI;
1350 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1351 }
1352 
1353 /**
1354  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1355  * @phba: Pointer to HBA context object.
1356  * @iocbq: Pointer to driver iocb object.
1357  *
1358  * This function is called with hbalock held to release driver
1359  * iocb object to the iocb pool. The iotag in the iocb object
1360  * does not change for each use of the iocb object. This function
1361  * clears all other fields of the iocb object when it is freed.
1362  **/
1363 static void
1364 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1365 {
1366 	lockdep_assert_held(&phba->hbalock);
1367 
1368 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1369 	phba->iocb_cnt--;
1370 }
1371 
1372 /**
1373  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1374  * @phba: Pointer to HBA context object.
1375  * @iocbq: Pointer to driver iocb object.
1376  *
1377  * This function is called with no lock held to release the iocb to
1378  * iocb pool.
1379  **/
1380 void
1381 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1382 {
1383 	unsigned long iflags;
1384 
1385 	/*
1386 	 * Clean all volatile data fields, preserve iotag and node struct.
1387 	 */
1388 	spin_lock_irqsave(&phba->hbalock, iflags);
1389 	__lpfc_sli_release_iocbq(phba, iocbq);
1390 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1391 }
1392 
1393 /**
1394  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1395  * @phba: Pointer to HBA context object.
1396  * @iocblist: List of IOCBs.
1397  * @ulpstatus: ULP status in IOCB command field.
1398  * @ulpWord4: ULP word-4 in IOCB command field.
1399  *
1400  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1401  * on the list by invoking the complete callback function associated with the
1402  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1403  * fields.
1404  **/
1405 void
1406 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1407 		      uint32_t ulpstatus, uint32_t ulpWord4)
1408 {
1409 	struct lpfc_iocbq *piocb;
1410 
1411 	while (!list_empty(iocblist)) {
1412 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1413 		if (!piocb->iocb_cmpl) {
1414 			if (piocb->iocb_flag & LPFC_IO_NVME)
1415 				lpfc_nvme_cancel_iocb(phba, piocb);
1416 			else
1417 				lpfc_sli_release_iocbq(phba, piocb);
1418 		} else {
1419 			piocb->iocb.ulpStatus = ulpstatus;
1420 			piocb->iocb.un.ulpWord[4] = ulpWord4;
1421 			(piocb->iocb_cmpl) (phba, piocb, piocb);
1422 		}
1423 	}
1424 	return;
1425 }
1426 
1427 /**
1428  * lpfc_sli_iocb_cmd_type - Get the iocb type
1429  * @iocb_cmnd: iocb command code.
1430  *
1431  * This function is called by ring event handler function to get the iocb type.
1432  * This function translates the iocb command to an iocb command type used to
1433  * decide the final disposition of each completed IOCB.
1434  * The function returns
1435  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1436  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1437  * LPFC_ABORT_IOCB   if it is an abort iocb
1438  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1439  *
1440  * The caller is not required to hold any lock.
1441  **/
1442 static lpfc_iocb_type
1443 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1444 {
1445 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1446 
1447 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1448 		return 0;
1449 
1450 	switch (iocb_cmnd) {
1451 	case CMD_XMIT_SEQUENCE_CR:
1452 	case CMD_XMIT_SEQUENCE_CX:
1453 	case CMD_XMIT_BCAST_CN:
1454 	case CMD_XMIT_BCAST_CX:
1455 	case CMD_ELS_REQUEST_CR:
1456 	case CMD_ELS_REQUEST_CX:
1457 	case CMD_CREATE_XRI_CR:
1458 	case CMD_CREATE_XRI_CX:
1459 	case CMD_GET_RPI_CN:
1460 	case CMD_XMIT_ELS_RSP_CX:
1461 	case CMD_GET_RPI_CR:
1462 	case CMD_FCP_IWRITE_CR:
1463 	case CMD_FCP_IWRITE_CX:
1464 	case CMD_FCP_IREAD_CR:
1465 	case CMD_FCP_IREAD_CX:
1466 	case CMD_FCP_ICMND_CR:
1467 	case CMD_FCP_ICMND_CX:
1468 	case CMD_FCP_TSEND_CX:
1469 	case CMD_FCP_TRSP_CX:
1470 	case CMD_FCP_TRECEIVE_CX:
1471 	case CMD_FCP_AUTO_TRSP_CX:
1472 	case CMD_ADAPTER_MSG:
1473 	case CMD_ADAPTER_DUMP:
1474 	case CMD_XMIT_SEQUENCE64_CR:
1475 	case CMD_XMIT_SEQUENCE64_CX:
1476 	case CMD_XMIT_BCAST64_CN:
1477 	case CMD_XMIT_BCAST64_CX:
1478 	case CMD_ELS_REQUEST64_CR:
1479 	case CMD_ELS_REQUEST64_CX:
1480 	case CMD_FCP_IWRITE64_CR:
1481 	case CMD_FCP_IWRITE64_CX:
1482 	case CMD_FCP_IREAD64_CR:
1483 	case CMD_FCP_IREAD64_CX:
1484 	case CMD_FCP_ICMND64_CR:
1485 	case CMD_FCP_ICMND64_CX:
1486 	case CMD_FCP_TSEND64_CX:
1487 	case CMD_FCP_TRSP64_CX:
1488 	case CMD_FCP_TRECEIVE64_CX:
1489 	case CMD_GEN_REQUEST64_CR:
1490 	case CMD_GEN_REQUEST64_CX:
1491 	case CMD_XMIT_ELS_RSP64_CX:
1492 	case DSSCMD_IWRITE64_CR:
1493 	case DSSCMD_IWRITE64_CX:
1494 	case DSSCMD_IREAD64_CR:
1495 	case DSSCMD_IREAD64_CX:
1496 		type = LPFC_SOL_IOCB;
1497 		break;
1498 	case CMD_ABORT_XRI_CN:
1499 	case CMD_ABORT_XRI_CX:
1500 	case CMD_CLOSE_XRI_CN:
1501 	case CMD_CLOSE_XRI_CX:
1502 	case CMD_XRI_ABORTED_CX:
1503 	case CMD_ABORT_MXRI64_CN:
1504 	case CMD_XMIT_BLS_RSP64_CX:
1505 		type = LPFC_ABORT_IOCB;
1506 		break;
1507 	case CMD_RCV_SEQUENCE_CX:
1508 	case CMD_RCV_ELS_REQ_CX:
1509 	case CMD_RCV_SEQUENCE64_CX:
1510 	case CMD_RCV_ELS_REQ64_CX:
1511 	case CMD_ASYNC_STATUS:
1512 	case CMD_IOCB_RCV_SEQ64_CX:
1513 	case CMD_IOCB_RCV_ELS64_CX:
1514 	case CMD_IOCB_RCV_CONT64_CX:
1515 	case CMD_IOCB_RET_XRI64_CX:
1516 		type = LPFC_UNSOL_IOCB;
1517 		break;
1518 	case CMD_IOCB_XMIT_MSEQ64_CR:
1519 	case CMD_IOCB_XMIT_MSEQ64_CX:
1520 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1521 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1522 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1523 	case CMD_IOCB_ABORT_EXTENDED_CN:
1524 	case CMD_IOCB_RET_HBQE64_CN:
1525 	case CMD_IOCB_FCP_IBIDIR64_CR:
1526 	case CMD_IOCB_FCP_IBIDIR64_CX:
1527 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1528 	case CMD_IOCB_LOGENTRY_CN:
1529 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1530 		printk("%s - Unhandled SLI-3 Command x%x\n",
1531 				__func__, iocb_cmnd);
1532 		type = LPFC_UNKNOWN_IOCB;
1533 		break;
1534 	default:
1535 		type = LPFC_UNKNOWN_IOCB;
1536 		break;
1537 	}
1538 
1539 	return type;
1540 }
1541 
1542 /**
1543  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1544  * @phba: Pointer to HBA context object.
1545  *
1546  * This function is called from SLI initialization code
1547  * to configure every ring of the HBA's SLI interface. The
1548  * caller is not required to hold any lock. This function issues
1549  * a config_ring mailbox command for each ring.
1550  * This function returns zero if successful else returns a negative
1551  * error code.
1552  **/
1553 static int
1554 lpfc_sli_ring_map(struct lpfc_hba *phba)
1555 {
1556 	struct lpfc_sli *psli = &phba->sli;
1557 	LPFC_MBOXQ_t *pmb;
1558 	MAILBOX_t *pmbox;
1559 	int i, rc, ret = 0;
1560 
1561 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1562 	if (!pmb)
1563 		return -ENOMEM;
1564 	pmbox = &pmb->u.mb;
1565 	phba->link_state = LPFC_INIT_MBX_CMDS;
1566 	for (i = 0; i < psli->num_rings; i++) {
1567 		lpfc_config_ring(phba, i, pmb);
1568 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1569 		if (rc != MBX_SUCCESS) {
1570 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1571 					"0446 Adapter failed to init (%d), "
1572 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1573 					"ring %d\n",
1574 					rc, pmbox->mbxCommand,
1575 					pmbox->mbxStatus, i);
1576 			phba->link_state = LPFC_HBA_ERROR;
1577 			ret = -ENXIO;
1578 			break;
1579 		}
1580 	}
1581 	mempool_free(pmb, phba->mbox_mem_pool);
1582 	return ret;
1583 }
1584 
1585 /**
1586  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1587  * @phba: Pointer to HBA context object.
1588  * @pring: Pointer to driver SLI ring object.
1589  * @piocb: Pointer to the driver iocb object.
1590  *
1591  * The driver calls this function with the hbalock held for SLI3 ports or
1592  * the ring lock held for SLI4 ports. The function adds the
1593  * new iocb to txcmplq of the given ring. This function always returns
1594  * 0. If this function is called for ELS ring, this function checks if
1595  * there is a vport associated with the ELS command. This function also
1596  * starts els_tmofunc timer if this is an ELS command.
1597  **/
1598 static int
1599 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1600 			struct lpfc_iocbq *piocb)
1601 {
1602 	if (phba->sli_rev == LPFC_SLI_REV4)
1603 		lockdep_assert_held(&pring->ring_lock);
1604 	else
1605 		lockdep_assert_held(&phba->hbalock);
1606 
1607 	BUG_ON(!piocb);
1608 
1609 	list_add_tail(&piocb->list, &pring->txcmplq);
1610 	piocb->iocb_flag |= LPFC_IO_ON_TXCMPLQ;
1611 	pring->txcmplq_cnt++;
1612 
1613 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1614 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
1615 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
1616 		BUG_ON(!piocb->vport);
1617 		if (!(piocb->vport->load_flag & FC_UNLOADING))
1618 			mod_timer(&piocb->vport->els_tmofunc,
1619 				  jiffies +
1620 				  msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1621 	}
1622 
1623 	return 0;
1624 }
1625 
1626 /**
1627  * lpfc_sli_ringtx_get - Get first element of the txq
1628  * @phba: Pointer to HBA context object.
1629  * @pring: Pointer to driver SLI ring object.
1630  *
1631  * This function is called with hbalock held to get next
1632  * iocb in txq of the given ring. If there is any iocb in
1633  * the txq, the function returns first iocb in the list after
1634  * removing the iocb from the list, else it returns NULL.
1635  **/
1636 struct lpfc_iocbq *
1637 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1638 {
1639 	struct lpfc_iocbq *cmd_iocb;
1640 
1641 	lockdep_assert_held(&phba->hbalock);
1642 
1643 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1644 	return cmd_iocb;
1645 }
1646 
1647 /**
1648  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
1649  * @phba: Pointer to HBA context object.
1650  * @pring: Pointer to driver SLI ring object.
1651  *
1652  * This function is called with hbalock held and the caller must post the
1653  * iocb without releasing the lock. If the caller releases the lock,
1654  * iocb slot returned by the function is not guaranteed to be available.
1655  * The function returns pointer to the next available iocb slot if there
1656  * is available slot in the ring, else it returns NULL.
1657  * If the get index of the ring is ahead of the put index, the function
1658  * will post an error attention event to the worker thread to take the
1659  * HBA to offline state.
1660  **/
1661 static IOCB_t *
1662 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1663 {
1664 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
1665 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
1666 
1667 	lockdep_assert_held(&phba->hbalock);
1668 
1669 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
1670 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
1671 		pring->sli.sli3.next_cmdidx = 0;
1672 
1673 	if (unlikely(pring->sli.sli3.local_getidx ==
1674 		pring->sli.sli3.next_cmdidx)) {
1675 
1676 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
1677 
1678 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
1679 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1680 					"0315 Ring %d issue: portCmdGet %d "
1681 					"is bigger than cmd ring %d\n",
1682 					pring->ringno,
1683 					pring->sli.sli3.local_getidx,
1684 					max_cmd_idx);
1685 
1686 			phba->link_state = LPFC_HBA_ERROR;
1687 			/*
1688 			 * All error attention handlers are posted to
1689 			 * worker thread
1690 			 */
1691 			phba->work_ha |= HA_ERATT;
1692 			phba->work_hs = HS_FFER3;
1693 
1694 			lpfc_worker_wake_up(phba);
1695 
1696 			return NULL;
1697 		}
1698 
1699 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
1700 			return NULL;
1701 	}
1702 
1703 	return lpfc_cmd_iocb(phba, pring);
1704 }
1705 
1706 /**
1707  * lpfc_sli_next_iotag - Get an iotag for the iocb
1708  * @phba: Pointer to HBA context object.
1709  * @iocbq: Pointer to driver iocb object.
1710  *
1711  * This function gets an iotag for the iocb. If there is no unused iotag and
1712  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
1713  * array and assigns a new iotag.
1714  * The function returns the allocated iotag if successful, else returns zero.
1715  * Zero is not a valid iotag.
1716  * The caller is not required to hold any lock.
1717  **/
1718 uint16_t
1719 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1720 {
1721 	struct lpfc_iocbq **new_arr;
1722 	struct lpfc_iocbq **old_arr;
1723 	size_t new_len;
1724 	struct lpfc_sli *psli = &phba->sli;
1725 	uint16_t iotag;
1726 
1727 	spin_lock_irq(&phba->hbalock);
1728 	iotag = psli->last_iotag;
1729 	if(++iotag < psli->iocbq_lookup_len) {
1730 		psli->last_iotag = iotag;
1731 		psli->iocbq_lookup[iotag] = iocbq;
1732 		spin_unlock_irq(&phba->hbalock);
1733 		iocbq->iotag = iotag;
1734 		return iotag;
1735 	} else if (psli->iocbq_lookup_len < (0xffff
1736 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
1737 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
1738 		spin_unlock_irq(&phba->hbalock);
1739 		new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
1740 				  GFP_KERNEL);
1741 		if (new_arr) {
1742 			spin_lock_irq(&phba->hbalock);
1743 			old_arr = psli->iocbq_lookup;
1744 			if (new_len <= psli->iocbq_lookup_len) {
1745 				/* highly unprobable case */
1746 				kfree(new_arr);
1747 				iotag = psli->last_iotag;
1748 				if(++iotag < psli->iocbq_lookup_len) {
1749 					psli->last_iotag = iotag;
1750 					psli->iocbq_lookup[iotag] = iocbq;
1751 					spin_unlock_irq(&phba->hbalock);
1752 					iocbq->iotag = iotag;
1753 					return iotag;
1754 				}
1755 				spin_unlock_irq(&phba->hbalock);
1756 				return 0;
1757 			}
1758 			if (psli->iocbq_lookup)
1759 				memcpy(new_arr, old_arr,
1760 				       ((psli->last_iotag  + 1) *
1761 					sizeof (struct lpfc_iocbq *)));
1762 			psli->iocbq_lookup = new_arr;
1763 			psli->iocbq_lookup_len = new_len;
1764 			psli->last_iotag = iotag;
1765 			psli->iocbq_lookup[iotag] = iocbq;
1766 			spin_unlock_irq(&phba->hbalock);
1767 			iocbq->iotag = iotag;
1768 			kfree(old_arr);
1769 			return iotag;
1770 		}
1771 	} else
1772 		spin_unlock_irq(&phba->hbalock);
1773 
1774 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
1775 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
1776 			psli->last_iotag);
1777 
1778 	return 0;
1779 }
1780 
1781 /**
1782  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
1783  * @phba: Pointer to HBA context object.
1784  * @pring: Pointer to driver SLI ring object.
1785  * @iocb: Pointer to iocb slot in the ring.
1786  * @nextiocb: Pointer to driver iocb object which need to be
1787  *            posted to firmware.
1788  *
1789  * This function is called with hbalock held to post a new iocb to
1790  * the firmware. This function copies the new iocb to ring iocb slot and
1791  * updates the ring pointers. It adds the new iocb to txcmplq if there is
1792  * a completion call back for this iocb else the function will free the
1793  * iocb object.
1794  **/
1795 static void
1796 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1797 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
1798 {
1799 	lockdep_assert_held(&phba->hbalock);
1800 	/*
1801 	 * Set up an iotag
1802 	 */
1803 	nextiocb->iocb.ulpIoTag = (nextiocb->iocb_cmpl) ? nextiocb->iotag : 0;
1804 
1805 
1806 	if (pring->ringno == LPFC_ELS_RING) {
1807 		lpfc_debugfs_slow_ring_trc(phba,
1808 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
1809 			*(((uint32_t *) &nextiocb->iocb) + 4),
1810 			*(((uint32_t *) &nextiocb->iocb) + 6),
1811 			*(((uint32_t *) &nextiocb->iocb) + 7));
1812 	}
1813 
1814 	/*
1815 	 * Issue iocb command to adapter
1816 	 */
1817 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
1818 	wmb();
1819 	pring->stats.iocb_cmd++;
1820 
1821 	/*
1822 	 * If there is no completion routine to call, we can release the
1823 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
1824 	 * that have no rsp ring completion, iocb_cmpl MUST be NULL.
1825 	 */
1826 	if (nextiocb->iocb_cmpl)
1827 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
1828 	else
1829 		__lpfc_sli_release_iocbq(phba, nextiocb);
1830 
1831 	/*
1832 	 * Let the HBA know what IOCB slot will be the next one the
1833 	 * driver will put a command into.
1834 	 */
1835 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
1836 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
1837 }
1838 
1839 /**
1840  * lpfc_sli_update_full_ring - Update the chip attention register
1841  * @phba: Pointer to HBA context object.
1842  * @pring: Pointer to driver SLI ring object.
1843  *
1844  * The caller is not required to hold any lock for calling this function.
1845  * This function updates the chip attention bits for the ring to inform firmware
1846  * that there are pending work to be done for this ring and requests an
1847  * interrupt when there is space available in the ring. This function is
1848  * called when the driver is unable to post more iocbs to the ring due
1849  * to unavailability of space in the ring.
1850  **/
1851 static void
1852 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1853 {
1854 	int ringno = pring->ringno;
1855 
1856 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
1857 
1858 	wmb();
1859 
1860 	/*
1861 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
1862 	 * The HBA will tell us when an IOCB entry is available.
1863 	 */
1864 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
1865 	readl(phba->CAregaddr); /* flush */
1866 
1867 	pring->stats.iocb_cmd_full++;
1868 }
1869 
1870 /**
1871  * lpfc_sli_update_ring - Update chip attention register
1872  * @phba: Pointer to HBA context object.
1873  * @pring: Pointer to driver SLI ring object.
1874  *
1875  * This function updates the chip attention register bit for the
1876  * given ring to inform HBA that there is more work to be done
1877  * in this ring. The caller is not required to hold any lock.
1878  **/
1879 static void
1880 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1881 {
1882 	int ringno = pring->ringno;
1883 
1884 	/*
1885 	 * Tell the HBA that there is work to do in this ring.
1886 	 */
1887 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
1888 		wmb();
1889 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
1890 		readl(phba->CAregaddr); /* flush */
1891 	}
1892 }
1893 
1894 /**
1895  * lpfc_sli_resume_iocb - Process iocbs in the txq
1896  * @phba: Pointer to HBA context object.
1897  * @pring: Pointer to driver SLI ring object.
1898  *
1899  * This function is called with hbalock held to post pending iocbs
1900  * in the txq to the firmware. This function is called when driver
1901  * detects space available in the ring.
1902  **/
1903 static void
1904 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1905 {
1906 	IOCB_t *iocb;
1907 	struct lpfc_iocbq *nextiocb;
1908 
1909 	lockdep_assert_held(&phba->hbalock);
1910 
1911 	/*
1912 	 * Check to see if:
1913 	 *  (a) there is anything on the txq to send
1914 	 *  (b) link is up
1915 	 *  (c) link attention events can be processed (fcp ring only)
1916 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
1917 	 */
1918 
1919 	if (lpfc_is_link_up(phba) &&
1920 	    (!list_empty(&pring->txq)) &&
1921 	    (pring->ringno != LPFC_FCP_RING ||
1922 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
1923 
1924 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
1925 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
1926 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
1927 
1928 		if (iocb)
1929 			lpfc_sli_update_ring(phba, pring);
1930 		else
1931 			lpfc_sli_update_full_ring(phba, pring);
1932 	}
1933 
1934 	return;
1935 }
1936 
1937 /**
1938  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
1939  * @phba: Pointer to HBA context object.
1940  * @hbqno: HBQ number.
1941  *
1942  * This function is called with hbalock held to get the next
1943  * available slot for the given HBQ. If there is free slot
1944  * available for the HBQ it will return pointer to the next available
1945  * HBQ entry else it will return NULL.
1946  **/
1947 static struct lpfc_hbq_entry *
1948 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
1949 {
1950 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
1951 
1952 	lockdep_assert_held(&phba->hbalock);
1953 
1954 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
1955 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
1956 		hbqp->next_hbqPutIdx = 0;
1957 
1958 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
1959 		uint32_t raw_index = phba->hbq_get[hbqno];
1960 		uint32_t getidx = le32_to_cpu(raw_index);
1961 
1962 		hbqp->local_hbqGetIdx = getidx;
1963 
1964 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
1965 			lpfc_printf_log(phba, KERN_ERR,
1966 					LOG_SLI | LOG_VPORT,
1967 					"1802 HBQ %d: local_hbqGetIdx "
1968 					"%u is > than hbqp->entry_count %u\n",
1969 					hbqno, hbqp->local_hbqGetIdx,
1970 					hbqp->entry_count);
1971 
1972 			phba->link_state = LPFC_HBA_ERROR;
1973 			return NULL;
1974 		}
1975 
1976 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
1977 			return NULL;
1978 	}
1979 
1980 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
1981 			hbqp->hbqPutIdx;
1982 }
1983 
1984 /**
1985  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
1986  * @phba: Pointer to HBA context object.
1987  *
1988  * This function is called with no lock held to free all the
1989  * hbq buffers while uninitializing the SLI interface. It also
1990  * frees the HBQ buffers returned by the firmware but not yet
1991  * processed by the upper layers.
1992  **/
1993 void
1994 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
1995 {
1996 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
1997 	struct hbq_dmabuf *hbq_buf;
1998 	unsigned long flags;
1999 	int i, hbq_count;
2000 
2001 	hbq_count = lpfc_sli_hbq_count();
2002 	/* Return all memory used by all HBQs */
2003 	spin_lock_irqsave(&phba->hbalock, flags);
2004 	for (i = 0; i < hbq_count; ++i) {
2005 		list_for_each_entry_safe(dmabuf, next_dmabuf,
2006 				&phba->hbqs[i].hbq_buffer_list, list) {
2007 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2008 			list_del(&hbq_buf->dbuf.list);
2009 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2010 		}
2011 		phba->hbqs[i].buffer_count = 0;
2012 	}
2013 
2014 	/* Mark the HBQs not in use */
2015 	phba->hbq_in_use = 0;
2016 	spin_unlock_irqrestore(&phba->hbalock, flags);
2017 }
2018 
2019 /**
2020  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2021  * @phba: Pointer to HBA context object.
2022  * @hbqno: HBQ number.
2023  * @hbq_buf: Pointer to HBQ buffer.
2024  *
2025  * This function is called with the hbalock held to post a
2026  * hbq buffer to the firmware. If the function finds an empty
2027  * slot in the HBQ, it will post the buffer. The function will return
2028  * pointer to the hbq entry if it successfully post the buffer
2029  * else it will return NULL.
2030  **/
2031 static int
2032 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2033 			 struct hbq_dmabuf *hbq_buf)
2034 {
2035 	lockdep_assert_held(&phba->hbalock);
2036 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2037 }
2038 
2039 /**
2040  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2041  * @phba: Pointer to HBA context object.
2042  * @hbqno: HBQ number.
2043  * @hbq_buf: Pointer to HBQ buffer.
2044  *
2045  * This function is called with the hbalock held to post a hbq buffer to the
2046  * firmware. If the function finds an empty slot in the HBQ, it will post the
2047  * buffer and place it on the hbq_buffer_list. The function will return zero if
2048  * it successfully post the buffer else it will return an error.
2049  **/
2050 static int
2051 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2052 			    struct hbq_dmabuf *hbq_buf)
2053 {
2054 	struct lpfc_hbq_entry *hbqe;
2055 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
2056 
2057 	lockdep_assert_held(&phba->hbalock);
2058 	/* Get next HBQ entry slot to use */
2059 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2060 	if (hbqe) {
2061 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
2062 
2063 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2064 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2065 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2066 		hbqe->bde.tus.f.bdeFlags = 0;
2067 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2068 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2069 				/* Sync SLIM */
2070 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2071 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2072 				/* flush */
2073 		readl(phba->hbq_put + hbqno);
2074 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2075 		return 0;
2076 	} else
2077 		return -ENOMEM;
2078 }
2079 
2080 /**
2081  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2082  * @phba: Pointer to HBA context object.
2083  * @hbqno: HBQ number.
2084  * @hbq_buf: Pointer to HBQ buffer.
2085  *
2086  * This function is called with the hbalock held to post an RQE to the SLI4
2087  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2088  * the hbq_buffer_list and return zero, otherwise it will return an error.
2089  **/
2090 static int
2091 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2092 			    struct hbq_dmabuf *hbq_buf)
2093 {
2094 	int rc;
2095 	struct lpfc_rqe hrqe;
2096 	struct lpfc_rqe drqe;
2097 	struct lpfc_queue *hrq;
2098 	struct lpfc_queue *drq;
2099 
2100 	if (hbqno != LPFC_ELS_HBQ)
2101 		return 1;
2102 	hrq = phba->sli4_hba.hdr_rq;
2103 	drq = phba->sli4_hba.dat_rq;
2104 
2105 	lockdep_assert_held(&phba->hbalock);
2106 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2107 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2108 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2109 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2110 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2111 	if (rc < 0)
2112 		return rc;
2113 	hbq_buf->tag = (rc | (hbqno << 16));
2114 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2115 	return 0;
2116 }
2117 
2118 /* HBQ for ELS and CT traffic. */
2119 static struct lpfc_hbq_init lpfc_els_hbq = {
2120 	.rn = 1,
2121 	.entry_count = 256,
2122 	.mask_count = 0,
2123 	.profile = 0,
2124 	.ring_mask = (1 << LPFC_ELS_RING),
2125 	.buffer_count = 0,
2126 	.init_count = 40,
2127 	.add_count = 40,
2128 };
2129 
2130 /* Array of HBQs */
2131 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2132 	&lpfc_els_hbq,
2133 };
2134 
2135 /**
2136  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2137  * @phba: Pointer to HBA context object.
2138  * @hbqno: HBQ number.
2139  * @count: Number of HBQ buffers to be posted.
2140  *
2141  * This function is called with no lock held to post more hbq buffers to the
2142  * given HBQ. The function returns the number of HBQ buffers successfully
2143  * posted.
2144  **/
2145 static int
2146 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2147 {
2148 	uint32_t i, posted = 0;
2149 	unsigned long flags;
2150 	struct hbq_dmabuf *hbq_buffer;
2151 	LIST_HEAD(hbq_buf_list);
2152 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2153 		return 0;
2154 
2155 	if ((phba->hbqs[hbqno].buffer_count + count) >
2156 	    lpfc_hbq_defs[hbqno]->entry_count)
2157 		count = lpfc_hbq_defs[hbqno]->entry_count -
2158 					phba->hbqs[hbqno].buffer_count;
2159 	if (!count)
2160 		return 0;
2161 	/* Allocate HBQ entries */
2162 	for (i = 0; i < count; i++) {
2163 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2164 		if (!hbq_buffer)
2165 			break;
2166 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2167 	}
2168 	/* Check whether HBQ is still in use */
2169 	spin_lock_irqsave(&phba->hbalock, flags);
2170 	if (!phba->hbq_in_use)
2171 		goto err;
2172 	while (!list_empty(&hbq_buf_list)) {
2173 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2174 				 dbuf.list);
2175 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2176 				      (hbqno << 16));
2177 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2178 			phba->hbqs[hbqno].buffer_count++;
2179 			posted++;
2180 		} else
2181 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2182 	}
2183 	spin_unlock_irqrestore(&phba->hbalock, flags);
2184 	return posted;
2185 err:
2186 	spin_unlock_irqrestore(&phba->hbalock, flags);
2187 	while (!list_empty(&hbq_buf_list)) {
2188 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2189 				 dbuf.list);
2190 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2191 	}
2192 	return 0;
2193 }
2194 
2195 /**
2196  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2197  * @phba: Pointer to HBA context object.
2198  * @qno: HBQ number.
2199  *
2200  * This function posts more buffers to the HBQ. This function
2201  * is called with no lock held. The function returns the number of HBQ entries
2202  * successfully allocated.
2203  **/
2204 int
2205 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2206 {
2207 	if (phba->sli_rev == LPFC_SLI_REV4)
2208 		return 0;
2209 	else
2210 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2211 					 lpfc_hbq_defs[qno]->add_count);
2212 }
2213 
2214 /**
2215  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2216  * @phba: Pointer to HBA context object.
2217  * @qno:  HBQ queue number.
2218  *
2219  * This function is called from SLI initialization code path with
2220  * no lock held to post initial HBQ buffers to firmware. The
2221  * function returns the number of HBQ entries successfully allocated.
2222  **/
2223 static int
2224 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2225 {
2226 	if (phba->sli_rev == LPFC_SLI_REV4)
2227 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2228 					lpfc_hbq_defs[qno]->entry_count);
2229 	else
2230 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2231 					 lpfc_hbq_defs[qno]->init_count);
2232 }
2233 
2234 /**
2235  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2236  * @phba: Pointer to HBA context object.
2237  * @hbqno: HBQ number.
2238  *
2239  * This function removes the first hbq buffer on an hbq list and returns a
2240  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2241  **/
2242 static struct hbq_dmabuf *
2243 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2244 {
2245 	struct lpfc_dmabuf *d_buf;
2246 
2247 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2248 	if (!d_buf)
2249 		return NULL;
2250 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2251 }
2252 
2253 /**
2254  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2255  * @phba: Pointer to HBA context object.
2256  * @hbqno: HBQ number.
2257  *
2258  * This function removes the first RQ buffer on an RQ buffer list and returns a
2259  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2260  **/
2261 static struct rqb_dmabuf *
2262 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2263 {
2264 	struct lpfc_dmabuf *h_buf;
2265 	struct lpfc_rqb *rqbp;
2266 
2267 	rqbp = hrq->rqbp;
2268 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2269 			 struct lpfc_dmabuf, list);
2270 	if (!h_buf)
2271 		return NULL;
2272 	rqbp->buffer_count--;
2273 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2274 }
2275 
2276 /**
2277  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2278  * @phba: Pointer to HBA context object.
2279  * @tag: Tag of the hbq buffer.
2280  *
2281  * This function searches for the hbq buffer associated with the given tag in
2282  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2283  * otherwise it returns NULL.
2284  **/
2285 static struct hbq_dmabuf *
2286 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2287 {
2288 	struct lpfc_dmabuf *d_buf;
2289 	struct hbq_dmabuf *hbq_buf;
2290 	uint32_t hbqno;
2291 
2292 	hbqno = tag >> 16;
2293 	if (hbqno >= LPFC_MAX_HBQS)
2294 		return NULL;
2295 
2296 	spin_lock_irq(&phba->hbalock);
2297 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2298 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2299 		if (hbq_buf->tag == tag) {
2300 			spin_unlock_irq(&phba->hbalock);
2301 			return hbq_buf;
2302 		}
2303 	}
2304 	spin_unlock_irq(&phba->hbalock);
2305 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_VPORT,
2306 			"1803 Bad hbq tag. Data: x%x x%x\n",
2307 			tag, phba->hbqs[tag >> 16].buffer_count);
2308 	return NULL;
2309 }
2310 
2311 /**
2312  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2313  * @phba: Pointer to HBA context object.
2314  * @hbq_buffer: Pointer to HBQ buffer.
2315  *
2316  * This function is called with hbalock. This function gives back
2317  * the hbq buffer to firmware. If the HBQ does not have space to
2318  * post the buffer, it will free the buffer.
2319  **/
2320 void
2321 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2322 {
2323 	uint32_t hbqno;
2324 
2325 	if (hbq_buffer) {
2326 		hbqno = hbq_buffer->tag >> 16;
2327 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2328 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2329 	}
2330 }
2331 
2332 /**
2333  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2334  * @mbxCommand: mailbox command code.
2335  *
2336  * This function is called by the mailbox event handler function to verify
2337  * that the completed mailbox command is a legitimate mailbox command. If the
2338  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2339  * and the mailbox event handler will take the HBA offline.
2340  **/
2341 static int
2342 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2343 {
2344 	uint8_t ret;
2345 
2346 	switch (mbxCommand) {
2347 	case MBX_LOAD_SM:
2348 	case MBX_READ_NV:
2349 	case MBX_WRITE_NV:
2350 	case MBX_WRITE_VPARMS:
2351 	case MBX_RUN_BIU_DIAG:
2352 	case MBX_INIT_LINK:
2353 	case MBX_DOWN_LINK:
2354 	case MBX_CONFIG_LINK:
2355 	case MBX_CONFIG_RING:
2356 	case MBX_RESET_RING:
2357 	case MBX_READ_CONFIG:
2358 	case MBX_READ_RCONFIG:
2359 	case MBX_READ_SPARM:
2360 	case MBX_READ_STATUS:
2361 	case MBX_READ_RPI:
2362 	case MBX_READ_XRI:
2363 	case MBX_READ_REV:
2364 	case MBX_READ_LNK_STAT:
2365 	case MBX_REG_LOGIN:
2366 	case MBX_UNREG_LOGIN:
2367 	case MBX_CLEAR_LA:
2368 	case MBX_DUMP_MEMORY:
2369 	case MBX_DUMP_CONTEXT:
2370 	case MBX_RUN_DIAGS:
2371 	case MBX_RESTART:
2372 	case MBX_UPDATE_CFG:
2373 	case MBX_DOWN_LOAD:
2374 	case MBX_DEL_LD_ENTRY:
2375 	case MBX_RUN_PROGRAM:
2376 	case MBX_SET_MASK:
2377 	case MBX_SET_VARIABLE:
2378 	case MBX_UNREG_D_ID:
2379 	case MBX_KILL_BOARD:
2380 	case MBX_CONFIG_FARP:
2381 	case MBX_BEACON:
2382 	case MBX_LOAD_AREA:
2383 	case MBX_RUN_BIU_DIAG64:
2384 	case MBX_CONFIG_PORT:
2385 	case MBX_READ_SPARM64:
2386 	case MBX_READ_RPI64:
2387 	case MBX_REG_LOGIN64:
2388 	case MBX_READ_TOPOLOGY:
2389 	case MBX_WRITE_WWN:
2390 	case MBX_SET_DEBUG:
2391 	case MBX_LOAD_EXP_ROM:
2392 	case MBX_ASYNCEVT_ENABLE:
2393 	case MBX_REG_VPI:
2394 	case MBX_UNREG_VPI:
2395 	case MBX_HEARTBEAT:
2396 	case MBX_PORT_CAPABILITIES:
2397 	case MBX_PORT_IOV_CONTROL:
2398 	case MBX_SLI4_CONFIG:
2399 	case MBX_SLI4_REQ_FTRS:
2400 	case MBX_REG_FCFI:
2401 	case MBX_UNREG_FCFI:
2402 	case MBX_REG_VFI:
2403 	case MBX_UNREG_VFI:
2404 	case MBX_INIT_VPI:
2405 	case MBX_INIT_VFI:
2406 	case MBX_RESUME_RPI:
2407 	case MBX_READ_EVENT_LOG_STATUS:
2408 	case MBX_READ_EVENT_LOG:
2409 	case MBX_SECURITY_MGMT:
2410 	case MBX_AUTH_PORT:
2411 	case MBX_ACCESS_VDATA:
2412 		ret = mbxCommand;
2413 		break;
2414 	default:
2415 		ret = MBX_SHUTDOWN;
2416 		break;
2417 	}
2418 	return ret;
2419 }
2420 
2421 /**
2422  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2423  * @phba: Pointer to HBA context object.
2424  * @pmboxq: Pointer to mailbox command.
2425  *
2426  * This is completion handler function for mailbox commands issued from
2427  * lpfc_sli_issue_mbox_wait function. This function is called by the
2428  * mailbox event handler function with no lock held. This function
2429  * will wake up thread waiting on the wait queue pointed by context1
2430  * of the mailbox.
2431  **/
2432 void
2433 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2434 {
2435 	unsigned long drvr_flag;
2436 	struct completion *pmbox_done;
2437 
2438 	/*
2439 	 * If pmbox_done is empty, the driver thread gave up waiting and
2440 	 * continued running.
2441 	 */
2442 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2443 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2444 	pmbox_done = (struct completion *)pmboxq->context3;
2445 	if (pmbox_done)
2446 		complete(pmbox_done);
2447 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2448 	return;
2449 }
2450 
2451 static void
2452 __lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2453 {
2454 	unsigned long iflags;
2455 
2456 	if (ndlp->nlp_flag & NLP_RELEASE_RPI) {
2457 		lpfc_sli4_free_rpi(vport->phba, ndlp->nlp_rpi);
2458 		spin_lock_irqsave(&vport->phba->ndlp_lock, iflags);
2459 		ndlp->nlp_flag &= ~NLP_RELEASE_RPI;
2460 		ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
2461 		spin_unlock_irqrestore(&vport->phba->ndlp_lock, iflags);
2462 	}
2463 	ndlp->nlp_flag &= ~NLP_UNREG_INP;
2464 }
2465 
2466 /**
2467  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2468  * @phba: Pointer to HBA context object.
2469  * @pmb: Pointer to mailbox object.
2470  *
2471  * This function is the default mailbox completion handler. It
2472  * frees the memory resources associated with the completed mailbox
2473  * command. If the completed command is a REG_LOGIN mailbox command,
2474  * this function will issue a UREG_LOGIN to re-claim the RPI.
2475  **/
2476 void
2477 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2478 {
2479 	struct lpfc_vport  *vport = pmb->vport;
2480 	struct lpfc_dmabuf *mp;
2481 	struct lpfc_nodelist *ndlp;
2482 	struct Scsi_Host *shost;
2483 	uint16_t rpi, vpi;
2484 	int rc;
2485 
2486 	mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
2487 
2488 	if (mp) {
2489 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
2490 		kfree(mp);
2491 	}
2492 
2493 	/*
2494 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2495 	 * is in re-discovery driver need to cleanup the RPI.
2496 	 */
2497 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2498 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2499 	    !pmb->u.mb.mbxStatus) {
2500 		rpi = pmb->u.mb.un.varWords[0];
2501 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2502 		if (phba->sli_rev == LPFC_SLI_REV4)
2503 			vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2504 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2505 		pmb->vport = vport;
2506 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2507 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2508 		if (rc != MBX_NOT_FINISHED)
2509 			return;
2510 	}
2511 
2512 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2513 		!(phba->pport->load_flag & FC_UNLOADING) &&
2514 		!pmb->u.mb.mbxStatus) {
2515 		shost = lpfc_shost_from_vport(vport);
2516 		spin_lock_irq(shost->host_lock);
2517 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2518 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2519 		spin_unlock_irq(shost->host_lock);
2520 	}
2521 
2522 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2523 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2524 		lpfc_nlp_put(ndlp);
2525 		pmb->ctx_buf = NULL;
2526 		pmb->ctx_ndlp = NULL;
2527 	}
2528 
2529 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2530 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2531 
2532 		/* Check to see if there are any deferred events to process */
2533 		if (ndlp) {
2534 			lpfc_printf_vlog(
2535 				vport,
2536 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2537 				"1438 UNREG cmpl deferred mbox x%x "
2538 				"on NPort x%x Data: x%x x%x %px\n",
2539 				ndlp->nlp_rpi, ndlp->nlp_DID,
2540 				ndlp->nlp_flag, ndlp->nlp_defer_did, ndlp);
2541 
2542 			if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2543 			    (ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING)) {
2544 				ndlp->nlp_flag &= ~NLP_UNREG_INP;
2545 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2546 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2547 			} else {
2548 				__lpfc_sli_rpi_release(vport, ndlp);
2549 			}
2550 			if (vport->load_flag & FC_UNLOADING)
2551 				lpfc_nlp_put(ndlp);
2552 			pmb->ctx_ndlp = NULL;
2553 		}
2554 	}
2555 
2556 	/* Check security permission status on INIT_LINK mailbox command */
2557 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2558 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2559 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2560 				"2860 SLI authentication is required "
2561 				"for INIT_LINK but has not done yet\n");
2562 
2563 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2564 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2565 	else
2566 		mempool_free(pmb, phba->mbox_mem_pool);
2567 }
2568  /**
2569  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2570  * @phba: Pointer to HBA context object.
2571  * @pmb: Pointer to mailbox object.
2572  *
2573  * This function is the unreg rpi mailbox completion handler. It
2574  * frees the memory resources associated with the completed mailbox
2575  * command. An additional refrenece is put on the ndlp to prevent
2576  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2577  * the unreg mailbox command completes, this routine puts the
2578  * reference back.
2579  *
2580  **/
2581 void
2582 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2583 {
2584 	struct lpfc_vport  *vport = pmb->vport;
2585 	struct lpfc_nodelist *ndlp;
2586 
2587 	ndlp = pmb->ctx_ndlp;
2588 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2589 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2590 		    (bf_get(lpfc_sli_intf_if_type,
2591 		     &phba->sli4_hba.sli_intf) >=
2592 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2593 			if (ndlp) {
2594 				lpfc_printf_vlog(
2595 					vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2596 					 "0010 UNREG_LOGIN vpi:%x "
2597 					 "rpi:%x DID:%x defer x%x flg x%x "
2598 					 "map:%x %px\n",
2599 					 vport->vpi, ndlp->nlp_rpi,
2600 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
2601 					 ndlp->nlp_flag,
2602 					 ndlp->nlp_usg_map, ndlp);
2603 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2604 				lpfc_nlp_put(ndlp);
2605 
2606 				/* Check to see if there are any deferred
2607 				 * events to process
2608 				 */
2609 				if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2610 				    (ndlp->nlp_defer_did !=
2611 				    NLP_EVT_NOTHING_PENDING)) {
2612 					lpfc_printf_vlog(
2613 						vport, KERN_INFO, LOG_DISCOVERY,
2614 						"4111 UNREG cmpl deferred "
2615 						"clr x%x on "
2616 						"NPort x%x Data: x%x x%px\n",
2617 						ndlp->nlp_rpi, ndlp->nlp_DID,
2618 						ndlp->nlp_defer_did, ndlp);
2619 					ndlp->nlp_flag &= ~NLP_UNREG_INP;
2620 					ndlp->nlp_defer_did =
2621 						NLP_EVT_NOTHING_PENDING;
2622 					lpfc_issue_els_plogi(
2623 						vport, ndlp->nlp_DID, 0);
2624 				} else {
2625 					__lpfc_sli_rpi_release(vport, ndlp);
2626 				}
2627 			}
2628 		}
2629 	}
2630 
2631 	mempool_free(pmb, phba->mbox_mem_pool);
2632 }
2633 
2634 /**
2635  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
2636  * @phba: Pointer to HBA context object.
2637  *
2638  * This function is called with no lock held. This function processes all
2639  * the completed mailbox commands and gives it to upper layers. The interrupt
2640  * service routine processes mailbox completion interrupt and adds completed
2641  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
2642  * Worker thread call lpfc_sli_handle_mb_event, which will return the
2643  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
2644  * function returns the mailbox commands to the upper layer by calling the
2645  * completion handler function of each mailbox.
2646  **/
2647 int
2648 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
2649 {
2650 	MAILBOX_t *pmbox;
2651 	LPFC_MBOXQ_t *pmb;
2652 	int rc;
2653 	LIST_HEAD(cmplq);
2654 
2655 	phba->sli.slistat.mbox_event++;
2656 
2657 	/* Get all completed mailboxe buffers into the cmplq */
2658 	spin_lock_irq(&phba->hbalock);
2659 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
2660 	spin_unlock_irq(&phba->hbalock);
2661 
2662 	/* Get a Mailbox buffer to setup mailbox commands for callback */
2663 	do {
2664 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
2665 		if (pmb == NULL)
2666 			break;
2667 
2668 		pmbox = &pmb->u.mb;
2669 
2670 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
2671 			if (pmb->vport) {
2672 				lpfc_debugfs_disc_trc(pmb->vport,
2673 					LPFC_DISC_TRC_MBOX_VPORT,
2674 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
2675 					(uint32_t)pmbox->mbxCommand,
2676 					pmbox->un.varWords[0],
2677 					pmbox->un.varWords[1]);
2678 			}
2679 			else {
2680 				lpfc_debugfs_disc_trc(phba->pport,
2681 					LPFC_DISC_TRC_MBOX,
2682 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
2683 					(uint32_t)pmbox->mbxCommand,
2684 					pmbox->un.varWords[0],
2685 					pmbox->un.varWords[1]);
2686 			}
2687 		}
2688 
2689 		/*
2690 		 * It is a fatal error if unknown mbox command completion.
2691 		 */
2692 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
2693 		    MBX_SHUTDOWN) {
2694 			/* Unknown mailbox command compl */
2695 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2696 					"(%d):0323 Unknown Mailbox command "
2697 					"x%x (x%x/x%x) Cmpl\n",
2698 					pmb->vport ? pmb->vport->vpi :
2699 					LPFC_VPORT_UNKNOWN,
2700 					pmbox->mbxCommand,
2701 					lpfc_sli_config_mbox_subsys_get(phba,
2702 									pmb),
2703 					lpfc_sli_config_mbox_opcode_get(phba,
2704 									pmb));
2705 			phba->link_state = LPFC_HBA_ERROR;
2706 			phba->work_hs = HS_FFER3;
2707 			lpfc_handle_eratt(phba);
2708 			continue;
2709 		}
2710 
2711 		if (pmbox->mbxStatus) {
2712 			phba->sli.slistat.mbox_stat_err++;
2713 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
2714 				/* Mbox cmd cmpl error - RETRYing */
2715 				lpfc_printf_log(phba, KERN_INFO,
2716 					LOG_MBOX | LOG_SLI,
2717 					"(%d):0305 Mbox cmd cmpl "
2718 					"error - RETRYing Data: x%x "
2719 					"(x%x/x%x) x%x x%x x%x\n",
2720 					pmb->vport ? pmb->vport->vpi :
2721 					LPFC_VPORT_UNKNOWN,
2722 					pmbox->mbxCommand,
2723 					lpfc_sli_config_mbox_subsys_get(phba,
2724 									pmb),
2725 					lpfc_sli_config_mbox_opcode_get(phba,
2726 									pmb),
2727 					pmbox->mbxStatus,
2728 					pmbox->un.varWords[0],
2729 					pmb->vport ? pmb->vport->port_state :
2730 					LPFC_VPORT_UNKNOWN);
2731 				pmbox->mbxStatus = 0;
2732 				pmbox->mbxOwner = OWN_HOST;
2733 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2734 				if (rc != MBX_NOT_FINISHED)
2735 					continue;
2736 			}
2737 		}
2738 
2739 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
2740 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
2741 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
2742 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
2743 				"x%x x%x x%x\n",
2744 				pmb->vport ? pmb->vport->vpi : 0,
2745 				pmbox->mbxCommand,
2746 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
2747 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
2748 				pmb->mbox_cmpl,
2749 				*((uint32_t *) pmbox),
2750 				pmbox->un.varWords[0],
2751 				pmbox->un.varWords[1],
2752 				pmbox->un.varWords[2],
2753 				pmbox->un.varWords[3],
2754 				pmbox->un.varWords[4],
2755 				pmbox->un.varWords[5],
2756 				pmbox->un.varWords[6],
2757 				pmbox->un.varWords[7],
2758 				pmbox->un.varWords[8],
2759 				pmbox->un.varWords[9],
2760 				pmbox->un.varWords[10]);
2761 
2762 		if (pmb->mbox_cmpl)
2763 			pmb->mbox_cmpl(phba,pmb);
2764 	} while (1);
2765 	return 0;
2766 }
2767 
2768 /**
2769  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
2770  * @phba: Pointer to HBA context object.
2771  * @pring: Pointer to driver SLI ring object.
2772  * @tag: buffer tag.
2773  *
2774  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
2775  * is set in the tag the buffer is posted for a particular exchange,
2776  * the function will return the buffer without replacing the buffer.
2777  * If the buffer is for unsolicited ELS or CT traffic, this function
2778  * returns the buffer and also posts another buffer to the firmware.
2779  **/
2780 static struct lpfc_dmabuf *
2781 lpfc_sli_get_buff(struct lpfc_hba *phba,
2782 		  struct lpfc_sli_ring *pring,
2783 		  uint32_t tag)
2784 {
2785 	struct hbq_dmabuf *hbq_entry;
2786 
2787 	if (tag & QUE_BUFTAG_BIT)
2788 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
2789 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
2790 	if (!hbq_entry)
2791 		return NULL;
2792 	return &hbq_entry->dbuf;
2793 }
2794 
2795 /**
2796  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
2797  *                              containing a NVME LS request.
2798  * @phba: pointer to lpfc hba data structure.
2799  * @piocb: pointer to the iocbq struct representing the sequence starting
2800  *        frame.
2801  *
2802  * This routine initially validates the NVME LS, validates there is a login
2803  * with the port that sent the LS, and then calls the appropriate nvme host
2804  * or target LS request handler.
2805  **/
2806 static void
2807 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
2808 {
2809 	struct lpfc_nodelist *ndlp;
2810 	struct lpfc_dmabuf *d_buf;
2811 	struct hbq_dmabuf *nvmebuf;
2812 	struct fc_frame_header *fc_hdr;
2813 	struct lpfc_async_xchg_ctx *axchg = NULL;
2814 	char *failwhy = NULL;
2815 	uint32_t oxid, sid, did, fctl, size;
2816 	int ret = 1;
2817 
2818 	d_buf = piocb->context2;
2819 
2820 	nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2821 	fc_hdr = nvmebuf->hbuf.virt;
2822 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
2823 	sid = sli4_sid_from_fc_hdr(fc_hdr);
2824 	did = sli4_did_from_fc_hdr(fc_hdr);
2825 	fctl = (fc_hdr->fh_f_ctl[0] << 16 |
2826 		fc_hdr->fh_f_ctl[1] << 8 |
2827 		fc_hdr->fh_f_ctl[2]);
2828 	size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
2829 
2830 	lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
2831 			 oxid, size, sid);
2832 
2833 	if (phba->pport->load_flag & FC_UNLOADING) {
2834 		failwhy = "Driver Unloading";
2835 	} else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
2836 		failwhy = "NVME FC4 Disabled";
2837 	} else if (!phba->nvmet_support && !phba->pport->localport) {
2838 		failwhy = "No Localport";
2839 	} else if (phba->nvmet_support && !phba->targetport) {
2840 		failwhy = "No Targetport";
2841 	} else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
2842 		failwhy = "Bad NVME LS R_CTL";
2843 	} else if (unlikely((fctl & 0x00FF0000) !=
2844 			(FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
2845 		failwhy = "Bad NVME LS F_CTL";
2846 	} else {
2847 		axchg = kzalloc(sizeof(*axchg), GFP_ATOMIC);
2848 		if (!axchg)
2849 			failwhy = "No CTX memory";
2850 	}
2851 
2852 	if (unlikely(failwhy)) {
2853 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC | LOG_NVME_IOERR,
2854 				"6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
2855 				sid, oxid, failwhy);
2856 		goto out_fail;
2857 	}
2858 
2859 	/* validate the source of the LS is logged in */
2860 	ndlp = lpfc_findnode_did(phba->pport, sid);
2861 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp) ||
2862 	    ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
2863 	     (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
2864 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
2865 				"6216 NVME Unsol rcv: No ndlp: "
2866 				"NPort_ID x%x oxid x%x\n",
2867 				sid, oxid);
2868 		goto out_fail;
2869 	}
2870 
2871 	axchg->phba = phba;
2872 	axchg->ndlp = ndlp;
2873 	axchg->size = size;
2874 	axchg->oxid = oxid;
2875 	axchg->sid = sid;
2876 	axchg->wqeq = NULL;
2877 	axchg->state = LPFC_NVME_STE_LS_RCV;
2878 	axchg->entry_cnt = 1;
2879 	axchg->rqb_buffer = (void *)nvmebuf;
2880 	axchg->hdwq = &phba->sli4_hba.hdwq[0];
2881 	axchg->payload = nvmebuf->dbuf.virt;
2882 	INIT_LIST_HEAD(&axchg->list);
2883 
2884 	if (phba->nvmet_support)
2885 		ret = lpfc_nvmet_handle_lsreq(phba, axchg);
2886 	else
2887 		ret = lpfc_nvme_handle_lsreq(phba, axchg);
2888 
2889 	/* if zero, LS was successfully handled. If non-zero, LS not handled */
2890 	if (!ret)
2891 		return;
2892 
2893 	lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC | LOG_NVME_IOERR,
2894 			"6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
2895 			"NVMe%s handler failed %d\n",
2896 			did, sid, oxid,
2897 			(phba->nvmet_support) ? "T" : "I", ret);
2898 
2899 out_fail:
2900 
2901 	/* recycle receive buffer */
2902 	lpfc_in_buf_free(phba, &nvmebuf->dbuf);
2903 
2904 	/* If start of new exchange, abort it */
2905 	if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
2906 		ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
2907 
2908 	if (ret)
2909 		kfree(axchg);
2910 }
2911 
2912 /**
2913  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
2914  * @phba: Pointer to HBA context object.
2915  * @pring: Pointer to driver SLI ring object.
2916  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
2917  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
2918  * @fch_type: the type for the first frame of the sequence.
2919  *
2920  * This function is called with no lock held. This function uses the r_ctl and
2921  * type of the received sequence to find the correct callback function to call
2922  * to process the sequence.
2923  **/
2924 static int
2925 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2926 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
2927 			 uint32_t fch_type)
2928 {
2929 	int i;
2930 
2931 	switch (fch_type) {
2932 	case FC_TYPE_NVME:
2933 		lpfc_nvme_unsol_ls_handler(phba, saveq);
2934 		return 1;
2935 	default:
2936 		break;
2937 	}
2938 
2939 	/* unSolicited Responses */
2940 	if (pring->prt[0].profile) {
2941 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
2942 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
2943 									saveq);
2944 		return 1;
2945 	}
2946 	/* We must search, based on rctl / type
2947 	   for the right routine */
2948 	for (i = 0; i < pring->num_mask; i++) {
2949 		if ((pring->prt[i].rctl == fch_r_ctl) &&
2950 		    (pring->prt[i].type == fch_type)) {
2951 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
2952 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
2953 						(phba, pring, saveq);
2954 			return 1;
2955 		}
2956 	}
2957 	return 0;
2958 }
2959 
2960 /**
2961  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
2962  * @phba: Pointer to HBA context object.
2963  * @pring: Pointer to driver SLI ring object.
2964  * @saveq: Pointer to the unsolicited iocb.
2965  *
2966  * This function is called with no lock held by the ring event handler
2967  * when there is an unsolicited iocb posted to the response ring by the
2968  * firmware. This function gets the buffer associated with the iocbs
2969  * and calls the event handler for the ring. This function handles both
2970  * qring buffers and hbq buffers.
2971  * When the function returns 1 the caller can free the iocb object otherwise
2972  * upper layer functions will free the iocb objects.
2973  **/
2974 static int
2975 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2976 			    struct lpfc_iocbq *saveq)
2977 {
2978 	IOCB_t           * irsp;
2979 	WORD5            * w5p;
2980 	uint32_t           Rctl, Type;
2981 	struct lpfc_iocbq *iocbq;
2982 	struct lpfc_dmabuf *dmzbuf;
2983 
2984 	irsp = &(saveq->iocb);
2985 
2986 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
2987 		if (pring->lpfc_sli_rcv_async_status)
2988 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
2989 		else
2990 			lpfc_printf_log(phba,
2991 					KERN_WARNING,
2992 					LOG_SLI,
2993 					"0316 Ring %d handler: unexpected "
2994 					"ASYNC_STATUS iocb received evt_code "
2995 					"0x%x\n",
2996 					pring->ringno,
2997 					irsp->un.asyncstat.evt_code);
2998 		return 1;
2999 	}
3000 
3001 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3002 		(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3003 		if (irsp->ulpBdeCount > 0) {
3004 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3005 					irsp->un.ulpWord[3]);
3006 			lpfc_in_buf_free(phba, dmzbuf);
3007 		}
3008 
3009 		if (irsp->ulpBdeCount > 1) {
3010 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3011 					irsp->unsli3.sli3Words[3]);
3012 			lpfc_in_buf_free(phba, dmzbuf);
3013 		}
3014 
3015 		if (irsp->ulpBdeCount > 2) {
3016 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3017 				irsp->unsli3.sli3Words[7]);
3018 			lpfc_in_buf_free(phba, dmzbuf);
3019 		}
3020 
3021 		return 1;
3022 	}
3023 
3024 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3025 		if (irsp->ulpBdeCount != 0) {
3026 			saveq->context2 = lpfc_sli_get_buff(phba, pring,
3027 						irsp->un.ulpWord[3]);
3028 			if (!saveq->context2)
3029 				lpfc_printf_log(phba,
3030 					KERN_ERR,
3031 					LOG_SLI,
3032 					"0341 Ring %d Cannot find buffer for "
3033 					"an unsolicited iocb. tag 0x%x\n",
3034 					pring->ringno,
3035 					irsp->un.ulpWord[3]);
3036 		}
3037 		if (irsp->ulpBdeCount == 2) {
3038 			saveq->context3 = lpfc_sli_get_buff(phba, pring,
3039 						irsp->unsli3.sli3Words[7]);
3040 			if (!saveq->context3)
3041 				lpfc_printf_log(phba,
3042 					KERN_ERR,
3043 					LOG_SLI,
3044 					"0342 Ring %d Cannot find buffer for an"
3045 					" unsolicited iocb. tag 0x%x\n",
3046 					pring->ringno,
3047 					irsp->unsli3.sli3Words[7]);
3048 		}
3049 		list_for_each_entry(iocbq, &saveq->list, list) {
3050 			irsp = &(iocbq->iocb);
3051 			if (irsp->ulpBdeCount != 0) {
3052 				iocbq->context2 = lpfc_sli_get_buff(phba, pring,
3053 							irsp->un.ulpWord[3]);
3054 				if (!iocbq->context2)
3055 					lpfc_printf_log(phba,
3056 						KERN_ERR,
3057 						LOG_SLI,
3058 						"0343 Ring %d Cannot find "
3059 						"buffer for an unsolicited iocb"
3060 						". tag 0x%x\n", pring->ringno,
3061 						irsp->un.ulpWord[3]);
3062 			}
3063 			if (irsp->ulpBdeCount == 2) {
3064 				iocbq->context3 = lpfc_sli_get_buff(phba, pring,
3065 						irsp->unsli3.sli3Words[7]);
3066 				if (!iocbq->context3)
3067 					lpfc_printf_log(phba,
3068 						KERN_ERR,
3069 						LOG_SLI,
3070 						"0344 Ring %d Cannot find "
3071 						"buffer for an unsolicited "
3072 						"iocb. tag 0x%x\n",
3073 						pring->ringno,
3074 						irsp->unsli3.sli3Words[7]);
3075 			}
3076 		}
3077 	}
3078 	if (irsp->ulpBdeCount != 0 &&
3079 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3080 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3081 		int found = 0;
3082 
3083 		/* search continue save q for same XRI */
3084 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3085 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3086 				saveq->iocb.unsli3.rcvsli3.ox_id) {
3087 				list_add_tail(&saveq->list, &iocbq->list);
3088 				found = 1;
3089 				break;
3090 			}
3091 		}
3092 		if (!found)
3093 			list_add_tail(&saveq->clist,
3094 				      &pring->iocb_continue_saveq);
3095 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3096 			list_del_init(&iocbq->clist);
3097 			saveq = iocbq;
3098 			irsp = &(saveq->iocb);
3099 		} else
3100 			return 0;
3101 	}
3102 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3103 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3104 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3105 		Rctl = FC_RCTL_ELS_REQ;
3106 		Type = FC_TYPE_ELS;
3107 	} else {
3108 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3109 		Rctl = w5p->hcsw.Rctl;
3110 		Type = w5p->hcsw.Type;
3111 
3112 		/* Firmware Workaround */
3113 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3114 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3115 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3116 			Rctl = FC_RCTL_ELS_REQ;
3117 			Type = FC_TYPE_ELS;
3118 			w5p->hcsw.Rctl = Rctl;
3119 			w5p->hcsw.Type = Type;
3120 		}
3121 	}
3122 
3123 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3124 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3125 				"0313 Ring %d handler: unexpected Rctl x%x "
3126 				"Type x%x received\n",
3127 				pring->ringno, Rctl, Type);
3128 
3129 	return 1;
3130 }
3131 
3132 /**
3133  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3134  * @phba: Pointer to HBA context object.
3135  * @pring: Pointer to driver SLI ring object.
3136  * @prspiocb: Pointer to response iocb object.
3137  *
3138  * This function looks up the iocb_lookup table to get the command iocb
3139  * corresponding to the given response iocb using the iotag of the
3140  * response iocb. The driver calls this function with the hbalock held
3141  * for SLI3 ports or the ring lock held for SLI4 ports.
3142  * This function returns the command iocb object if it finds the command
3143  * iocb else returns NULL.
3144  **/
3145 static struct lpfc_iocbq *
3146 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3147 		      struct lpfc_sli_ring *pring,
3148 		      struct lpfc_iocbq *prspiocb)
3149 {
3150 	struct lpfc_iocbq *cmd_iocb = NULL;
3151 	uint16_t iotag;
3152 	spinlock_t *temp_lock = NULL;
3153 	unsigned long iflag = 0;
3154 
3155 	if (phba->sli_rev == LPFC_SLI_REV4)
3156 		temp_lock = &pring->ring_lock;
3157 	else
3158 		temp_lock = &phba->hbalock;
3159 
3160 	spin_lock_irqsave(temp_lock, iflag);
3161 	iotag = prspiocb->iocb.ulpIoTag;
3162 
3163 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3164 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3165 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3166 			/* remove from txcmpl queue list */
3167 			list_del_init(&cmd_iocb->list);
3168 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3169 			pring->txcmplq_cnt--;
3170 			spin_unlock_irqrestore(temp_lock, iflag);
3171 			return cmd_iocb;
3172 		}
3173 	}
3174 
3175 	spin_unlock_irqrestore(temp_lock, iflag);
3176 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3177 			"0317 iotag x%x is out of "
3178 			"range: max iotag x%x wd0 x%x\n",
3179 			iotag, phba->sli.last_iotag,
3180 			*(((uint32_t *) &prspiocb->iocb) + 7));
3181 	return NULL;
3182 }
3183 
3184 /**
3185  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3186  * @phba: Pointer to HBA context object.
3187  * @pring: Pointer to driver SLI ring object.
3188  * @iotag: IOCB tag.
3189  *
3190  * This function looks up the iocb_lookup table to get the command iocb
3191  * corresponding to the given iotag. The driver calls this function with
3192  * the ring lock held because this function is an SLI4 port only helper.
3193  * This function returns the command iocb object if it finds the command
3194  * iocb else returns NULL.
3195  **/
3196 static struct lpfc_iocbq *
3197 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3198 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3199 {
3200 	struct lpfc_iocbq *cmd_iocb = NULL;
3201 	spinlock_t *temp_lock = NULL;
3202 	unsigned long iflag = 0;
3203 
3204 	if (phba->sli_rev == LPFC_SLI_REV4)
3205 		temp_lock = &pring->ring_lock;
3206 	else
3207 		temp_lock = &phba->hbalock;
3208 
3209 	spin_lock_irqsave(temp_lock, iflag);
3210 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3211 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3212 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3213 			/* remove from txcmpl queue list */
3214 			list_del_init(&cmd_iocb->list);
3215 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3216 			pring->txcmplq_cnt--;
3217 			spin_unlock_irqrestore(temp_lock, iflag);
3218 			return cmd_iocb;
3219 		}
3220 	}
3221 
3222 	spin_unlock_irqrestore(temp_lock, iflag);
3223 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3224 			"0372 iotag x%x lookup error: max iotag (x%x) "
3225 			"iocb_flag x%x\n",
3226 			iotag, phba->sli.last_iotag,
3227 			cmd_iocb ? cmd_iocb->iocb_flag : 0xffff);
3228 	return NULL;
3229 }
3230 
3231 /**
3232  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3233  * @phba: Pointer to HBA context object.
3234  * @pring: Pointer to driver SLI ring object.
3235  * @saveq: Pointer to the response iocb to be processed.
3236  *
3237  * This function is called by the ring event handler for non-fcp
3238  * rings when there is a new response iocb in the response ring.
3239  * The caller is not required to hold any locks. This function
3240  * gets the command iocb associated with the response iocb and
3241  * calls the completion handler for the command iocb. If there
3242  * is no completion handler, the function will free the resources
3243  * associated with command iocb. If the response iocb is for
3244  * an already aborted command iocb, the status of the completion
3245  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3246  * This function always returns 1.
3247  **/
3248 static int
3249 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3250 			  struct lpfc_iocbq *saveq)
3251 {
3252 	struct lpfc_iocbq *cmdiocbp;
3253 	int rc = 1;
3254 	unsigned long iflag;
3255 
3256 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3257 	if (cmdiocbp) {
3258 		if (cmdiocbp->iocb_cmpl) {
3259 			/*
3260 			 * If an ELS command failed send an event to mgmt
3261 			 * application.
3262 			 */
3263 			if (saveq->iocb.ulpStatus &&
3264 			     (pring->ringno == LPFC_ELS_RING) &&
3265 			     (cmdiocbp->iocb.ulpCommand ==
3266 				CMD_ELS_REQUEST64_CR))
3267 				lpfc_send_els_failure_event(phba,
3268 					cmdiocbp, saveq);
3269 
3270 			/*
3271 			 * Post all ELS completions to the worker thread.
3272 			 * All other are passed to the completion callback.
3273 			 */
3274 			if (pring->ringno == LPFC_ELS_RING) {
3275 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3276 				    (cmdiocbp->iocb_flag &
3277 							LPFC_DRIVER_ABORTED)) {
3278 					spin_lock_irqsave(&phba->hbalock,
3279 							  iflag);
3280 					cmdiocbp->iocb_flag &=
3281 						~LPFC_DRIVER_ABORTED;
3282 					spin_unlock_irqrestore(&phba->hbalock,
3283 							       iflag);
3284 					saveq->iocb.ulpStatus =
3285 						IOSTAT_LOCAL_REJECT;
3286 					saveq->iocb.un.ulpWord[4] =
3287 						IOERR_SLI_ABORTED;
3288 
3289 					/* Firmware could still be in progress
3290 					 * of DMAing payload, so don't free data
3291 					 * buffer till after a hbeat.
3292 					 */
3293 					spin_lock_irqsave(&phba->hbalock,
3294 							  iflag);
3295 					saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
3296 					spin_unlock_irqrestore(&phba->hbalock,
3297 							       iflag);
3298 				}
3299 				if (phba->sli_rev == LPFC_SLI_REV4) {
3300 					if (saveq->iocb_flag &
3301 					    LPFC_EXCHANGE_BUSY) {
3302 						/* Set cmdiocb flag for the
3303 						 * exchange busy so sgl (xri)
3304 						 * will not be released until
3305 						 * the abort xri is received
3306 						 * from hba.
3307 						 */
3308 						spin_lock_irqsave(
3309 							&phba->hbalock, iflag);
3310 						cmdiocbp->iocb_flag |=
3311 							LPFC_EXCHANGE_BUSY;
3312 						spin_unlock_irqrestore(
3313 							&phba->hbalock, iflag);
3314 					}
3315 					if (cmdiocbp->iocb_flag &
3316 					    LPFC_DRIVER_ABORTED) {
3317 						/*
3318 						 * Clear LPFC_DRIVER_ABORTED
3319 						 * bit in case it was driver
3320 						 * initiated abort.
3321 						 */
3322 						spin_lock_irqsave(
3323 							&phba->hbalock, iflag);
3324 						cmdiocbp->iocb_flag &=
3325 							~LPFC_DRIVER_ABORTED;
3326 						spin_unlock_irqrestore(
3327 							&phba->hbalock, iflag);
3328 						cmdiocbp->iocb.ulpStatus =
3329 							IOSTAT_LOCAL_REJECT;
3330 						cmdiocbp->iocb.un.ulpWord[4] =
3331 							IOERR_ABORT_REQUESTED;
3332 						/*
3333 						 * For SLI4, irsiocb contains
3334 						 * NO_XRI in sli_xritag, it
3335 						 * shall not affect releasing
3336 						 * sgl (xri) process.
3337 						 */
3338 						saveq->iocb.ulpStatus =
3339 							IOSTAT_LOCAL_REJECT;
3340 						saveq->iocb.un.ulpWord[4] =
3341 							IOERR_SLI_ABORTED;
3342 						spin_lock_irqsave(
3343 							&phba->hbalock, iflag);
3344 						saveq->iocb_flag |=
3345 							LPFC_DELAY_MEM_FREE;
3346 						spin_unlock_irqrestore(
3347 							&phba->hbalock, iflag);
3348 					}
3349 				}
3350 			}
3351 			(cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
3352 		} else
3353 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3354 	} else {
3355 		/*
3356 		 * Unknown initiating command based on the response iotag.
3357 		 * This could be the case on the ELS ring because of
3358 		 * lpfc_els_abort().
3359 		 */
3360 		if (pring->ringno != LPFC_ELS_RING) {
3361 			/*
3362 			 * Ring <ringno> handler: unexpected completion IoTag
3363 			 * <IoTag>
3364 			 */
3365 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3366 					 "0322 Ring %d handler: "
3367 					 "unexpected completion IoTag x%x "
3368 					 "Data: x%x x%x x%x x%x\n",
3369 					 pring->ringno,
3370 					 saveq->iocb.ulpIoTag,
3371 					 saveq->iocb.ulpStatus,
3372 					 saveq->iocb.un.ulpWord[4],
3373 					 saveq->iocb.ulpCommand,
3374 					 saveq->iocb.ulpContext);
3375 		}
3376 	}
3377 
3378 	return rc;
3379 }
3380 
3381 /**
3382  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3383  * @phba: Pointer to HBA context object.
3384  * @pring: Pointer to driver SLI ring object.
3385  *
3386  * This function is called from the iocb ring event handlers when
3387  * put pointer is ahead of the get pointer for a ring. This function signal
3388  * an error attention condition to the worker thread and the worker
3389  * thread will transition the HBA to offline state.
3390  **/
3391 static void
3392 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3393 {
3394 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3395 	/*
3396 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3397 	 * rsp ring <portRspMax>
3398 	 */
3399 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3400 			"0312 Ring %d handler: portRspPut %d "
3401 			"is bigger than rsp ring %d\n",
3402 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3403 			pring->sli.sli3.numRiocb);
3404 
3405 	phba->link_state = LPFC_HBA_ERROR;
3406 
3407 	/*
3408 	 * All error attention handlers are posted to
3409 	 * worker thread
3410 	 */
3411 	phba->work_ha |= HA_ERATT;
3412 	phba->work_hs = HS_FFER3;
3413 
3414 	lpfc_worker_wake_up(phba);
3415 
3416 	return;
3417 }
3418 
3419 /**
3420  * lpfc_poll_eratt - Error attention polling timer timeout handler
3421  * @ptr: Pointer to address of HBA context object.
3422  *
3423  * This function is invoked by the Error Attention polling timer when the
3424  * timer times out. It will check the SLI Error Attention register for
3425  * possible attention events. If so, it will post an Error Attention event
3426  * and wake up worker thread to process it. Otherwise, it will set up the
3427  * Error Attention polling timer for the next poll.
3428  **/
3429 void lpfc_poll_eratt(struct timer_list *t)
3430 {
3431 	struct lpfc_hba *phba;
3432 	uint32_t eratt = 0;
3433 	uint64_t sli_intr, cnt;
3434 
3435 	phba = from_timer(phba, t, eratt_poll);
3436 
3437 	/* Here we will also keep track of interrupts per sec of the hba */
3438 	sli_intr = phba->sli.slistat.sli_intr;
3439 
3440 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3441 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3442 			sli_intr);
3443 	else
3444 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3445 
3446 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3447 	do_div(cnt, phba->eratt_poll_interval);
3448 	phba->sli.slistat.sli_ips = cnt;
3449 
3450 	phba->sli.slistat.sli_prev_intr = sli_intr;
3451 
3452 	/* Check chip HA register for error event */
3453 	eratt = lpfc_sli_check_eratt(phba);
3454 
3455 	if (eratt)
3456 		/* Tell the worker thread there is work to do */
3457 		lpfc_worker_wake_up(phba);
3458 	else
3459 		/* Restart the timer for next eratt poll */
3460 		mod_timer(&phba->eratt_poll,
3461 			  jiffies +
3462 			  msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3463 	return;
3464 }
3465 
3466 
3467 /**
3468  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3469  * @phba: Pointer to HBA context object.
3470  * @pring: Pointer to driver SLI ring object.
3471  * @mask: Host attention register mask for this ring.
3472  *
3473  * This function is called from the interrupt context when there is a ring
3474  * event for the fcp ring. The caller does not hold any lock.
3475  * The function processes each response iocb in the response ring until it
3476  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3477  * LE bit set. The function will call the completion handler of the command iocb
3478  * if the response iocb indicates a completion for a command iocb or it is
3479  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3480  * function if this is an unsolicited iocb.
3481  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3482  * to check it explicitly.
3483  */
3484 int
3485 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3486 				struct lpfc_sli_ring *pring, uint32_t mask)
3487 {
3488 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3489 	IOCB_t *irsp = NULL;
3490 	IOCB_t *entry = NULL;
3491 	struct lpfc_iocbq *cmdiocbq = NULL;
3492 	struct lpfc_iocbq rspiocbq;
3493 	uint32_t status;
3494 	uint32_t portRspPut, portRspMax;
3495 	int rc = 1;
3496 	lpfc_iocb_type type;
3497 	unsigned long iflag;
3498 	uint32_t rsp_cmpl = 0;
3499 
3500 	spin_lock_irqsave(&phba->hbalock, iflag);
3501 	pring->stats.iocb_event++;
3502 
3503 	/*
3504 	 * The next available response entry should never exceed the maximum
3505 	 * entries.  If it does, treat it as an adapter hardware error.
3506 	 */
3507 	portRspMax = pring->sli.sli3.numRiocb;
3508 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3509 	if (unlikely(portRspPut >= portRspMax)) {
3510 		lpfc_sli_rsp_pointers_error(phba, pring);
3511 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3512 		return 1;
3513 	}
3514 	if (phba->fcp_ring_in_use) {
3515 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3516 		return 1;
3517 	} else
3518 		phba->fcp_ring_in_use = 1;
3519 
3520 	rmb();
3521 	while (pring->sli.sli3.rspidx != portRspPut) {
3522 		/*
3523 		 * Fetch an entry off the ring and copy it into a local data
3524 		 * structure.  The copy involves a byte-swap since the
3525 		 * network byte order and pci byte orders are different.
3526 		 */
3527 		entry = lpfc_resp_iocb(phba, pring);
3528 		phba->last_completion_time = jiffies;
3529 
3530 		if (++pring->sli.sli3.rspidx >= portRspMax)
3531 			pring->sli.sli3.rspidx = 0;
3532 
3533 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3534 				      (uint32_t *) &rspiocbq.iocb,
3535 				      phba->iocb_rsp_size);
3536 		INIT_LIST_HEAD(&(rspiocbq.list));
3537 		irsp = &rspiocbq.iocb;
3538 
3539 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3540 		pring->stats.iocb_rsp++;
3541 		rsp_cmpl++;
3542 
3543 		if (unlikely(irsp->ulpStatus)) {
3544 			/*
3545 			 * If resource errors reported from HBA, reduce
3546 			 * queuedepths of the SCSI device.
3547 			 */
3548 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3549 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3550 			     IOERR_NO_RESOURCES)) {
3551 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3552 				phba->lpfc_rampdown_queue_depth(phba);
3553 				spin_lock_irqsave(&phba->hbalock, iflag);
3554 			}
3555 
3556 			/* Rsp ring <ringno> error: IOCB */
3557 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3558 					"0336 Rsp Ring %d error: IOCB Data: "
3559 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
3560 					pring->ringno,
3561 					irsp->un.ulpWord[0],
3562 					irsp->un.ulpWord[1],
3563 					irsp->un.ulpWord[2],
3564 					irsp->un.ulpWord[3],
3565 					irsp->un.ulpWord[4],
3566 					irsp->un.ulpWord[5],
3567 					*(uint32_t *)&irsp->un1,
3568 					*((uint32_t *)&irsp->un1 + 1));
3569 		}
3570 
3571 		switch (type) {
3572 		case LPFC_ABORT_IOCB:
3573 		case LPFC_SOL_IOCB:
3574 			/*
3575 			 * Idle exchange closed via ABTS from port.  No iocb
3576 			 * resources need to be recovered.
3577 			 */
3578 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3579 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3580 						"0333 IOCB cmd 0x%x"
3581 						" processed. Skipping"
3582 						" completion\n",
3583 						irsp->ulpCommand);
3584 				break;
3585 			}
3586 
3587 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3588 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3589 							 &rspiocbq);
3590 			spin_lock_irqsave(&phba->hbalock, iflag);
3591 			if (unlikely(!cmdiocbq))
3592 				break;
3593 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3594 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3595 			if (cmdiocbq->iocb_cmpl) {
3596 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3597 				(cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
3598 						      &rspiocbq);
3599 				spin_lock_irqsave(&phba->hbalock, iflag);
3600 			}
3601 			break;
3602 		case LPFC_UNSOL_IOCB:
3603 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3604 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
3605 			spin_lock_irqsave(&phba->hbalock, iflag);
3606 			break;
3607 		default:
3608 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3609 				char adaptermsg[LPFC_MAX_ADPTMSG];
3610 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3611 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
3612 				       MAX_MSG_DATA);
3613 				dev_warn(&((phba->pcidev)->dev),
3614 					 "lpfc%d: %s\n",
3615 					 phba->brd_no, adaptermsg);
3616 			} else {
3617 				/* Unknown IOCB command */
3618 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3619 						"0334 Unknown IOCB command "
3620 						"Data: x%x, x%x x%x x%x x%x\n",
3621 						type, irsp->ulpCommand,
3622 						irsp->ulpStatus,
3623 						irsp->ulpIoTag,
3624 						irsp->ulpContext);
3625 			}
3626 			break;
3627 		}
3628 
3629 		/*
3630 		 * The response IOCB has been processed.  Update the ring
3631 		 * pointer in SLIM.  If the port response put pointer has not
3632 		 * been updated, sync the pgp->rspPutInx and fetch the new port
3633 		 * response put pointer.
3634 		 */
3635 		writel(pring->sli.sli3.rspidx,
3636 			&phba->host_gp[pring->ringno].rspGetInx);
3637 
3638 		if (pring->sli.sli3.rspidx == portRspPut)
3639 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3640 	}
3641 
3642 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
3643 		pring->stats.iocb_rsp_full++;
3644 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3645 		writel(status, phba->CAregaddr);
3646 		readl(phba->CAregaddr);
3647 	}
3648 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3649 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3650 		pring->stats.iocb_cmd_empty++;
3651 
3652 		/* Force update of the local copy of cmdGetInx */
3653 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3654 		lpfc_sli_resume_iocb(phba, pring);
3655 
3656 		if ((pring->lpfc_sli_cmd_available))
3657 			(pring->lpfc_sli_cmd_available) (phba, pring);
3658 
3659 	}
3660 
3661 	phba->fcp_ring_in_use = 0;
3662 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3663 	return rc;
3664 }
3665 
3666 /**
3667  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
3668  * @phba: Pointer to HBA context object.
3669  * @pring: Pointer to driver SLI ring object.
3670  * @rspiocbp: Pointer to driver response IOCB object.
3671  *
3672  * This function is called from the worker thread when there is a slow-path
3673  * response IOCB to process. This function chains all the response iocbs until
3674  * seeing the iocb with the LE bit set. The function will call
3675  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
3676  * completion of a command iocb. The function will call the
3677  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
3678  * The function frees the resources or calls the completion handler if this
3679  * iocb is an abort completion. The function returns NULL when the response
3680  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
3681  * this function shall chain the iocb on to the iocb_continueq and return the
3682  * response iocb passed in.
3683  **/
3684 static struct lpfc_iocbq *
3685 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3686 			struct lpfc_iocbq *rspiocbp)
3687 {
3688 	struct lpfc_iocbq *saveq;
3689 	struct lpfc_iocbq *cmdiocbp;
3690 	struct lpfc_iocbq *next_iocb;
3691 	IOCB_t *irsp = NULL;
3692 	uint32_t free_saveq;
3693 	uint8_t iocb_cmd_type;
3694 	lpfc_iocb_type type;
3695 	unsigned long iflag;
3696 	int rc;
3697 
3698 	spin_lock_irqsave(&phba->hbalock, iflag);
3699 	/* First add the response iocb to the countinueq list */
3700 	list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
3701 	pring->iocb_continueq_cnt++;
3702 
3703 	/* Now, determine whether the list is completed for processing */
3704 	irsp = &rspiocbp->iocb;
3705 	if (irsp->ulpLe) {
3706 		/*
3707 		 * By default, the driver expects to free all resources
3708 		 * associated with this iocb completion.
3709 		 */
3710 		free_saveq = 1;
3711 		saveq = list_get_first(&pring->iocb_continueq,
3712 				       struct lpfc_iocbq, list);
3713 		irsp = &(saveq->iocb);
3714 		list_del_init(&pring->iocb_continueq);
3715 		pring->iocb_continueq_cnt = 0;
3716 
3717 		pring->stats.iocb_rsp++;
3718 
3719 		/*
3720 		 * If resource errors reported from HBA, reduce
3721 		 * queuedepths of the SCSI device.
3722 		 */
3723 		if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3724 		    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3725 		     IOERR_NO_RESOURCES)) {
3726 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3727 			phba->lpfc_rampdown_queue_depth(phba);
3728 			spin_lock_irqsave(&phba->hbalock, iflag);
3729 		}
3730 
3731 		if (irsp->ulpStatus) {
3732 			/* Rsp ring <ringno> error: IOCB */
3733 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3734 					"0328 Rsp Ring %d error: "
3735 					"IOCB Data: "
3736 					"x%x x%x x%x x%x "
3737 					"x%x x%x x%x x%x "
3738 					"x%x x%x x%x x%x "
3739 					"x%x x%x x%x x%x\n",
3740 					pring->ringno,
3741 					irsp->un.ulpWord[0],
3742 					irsp->un.ulpWord[1],
3743 					irsp->un.ulpWord[2],
3744 					irsp->un.ulpWord[3],
3745 					irsp->un.ulpWord[4],
3746 					irsp->un.ulpWord[5],
3747 					*(((uint32_t *) irsp) + 6),
3748 					*(((uint32_t *) irsp) + 7),
3749 					*(((uint32_t *) irsp) + 8),
3750 					*(((uint32_t *) irsp) + 9),
3751 					*(((uint32_t *) irsp) + 10),
3752 					*(((uint32_t *) irsp) + 11),
3753 					*(((uint32_t *) irsp) + 12),
3754 					*(((uint32_t *) irsp) + 13),
3755 					*(((uint32_t *) irsp) + 14),
3756 					*(((uint32_t *) irsp) + 15));
3757 		}
3758 
3759 		/*
3760 		 * Fetch the IOCB command type and call the correct completion
3761 		 * routine. Solicited and Unsolicited IOCBs on the ELS ring
3762 		 * get freed back to the lpfc_iocb_list by the discovery
3763 		 * kernel thread.
3764 		 */
3765 		iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
3766 		type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
3767 		switch (type) {
3768 		case LPFC_SOL_IOCB:
3769 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3770 			rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
3771 			spin_lock_irqsave(&phba->hbalock, iflag);
3772 			break;
3773 
3774 		case LPFC_UNSOL_IOCB:
3775 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3776 			rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
3777 			spin_lock_irqsave(&phba->hbalock, iflag);
3778 			if (!rc)
3779 				free_saveq = 0;
3780 			break;
3781 
3782 		case LPFC_ABORT_IOCB:
3783 			cmdiocbp = NULL;
3784 			if (irsp->ulpCommand != CMD_XRI_ABORTED_CX) {
3785 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3786 				cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
3787 								 saveq);
3788 				spin_lock_irqsave(&phba->hbalock, iflag);
3789 			}
3790 			if (cmdiocbp) {
3791 				/* Call the specified completion routine */
3792 				if (cmdiocbp->iocb_cmpl) {
3793 					spin_unlock_irqrestore(&phba->hbalock,
3794 							       iflag);
3795 					(cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
3796 							      saveq);
3797 					spin_lock_irqsave(&phba->hbalock,
3798 							  iflag);
3799 				} else
3800 					__lpfc_sli_release_iocbq(phba,
3801 								 cmdiocbp);
3802 			}
3803 			break;
3804 
3805 		case LPFC_UNKNOWN_IOCB:
3806 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3807 				char adaptermsg[LPFC_MAX_ADPTMSG];
3808 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3809 				memcpy(&adaptermsg[0], (uint8_t *)irsp,
3810 				       MAX_MSG_DATA);
3811 				dev_warn(&((phba->pcidev)->dev),
3812 					 "lpfc%d: %s\n",
3813 					 phba->brd_no, adaptermsg);
3814 			} else {
3815 				/* Unknown IOCB command */
3816 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3817 						"0335 Unknown IOCB "
3818 						"command Data: x%x "
3819 						"x%x x%x x%x\n",
3820 						irsp->ulpCommand,
3821 						irsp->ulpStatus,
3822 						irsp->ulpIoTag,
3823 						irsp->ulpContext);
3824 			}
3825 			break;
3826 		}
3827 
3828 		if (free_saveq) {
3829 			list_for_each_entry_safe(rspiocbp, next_iocb,
3830 						 &saveq->list, list) {
3831 				list_del_init(&rspiocbp->list);
3832 				__lpfc_sli_release_iocbq(phba, rspiocbp);
3833 			}
3834 			__lpfc_sli_release_iocbq(phba, saveq);
3835 		}
3836 		rspiocbp = NULL;
3837 	}
3838 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3839 	return rspiocbp;
3840 }
3841 
3842 /**
3843  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
3844  * @phba: Pointer to HBA context object.
3845  * @pring: Pointer to driver SLI ring object.
3846  * @mask: Host attention register mask for this ring.
3847  *
3848  * This routine wraps the actual slow_ring event process routine from the
3849  * API jump table function pointer from the lpfc_hba struct.
3850  **/
3851 void
3852 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
3853 				struct lpfc_sli_ring *pring, uint32_t mask)
3854 {
3855 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
3856 }
3857 
3858 /**
3859  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
3860  * @phba: Pointer to HBA context object.
3861  * @pring: Pointer to driver SLI ring object.
3862  * @mask: Host attention register mask for this ring.
3863  *
3864  * This function is called from the worker thread when there is a ring event
3865  * for non-fcp rings. The caller does not hold any lock. The function will
3866  * remove each response iocb in the response ring and calls the handle
3867  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3868  **/
3869 static void
3870 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
3871 				   struct lpfc_sli_ring *pring, uint32_t mask)
3872 {
3873 	struct lpfc_pgp *pgp;
3874 	IOCB_t *entry;
3875 	IOCB_t *irsp = NULL;
3876 	struct lpfc_iocbq *rspiocbp = NULL;
3877 	uint32_t portRspPut, portRspMax;
3878 	unsigned long iflag;
3879 	uint32_t status;
3880 
3881 	pgp = &phba->port_gp[pring->ringno];
3882 	spin_lock_irqsave(&phba->hbalock, iflag);
3883 	pring->stats.iocb_event++;
3884 
3885 	/*
3886 	 * The next available response entry should never exceed the maximum
3887 	 * entries.  If it does, treat it as an adapter hardware error.
3888 	 */
3889 	portRspMax = pring->sli.sli3.numRiocb;
3890 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3891 	if (portRspPut >= portRspMax) {
3892 		/*
3893 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3894 		 * rsp ring <portRspMax>
3895 		 */
3896 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3897 				"0303 Ring %d handler: portRspPut %d "
3898 				"is bigger than rsp ring %d\n",
3899 				pring->ringno, portRspPut, portRspMax);
3900 
3901 		phba->link_state = LPFC_HBA_ERROR;
3902 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3903 
3904 		phba->work_hs = HS_FFER3;
3905 		lpfc_handle_eratt(phba);
3906 
3907 		return;
3908 	}
3909 
3910 	rmb();
3911 	while (pring->sli.sli3.rspidx != portRspPut) {
3912 		/*
3913 		 * Build a completion list and call the appropriate handler.
3914 		 * The process is to get the next available response iocb, get
3915 		 * a free iocb from the list, copy the response data into the
3916 		 * free iocb, insert to the continuation list, and update the
3917 		 * next response index to slim.  This process makes response
3918 		 * iocb's in the ring available to DMA as fast as possible but
3919 		 * pays a penalty for a copy operation.  Since the iocb is
3920 		 * only 32 bytes, this penalty is considered small relative to
3921 		 * the PCI reads for register values and a slim write.  When
3922 		 * the ulpLe field is set, the entire Command has been
3923 		 * received.
3924 		 */
3925 		entry = lpfc_resp_iocb(phba, pring);
3926 
3927 		phba->last_completion_time = jiffies;
3928 		rspiocbp = __lpfc_sli_get_iocbq(phba);
3929 		if (rspiocbp == NULL) {
3930 			printk(KERN_ERR "%s: out of buffers! Failing "
3931 			       "completion.\n", __func__);
3932 			break;
3933 		}
3934 
3935 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
3936 				      phba->iocb_rsp_size);
3937 		irsp = &rspiocbp->iocb;
3938 
3939 		if (++pring->sli.sli3.rspidx >= portRspMax)
3940 			pring->sli.sli3.rspidx = 0;
3941 
3942 		if (pring->ringno == LPFC_ELS_RING) {
3943 			lpfc_debugfs_slow_ring_trc(phba,
3944 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
3945 				*(((uint32_t *) irsp) + 4),
3946 				*(((uint32_t *) irsp) + 6),
3947 				*(((uint32_t *) irsp) + 7));
3948 		}
3949 
3950 		writel(pring->sli.sli3.rspidx,
3951 			&phba->host_gp[pring->ringno].rspGetInx);
3952 
3953 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3954 		/* Handle the response IOCB */
3955 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
3956 		spin_lock_irqsave(&phba->hbalock, iflag);
3957 
3958 		/*
3959 		 * If the port response put pointer has not been updated, sync
3960 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
3961 		 * response put pointer.
3962 		 */
3963 		if (pring->sli.sli3.rspidx == portRspPut) {
3964 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3965 		}
3966 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
3967 
3968 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
3969 		/* At least one response entry has been freed */
3970 		pring->stats.iocb_rsp_full++;
3971 		/* SET RxRE_RSP in Chip Att register */
3972 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3973 		writel(status, phba->CAregaddr);
3974 		readl(phba->CAregaddr); /* flush */
3975 	}
3976 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3977 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3978 		pring->stats.iocb_cmd_empty++;
3979 
3980 		/* Force update of the local copy of cmdGetInx */
3981 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3982 		lpfc_sli_resume_iocb(phba, pring);
3983 
3984 		if ((pring->lpfc_sli_cmd_available))
3985 			(pring->lpfc_sli_cmd_available) (phba, pring);
3986 
3987 	}
3988 
3989 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3990 	return;
3991 }
3992 
3993 /**
3994  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
3995  * @phba: Pointer to HBA context object.
3996  * @pring: Pointer to driver SLI ring object.
3997  * @mask: Host attention register mask for this ring.
3998  *
3999  * This function is called from the worker thread when there is a pending
4000  * ELS response iocb on the driver internal slow-path response iocb worker
4001  * queue. The caller does not hold any lock. The function will remove each
4002  * response iocb from the response worker queue and calls the handle
4003  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4004  **/
4005 static void
4006 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4007 				   struct lpfc_sli_ring *pring, uint32_t mask)
4008 {
4009 	struct lpfc_iocbq *irspiocbq;
4010 	struct hbq_dmabuf *dmabuf;
4011 	struct lpfc_cq_event *cq_event;
4012 	unsigned long iflag;
4013 	int count = 0;
4014 
4015 	spin_lock_irqsave(&phba->hbalock, iflag);
4016 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
4017 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4018 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4019 		/* Get the response iocb from the head of work queue */
4020 		spin_lock_irqsave(&phba->hbalock, iflag);
4021 		list_remove_head(&phba->sli4_hba.sp_queue_event,
4022 				 cq_event, struct lpfc_cq_event, list);
4023 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4024 
4025 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4026 		case CQE_CODE_COMPL_WQE:
4027 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4028 						 cq_event);
4029 			/* Translate ELS WCQE to response IOCBQ */
4030 			irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
4031 								   irspiocbq);
4032 			if (irspiocbq)
4033 				lpfc_sli_sp_handle_rspiocb(phba, pring,
4034 							   irspiocbq);
4035 			count++;
4036 			break;
4037 		case CQE_CODE_RECEIVE:
4038 		case CQE_CODE_RECEIVE_V1:
4039 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
4040 					      cq_event);
4041 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
4042 			count++;
4043 			break;
4044 		default:
4045 			break;
4046 		}
4047 
4048 		/* Limit the number of events to 64 to avoid soft lockups */
4049 		if (count == 64)
4050 			break;
4051 	}
4052 }
4053 
4054 /**
4055  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4056  * @phba: Pointer to HBA context object.
4057  * @pring: Pointer to driver SLI ring object.
4058  *
4059  * This function aborts all iocbs in the given ring and frees all the iocb
4060  * objects in txq. This function issues an abort iocb for all the iocb commands
4061  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4062  * the return of this function. The caller is not required to hold any locks.
4063  **/
4064 void
4065 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4066 {
4067 	LIST_HEAD(completions);
4068 	struct lpfc_iocbq *iocb, *next_iocb;
4069 
4070 	if (pring->ringno == LPFC_ELS_RING) {
4071 		lpfc_fabric_abort_hba(phba);
4072 	}
4073 
4074 	/* Error everything on txq and txcmplq
4075 	 * First do the txq.
4076 	 */
4077 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4078 		spin_lock_irq(&pring->ring_lock);
4079 		list_splice_init(&pring->txq, &completions);
4080 		pring->txq_cnt = 0;
4081 		spin_unlock_irq(&pring->ring_lock);
4082 
4083 		spin_lock_irq(&phba->hbalock);
4084 		/* Next issue ABTS for everything on the txcmplq */
4085 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4086 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
4087 		spin_unlock_irq(&phba->hbalock);
4088 	} else {
4089 		spin_lock_irq(&phba->hbalock);
4090 		list_splice_init(&pring->txq, &completions);
4091 		pring->txq_cnt = 0;
4092 
4093 		/* Next issue ABTS for everything on the txcmplq */
4094 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4095 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
4096 		spin_unlock_irq(&phba->hbalock);
4097 	}
4098 
4099 	/* Cancel all the IOCBs from the completions list */
4100 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
4101 			      IOERR_SLI_ABORTED);
4102 }
4103 
4104 /**
4105  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4106  * @phba: Pointer to HBA context object.
4107  * @pring: Pointer to driver SLI ring object.
4108  *
4109  * This function aborts all iocbs in FCP rings and frees all the iocb
4110  * objects in txq. This function issues an abort iocb for all the iocb commands
4111  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4112  * the return of this function. The caller is not required to hold any locks.
4113  **/
4114 void
4115 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4116 {
4117 	struct lpfc_sli *psli = &phba->sli;
4118 	struct lpfc_sli_ring  *pring;
4119 	uint32_t i;
4120 
4121 	/* Look on all the FCP Rings for the iotag */
4122 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4123 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4124 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4125 			lpfc_sli_abort_iocb_ring(phba, pring);
4126 		}
4127 	} else {
4128 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4129 		lpfc_sli_abort_iocb_ring(phba, pring);
4130 	}
4131 }
4132 
4133 /**
4134  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4135  * @phba: Pointer to HBA context object.
4136  *
4137  * This function flushes all iocbs in the IO ring and frees all the iocb
4138  * objects in txq and txcmplq. This function will not issue abort iocbs
4139  * for all the iocb commands in txcmplq, they will just be returned with
4140  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4141  * slot has been permanently disabled.
4142  **/
4143 void
4144 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4145 {
4146 	LIST_HEAD(txq);
4147 	LIST_HEAD(txcmplq);
4148 	struct lpfc_sli *psli = &phba->sli;
4149 	struct lpfc_sli_ring  *pring;
4150 	uint32_t i;
4151 	struct lpfc_iocbq *piocb, *next_iocb;
4152 
4153 	spin_lock_irq(&phba->hbalock);
4154 	if (phba->hba_flag & HBA_IOQ_FLUSH ||
4155 	    !phba->sli4_hba.hdwq) {
4156 		spin_unlock_irq(&phba->hbalock);
4157 		return;
4158 	}
4159 	/* Indicate the I/O queues are flushed */
4160 	phba->hba_flag |= HBA_IOQ_FLUSH;
4161 	spin_unlock_irq(&phba->hbalock);
4162 
4163 	/* Look on all the FCP Rings for the iotag */
4164 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4165 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4166 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4167 
4168 			spin_lock_irq(&pring->ring_lock);
4169 			/* Retrieve everything on txq */
4170 			list_splice_init(&pring->txq, &txq);
4171 			list_for_each_entry_safe(piocb, next_iocb,
4172 						 &pring->txcmplq, list)
4173 				piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4174 			/* Retrieve everything on the txcmplq */
4175 			list_splice_init(&pring->txcmplq, &txcmplq);
4176 			pring->txq_cnt = 0;
4177 			pring->txcmplq_cnt = 0;
4178 			spin_unlock_irq(&pring->ring_lock);
4179 
4180 			/* Flush the txq */
4181 			lpfc_sli_cancel_iocbs(phba, &txq,
4182 					      IOSTAT_LOCAL_REJECT,
4183 					      IOERR_SLI_DOWN);
4184 			/* Flush the txcmpq */
4185 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4186 					      IOSTAT_LOCAL_REJECT,
4187 					      IOERR_SLI_DOWN);
4188 		}
4189 	} else {
4190 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4191 
4192 		spin_lock_irq(&phba->hbalock);
4193 		/* Retrieve everything on txq */
4194 		list_splice_init(&pring->txq, &txq);
4195 		list_for_each_entry_safe(piocb, next_iocb,
4196 					 &pring->txcmplq, list)
4197 			piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4198 		/* Retrieve everything on the txcmplq */
4199 		list_splice_init(&pring->txcmplq, &txcmplq);
4200 		pring->txq_cnt = 0;
4201 		pring->txcmplq_cnt = 0;
4202 		spin_unlock_irq(&phba->hbalock);
4203 
4204 		/* Flush the txq */
4205 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4206 				      IOERR_SLI_DOWN);
4207 		/* Flush the txcmpq */
4208 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4209 				      IOERR_SLI_DOWN);
4210 	}
4211 }
4212 
4213 /**
4214  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4215  * @phba: Pointer to HBA context object.
4216  * @mask: Bit mask to be checked.
4217  *
4218  * This function reads the host status register and compares
4219  * with the provided bit mask to check if HBA completed
4220  * the restart. This function will wait in a loop for the
4221  * HBA to complete restart. If the HBA does not restart within
4222  * 15 iterations, the function will reset the HBA again. The
4223  * function returns 1 when HBA fail to restart otherwise returns
4224  * zero.
4225  **/
4226 static int
4227 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4228 {
4229 	uint32_t status;
4230 	int i = 0;
4231 	int retval = 0;
4232 
4233 	/* Read the HBA Host Status Register */
4234 	if (lpfc_readl(phba->HSregaddr, &status))
4235 		return 1;
4236 
4237 	/*
4238 	 * Check status register every 100ms for 5 retries, then every
4239 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4240 	 * every 2.5 sec for 4.
4241 	 * Break our of the loop if errors occurred during init.
4242 	 */
4243 	while (((status & mask) != mask) &&
4244 	       !(status & HS_FFERM) &&
4245 	       i++ < 20) {
4246 
4247 		if (i <= 5)
4248 			msleep(10);
4249 		else if (i <= 10)
4250 			msleep(500);
4251 		else
4252 			msleep(2500);
4253 
4254 		if (i == 15) {
4255 				/* Do post */
4256 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4257 			lpfc_sli_brdrestart(phba);
4258 		}
4259 		/* Read the HBA Host Status Register */
4260 		if (lpfc_readl(phba->HSregaddr, &status)) {
4261 			retval = 1;
4262 			break;
4263 		}
4264 	}
4265 
4266 	/* Check to see if any errors occurred during init */
4267 	if ((status & HS_FFERM) || (i >= 20)) {
4268 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4269 				"2751 Adapter failed to restart, "
4270 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4271 				status,
4272 				readl(phba->MBslimaddr + 0xa8),
4273 				readl(phba->MBslimaddr + 0xac));
4274 		phba->link_state = LPFC_HBA_ERROR;
4275 		retval = 1;
4276 	}
4277 
4278 	return retval;
4279 }
4280 
4281 /**
4282  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4283  * @phba: Pointer to HBA context object.
4284  * @mask: Bit mask to be checked.
4285  *
4286  * This function checks the host status register to check if HBA is
4287  * ready. This function will wait in a loop for the HBA to be ready
4288  * If the HBA is not ready , the function will will reset the HBA PCI
4289  * function again. The function returns 1 when HBA fail to be ready
4290  * otherwise returns zero.
4291  **/
4292 static int
4293 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4294 {
4295 	uint32_t status;
4296 	int retval = 0;
4297 
4298 	/* Read the HBA Host Status Register */
4299 	status = lpfc_sli4_post_status_check(phba);
4300 
4301 	if (status) {
4302 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4303 		lpfc_sli_brdrestart(phba);
4304 		status = lpfc_sli4_post_status_check(phba);
4305 	}
4306 
4307 	/* Check to see if any errors occurred during init */
4308 	if (status) {
4309 		phba->link_state = LPFC_HBA_ERROR;
4310 		retval = 1;
4311 	} else
4312 		phba->sli4_hba.intr_enable = 0;
4313 
4314 	return retval;
4315 }
4316 
4317 /**
4318  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4319  * @phba: Pointer to HBA context object.
4320  * @mask: Bit mask to be checked.
4321  *
4322  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4323  * from the API jump table function pointer from the lpfc_hba struct.
4324  **/
4325 int
4326 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4327 {
4328 	return phba->lpfc_sli_brdready(phba, mask);
4329 }
4330 
4331 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4332 
4333 /**
4334  * lpfc_reset_barrier - Make HBA ready for HBA reset
4335  * @phba: Pointer to HBA context object.
4336  *
4337  * This function is called before resetting an HBA. This function is called
4338  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4339  **/
4340 void lpfc_reset_barrier(struct lpfc_hba *phba)
4341 {
4342 	uint32_t __iomem *resp_buf;
4343 	uint32_t __iomem *mbox_buf;
4344 	volatile uint32_t mbox;
4345 	uint32_t hc_copy, ha_copy, resp_data;
4346 	int  i;
4347 	uint8_t hdrtype;
4348 
4349 	lockdep_assert_held(&phba->hbalock);
4350 
4351 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4352 	if (hdrtype != 0x80 ||
4353 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4354 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4355 		return;
4356 
4357 	/*
4358 	 * Tell the other part of the chip to suspend temporarily all
4359 	 * its DMA activity.
4360 	 */
4361 	resp_buf = phba->MBslimaddr;
4362 
4363 	/* Disable the error attention */
4364 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4365 		return;
4366 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4367 	readl(phba->HCregaddr); /* flush */
4368 	phba->link_flag |= LS_IGNORE_ERATT;
4369 
4370 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4371 		return;
4372 	if (ha_copy & HA_ERATT) {
4373 		/* Clear Chip error bit */
4374 		writel(HA_ERATT, phba->HAregaddr);
4375 		phba->pport->stopped = 1;
4376 	}
4377 
4378 	mbox = 0;
4379 	((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
4380 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
4381 
4382 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4383 	mbox_buf = phba->MBslimaddr;
4384 	writel(mbox, mbox_buf);
4385 
4386 	for (i = 0; i < 50; i++) {
4387 		if (lpfc_readl((resp_buf + 1), &resp_data))
4388 			return;
4389 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4390 			mdelay(1);
4391 		else
4392 			break;
4393 	}
4394 	resp_data = 0;
4395 	if (lpfc_readl((resp_buf + 1), &resp_data))
4396 		return;
4397 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4398 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4399 		    phba->pport->stopped)
4400 			goto restore_hc;
4401 		else
4402 			goto clear_errat;
4403 	}
4404 
4405 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
4406 	resp_data = 0;
4407 	for (i = 0; i < 500; i++) {
4408 		if (lpfc_readl(resp_buf, &resp_data))
4409 			return;
4410 		if (resp_data != mbox)
4411 			mdelay(1);
4412 		else
4413 			break;
4414 	}
4415 
4416 clear_errat:
4417 
4418 	while (++i < 500) {
4419 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4420 			return;
4421 		if (!(ha_copy & HA_ERATT))
4422 			mdelay(1);
4423 		else
4424 			break;
4425 	}
4426 
4427 	if (readl(phba->HAregaddr) & HA_ERATT) {
4428 		writel(HA_ERATT, phba->HAregaddr);
4429 		phba->pport->stopped = 1;
4430 	}
4431 
4432 restore_hc:
4433 	phba->link_flag &= ~LS_IGNORE_ERATT;
4434 	writel(hc_copy, phba->HCregaddr);
4435 	readl(phba->HCregaddr); /* flush */
4436 }
4437 
4438 /**
4439  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4440  * @phba: Pointer to HBA context object.
4441  *
4442  * This function issues a kill_board mailbox command and waits for
4443  * the error attention interrupt. This function is called for stopping
4444  * the firmware processing. The caller is not required to hold any
4445  * locks. This function calls lpfc_hba_down_post function to free
4446  * any pending commands after the kill. The function will return 1 when it
4447  * fails to kill the board else will return 0.
4448  **/
4449 int
4450 lpfc_sli_brdkill(struct lpfc_hba *phba)
4451 {
4452 	struct lpfc_sli *psli;
4453 	LPFC_MBOXQ_t *pmb;
4454 	uint32_t status;
4455 	uint32_t ha_copy;
4456 	int retval;
4457 	int i = 0;
4458 
4459 	psli = &phba->sli;
4460 
4461 	/* Kill HBA */
4462 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4463 			"0329 Kill HBA Data: x%x x%x\n",
4464 			phba->pport->port_state, psli->sli_flag);
4465 
4466 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4467 	if (!pmb)
4468 		return 1;
4469 
4470 	/* Disable the error attention */
4471 	spin_lock_irq(&phba->hbalock);
4472 	if (lpfc_readl(phba->HCregaddr, &status)) {
4473 		spin_unlock_irq(&phba->hbalock);
4474 		mempool_free(pmb, phba->mbox_mem_pool);
4475 		return 1;
4476 	}
4477 	status &= ~HC_ERINT_ENA;
4478 	writel(status, phba->HCregaddr);
4479 	readl(phba->HCregaddr); /* flush */
4480 	phba->link_flag |= LS_IGNORE_ERATT;
4481 	spin_unlock_irq(&phba->hbalock);
4482 
4483 	lpfc_kill_board(phba, pmb);
4484 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4485 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4486 
4487 	if (retval != MBX_SUCCESS) {
4488 		if (retval != MBX_BUSY)
4489 			mempool_free(pmb, phba->mbox_mem_pool);
4490 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4491 				"2752 KILL_BOARD command failed retval %d\n",
4492 				retval);
4493 		spin_lock_irq(&phba->hbalock);
4494 		phba->link_flag &= ~LS_IGNORE_ERATT;
4495 		spin_unlock_irq(&phba->hbalock);
4496 		return 1;
4497 	}
4498 
4499 	spin_lock_irq(&phba->hbalock);
4500 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
4501 	spin_unlock_irq(&phba->hbalock);
4502 
4503 	mempool_free(pmb, phba->mbox_mem_pool);
4504 
4505 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
4506 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
4507 	 * 3 seconds we still set HBA_ERROR state because the status of the
4508 	 * board is now undefined.
4509 	 */
4510 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4511 		return 1;
4512 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
4513 		mdelay(100);
4514 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4515 			return 1;
4516 	}
4517 
4518 	del_timer_sync(&psli->mbox_tmo);
4519 	if (ha_copy & HA_ERATT) {
4520 		writel(HA_ERATT, phba->HAregaddr);
4521 		phba->pport->stopped = 1;
4522 	}
4523 	spin_lock_irq(&phba->hbalock);
4524 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4525 	psli->mbox_active = NULL;
4526 	phba->link_flag &= ~LS_IGNORE_ERATT;
4527 	spin_unlock_irq(&phba->hbalock);
4528 
4529 	lpfc_hba_down_post(phba);
4530 	phba->link_state = LPFC_HBA_ERROR;
4531 
4532 	return ha_copy & HA_ERATT ? 0 : 1;
4533 }
4534 
4535 /**
4536  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
4537  * @phba: Pointer to HBA context object.
4538  *
4539  * This function resets the HBA by writing HC_INITFF to the control
4540  * register. After the HBA resets, this function resets all the iocb ring
4541  * indices. This function disables PCI layer parity checking during
4542  * the reset.
4543  * This function returns 0 always.
4544  * The caller is not required to hold any locks.
4545  **/
4546 int
4547 lpfc_sli_brdreset(struct lpfc_hba *phba)
4548 {
4549 	struct lpfc_sli *psli;
4550 	struct lpfc_sli_ring *pring;
4551 	uint16_t cfg_value;
4552 	int i;
4553 
4554 	psli = &phba->sli;
4555 
4556 	/* Reset HBA */
4557 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4558 			"0325 Reset HBA Data: x%x x%x\n",
4559 			(phba->pport) ? phba->pport->port_state : 0,
4560 			psli->sli_flag);
4561 
4562 	/* perform board reset */
4563 	phba->fc_eventTag = 0;
4564 	phba->link_events = 0;
4565 	if (phba->pport) {
4566 		phba->pport->fc_myDID = 0;
4567 		phba->pport->fc_prevDID = 0;
4568 	}
4569 
4570 	/* Turn off parity checking and serr during the physical reset */
4571 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
4572 		return -EIO;
4573 
4574 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
4575 			      (cfg_value &
4576 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4577 
4578 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4579 
4580 	/* Now toggle INITFF bit in the Host Control Register */
4581 	writel(HC_INITFF, phba->HCregaddr);
4582 	mdelay(1);
4583 	readl(phba->HCregaddr); /* flush */
4584 	writel(0, phba->HCregaddr);
4585 	readl(phba->HCregaddr); /* flush */
4586 
4587 	/* Restore PCI cmd register */
4588 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4589 
4590 	/* Initialize relevant SLI info */
4591 	for (i = 0; i < psli->num_rings; i++) {
4592 		pring = &psli->sli3_ring[i];
4593 		pring->flag = 0;
4594 		pring->sli.sli3.rspidx = 0;
4595 		pring->sli.sli3.next_cmdidx  = 0;
4596 		pring->sli.sli3.local_getidx = 0;
4597 		pring->sli.sli3.cmdidx = 0;
4598 		pring->missbufcnt = 0;
4599 	}
4600 
4601 	phba->link_state = LPFC_WARM_START;
4602 	return 0;
4603 }
4604 
4605 /**
4606  * lpfc_sli4_brdreset - Reset a sli-4 HBA
4607  * @phba: Pointer to HBA context object.
4608  *
4609  * This function resets a SLI4 HBA. This function disables PCI layer parity
4610  * checking during resets the device. The caller is not required to hold
4611  * any locks.
4612  *
4613  * This function returns 0 on success else returns negative error code.
4614  **/
4615 int
4616 lpfc_sli4_brdreset(struct lpfc_hba *phba)
4617 {
4618 	struct lpfc_sli *psli = &phba->sli;
4619 	uint16_t cfg_value;
4620 	int rc = 0;
4621 
4622 	/* Reset HBA */
4623 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4624 			"0295 Reset HBA Data: x%x x%x x%x\n",
4625 			phba->pport->port_state, psli->sli_flag,
4626 			phba->hba_flag);
4627 
4628 	/* perform board reset */
4629 	phba->fc_eventTag = 0;
4630 	phba->link_events = 0;
4631 	phba->pport->fc_myDID = 0;
4632 	phba->pport->fc_prevDID = 0;
4633 
4634 	spin_lock_irq(&phba->hbalock);
4635 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
4636 	phba->fcf.fcf_flag = 0;
4637 	spin_unlock_irq(&phba->hbalock);
4638 
4639 	/* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
4640 	if (phba->hba_flag & HBA_FW_DUMP_OP) {
4641 		phba->hba_flag &= ~HBA_FW_DUMP_OP;
4642 		return rc;
4643 	}
4644 
4645 	/* Now physically reset the device */
4646 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4647 			"0389 Performing PCI function reset!\n");
4648 
4649 	/* Turn off parity checking and serr during the physical reset */
4650 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
4651 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4652 				"3205 PCI read Config failed\n");
4653 		return -EIO;
4654 	}
4655 
4656 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
4657 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4658 
4659 	/* Perform FCoE PCI function reset before freeing queue memory */
4660 	rc = lpfc_pci_function_reset(phba);
4661 
4662 	/* Restore PCI cmd register */
4663 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4664 
4665 	return rc;
4666 }
4667 
4668 /**
4669  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
4670  * @phba: Pointer to HBA context object.
4671  *
4672  * This function is called in the SLI initialization code path to
4673  * restart the HBA. The caller is not required to hold any lock.
4674  * This function writes MBX_RESTART mailbox command to the SLIM and
4675  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
4676  * function to free any pending commands. The function enables
4677  * POST only during the first initialization. The function returns zero.
4678  * The function does not guarantee completion of MBX_RESTART mailbox
4679  * command before the return of this function.
4680  **/
4681 static int
4682 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
4683 {
4684 	MAILBOX_t *mb;
4685 	struct lpfc_sli *psli;
4686 	volatile uint32_t word0;
4687 	void __iomem *to_slim;
4688 	uint32_t hba_aer_enabled;
4689 
4690 	spin_lock_irq(&phba->hbalock);
4691 
4692 	/* Take PCIe device Advanced Error Reporting (AER) state */
4693 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4694 
4695 	psli = &phba->sli;
4696 
4697 	/* Restart HBA */
4698 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4699 			"0337 Restart HBA Data: x%x x%x\n",
4700 			(phba->pport) ? phba->pport->port_state : 0,
4701 			psli->sli_flag);
4702 
4703 	word0 = 0;
4704 	mb = (MAILBOX_t *) &word0;
4705 	mb->mbxCommand = MBX_RESTART;
4706 	mb->mbxHc = 1;
4707 
4708 	lpfc_reset_barrier(phba);
4709 
4710 	to_slim = phba->MBslimaddr;
4711 	writel(*(uint32_t *) mb, to_slim);
4712 	readl(to_slim); /* flush */
4713 
4714 	/* Only skip post after fc_ffinit is completed */
4715 	if (phba->pport && phba->pport->port_state)
4716 		word0 = 1;	/* This is really setting up word1 */
4717 	else
4718 		word0 = 0;	/* This is really setting up word1 */
4719 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
4720 	writel(*(uint32_t *) mb, to_slim);
4721 	readl(to_slim); /* flush */
4722 
4723 	lpfc_sli_brdreset(phba);
4724 	if (phba->pport)
4725 		phba->pport->stopped = 0;
4726 	phba->link_state = LPFC_INIT_START;
4727 	phba->hba_flag = 0;
4728 	spin_unlock_irq(&phba->hbalock);
4729 
4730 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4731 	psli->stats_start = ktime_get_seconds();
4732 
4733 	/* Give the INITFF and Post time to settle. */
4734 	mdelay(100);
4735 
4736 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4737 	if (hba_aer_enabled)
4738 		pci_disable_pcie_error_reporting(phba->pcidev);
4739 
4740 	lpfc_hba_down_post(phba);
4741 
4742 	return 0;
4743 }
4744 
4745 /**
4746  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
4747  * @phba: Pointer to HBA context object.
4748  *
4749  * This function is called in the SLI initialization code path to restart
4750  * a SLI4 HBA. The caller is not required to hold any lock.
4751  * At the end of the function, it calls lpfc_hba_down_post function to
4752  * free any pending commands.
4753  **/
4754 static int
4755 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
4756 {
4757 	struct lpfc_sli *psli = &phba->sli;
4758 	uint32_t hba_aer_enabled;
4759 	int rc;
4760 
4761 	/* Restart HBA */
4762 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4763 			"0296 Restart HBA Data: x%x x%x\n",
4764 			phba->pport->port_state, psli->sli_flag);
4765 
4766 	/* Take PCIe device Advanced Error Reporting (AER) state */
4767 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4768 
4769 	rc = lpfc_sli4_brdreset(phba);
4770 	if (rc) {
4771 		phba->link_state = LPFC_HBA_ERROR;
4772 		goto hba_down_queue;
4773 	}
4774 
4775 	spin_lock_irq(&phba->hbalock);
4776 	phba->pport->stopped = 0;
4777 	phba->link_state = LPFC_INIT_START;
4778 	phba->hba_flag = 0;
4779 	spin_unlock_irq(&phba->hbalock);
4780 
4781 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4782 	psli->stats_start = ktime_get_seconds();
4783 
4784 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4785 	if (hba_aer_enabled)
4786 		pci_disable_pcie_error_reporting(phba->pcidev);
4787 
4788 hba_down_queue:
4789 	lpfc_hba_down_post(phba);
4790 	lpfc_sli4_queue_destroy(phba);
4791 
4792 	return rc;
4793 }
4794 
4795 /**
4796  * lpfc_sli_brdrestart - Wrapper func for restarting hba
4797  * @phba: Pointer to HBA context object.
4798  *
4799  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
4800  * API jump table function pointer from the lpfc_hba struct.
4801 **/
4802 int
4803 lpfc_sli_brdrestart(struct lpfc_hba *phba)
4804 {
4805 	return phba->lpfc_sli_brdrestart(phba);
4806 }
4807 
4808 /**
4809  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
4810  * @phba: Pointer to HBA context object.
4811  *
4812  * This function is called after a HBA restart to wait for successful
4813  * restart of the HBA. Successful restart of the HBA is indicated by
4814  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
4815  * iteration, the function will restart the HBA again. The function returns
4816  * zero if HBA successfully restarted else returns negative error code.
4817  **/
4818 int
4819 lpfc_sli_chipset_init(struct lpfc_hba *phba)
4820 {
4821 	uint32_t status, i = 0;
4822 
4823 	/* Read the HBA Host Status Register */
4824 	if (lpfc_readl(phba->HSregaddr, &status))
4825 		return -EIO;
4826 
4827 	/* Check status register to see what current state is */
4828 	i = 0;
4829 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
4830 
4831 		/* Check every 10ms for 10 retries, then every 100ms for 90
4832 		 * retries, then every 1 sec for 50 retires for a total of
4833 		 * ~60 seconds before reset the board again and check every
4834 		 * 1 sec for 50 retries. The up to 60 seconds before the
4835 		 * board ready is required by the Falcon FIPS zeroization
4836 		 * complete, and any reset the board in between shall cause
4837 		 * restart of zeroization, further delay the board ready.
4838 		 */
4839 		if (i++ >= 200) {
4840 			/* Adapter failed to init, timeout, status reg
4841 			   <status> */
4842 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4843 					"0436 Adapter failed to init, "
4844 					"timeout, status reg x%x, "
4845 					"FW Data: A8 x%x AC x%x\n", status,
4846 					readl(phba->MBslimaddr + 0xa8),
4847 					readl(phba->MBslimaddr + 0xac));
4848 			phba->link_state = LPFC_HBA_ERROR;
4849 			return -ETIMEDOUT;
4850 		}
4851 
4852 		/* Check to see if any errors occurred during init */
4853 		if (status & HS_FFERM) {
4854 			/* ERROR: During chipset initialization */
4855 			/* Adapter failed to init, chipset, status reg
4856 			   <status> */
4857 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4858 					"0437 Adapter failed to init, "
4859 					"chipset, status reg x%x, "
4860 					"FW Data: A8 x%x AC x%x\n", status,
4861 					readl(phba->MBslimaddr + 0xa8),
4862 					readl(phba->MBslimaddr + 0xac));
4863 			phba->link_state = LPFC_HBA_ERROR;
4864 			return -EIO;
4865 		}
4866 
4867 		if (i <= 10)
4868 			msleep(10);
4869 		else if (i <= 100)
4870 			msleep(100);
4871 		else
4872 			msleep(1000);
4873 
4874 		if (i == 150) {
4875 			/* Do post */
4876 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4877 			lpfc_sli_brdrestart(phba);
4878 		}
4879 		/* Read the HBA Host Status Register */
4880 		if (lpfc_readl(phba->HSregaddr, &status))
4881 			return -EIO;
4882 	}
4883 
4884 	/* Check to see if any errors occurred during init */
4885 	if (status & HS_FFERM) {
4886 		/* ERROR: During chipset initialization */
4887 		/* Adapter failed to init, chipset, status reg <status> */
4888 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4889 				"0438 Adapter failed to init, chipset, "
4890 				"status reg x%x, "
4891 				"FW Data: A8 x%x AC x%x\n", status,
4892 				readl(phba->MBslimaddr + 0xa8),
4893 				readl(phba->MBslimaddr + 0xac));
4894 		phba->link_state = LPFC_HBA_ERROR;
4895 		return -EIO;
4896 	}
4897 
4898 	/* Clear all interrupt enable conditions */
4899 	writel(0, phba->HCregaddr);
4900 	readl(phba->HCregaddr); /* flush */
4901 
4902 	/* setup host attn register */
4903 	writel(0xffffffff, phba->HAregaddr);
4904 	readl(phba->HAregaddr); /* flush */
4905 	return 0;
4906 }
4907 
4908 /**
4909  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
4910  *
4911  * This function calculates and returns the number of HBQs required to be
4912  * configured.
4913  **/
4914 int
4915 lpfc_sli_hbq_count(void)
4916 {
4917 	return ARRAY_SIZE(lpfc_hbq_defs);
4918 }
4919 
4920 /**
4921  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
4922  *
4923  * This function adds the number of hbq entries in every HBQ to get
4924  * the total number of hbq entries required for the HBA and returns
4925  * the total count.
4926  **/
4927 static int
4928 lpfc_sli_hbq_entry_count(void)
4929 {
4930 	int  hbq_count = lpfc_sli_hbq_count();
4931 	int  count = 0;
4932 	int  i;
4933 
4934 	for (i = 0; i < hbq_count; ++i)
4935 		count += lpfc_hbq_defs[i]->entry_count;
4936 	return count;
4937 }
4938 
4939 /**
4940  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
4941  *
4942  * This function calculates amount of memory required for all hbq entries
4943  * to be configured and returns the total memory required.
4944  **/
4945 int
4946 lpfc_sli_hbq_size(void)
4947 {
4948 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
4949 }
4950 
4951 /**
4952  * lpfc_sli_hbq_setup - configure and initialize HBQs
4953  * @phba: Pointer to HBA context object.
4954  *
4955  * This function is called during the SLI initialization to configure
4956  * all the HBQs and post buffers to the HBQ. The caller is not
4957  * required to hold any locks. This function will return zero if successful
4958  * else it will return negative error code.
4959  **/
4960 static int
4961 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
4962 {
4963 	int  hbq_count = lpfc_sli_hbq_count();
4964 	LPFC_MBOXQ_t *pmb;
4965 	MAILBOX_t *pmbox;
4966 	uint32_t hbqno;
4967 	uint32_t hbq_entry_index;
4968 
4969 				/* Get a Mailbox buffer to setup mailbox
4970 				 * commands for HBA initialization
4971 				 */
4972 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4973 
4974 	if (!pmb)
4975 		return -ENOMEM;
4976 
4977 	pmbox = &pmb->u.mb;
4978 
4979 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
4980 	phba->link_state = LPFC_INIT_MBX_CMDS;
4981 	phba->hbq_in_use = 1;
4982 
4983 	hbq_entry_index = 0;
4984 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
4985 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
4986 		phba->hbqs[hbqno].hbqPutIdx      = 0;
4987 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
4988 		phba->hbqs[hbqno].entry_count =
4989 			lpfc_hbq_defs[hbqno]->entry_count;
4990 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
4991 			hbq_entry_index, pmb);
4992 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
4993 
4994 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
4995 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
4996 			   mbxStatus <status>, ring <num> */
4997 
4998 			lpfc_printf_log(phba, KERN_ERR,
4999 					LOG_SLI | LOG_VPORT,
5000 					"1805 Adapter failed to init. "
5001 					"Data: x%x x%x x%x\n",
5002 					pmbox->mbxCommand,
5003 					pmbox->mbxStatus, hbqno);
5004 
5005 			phba->link_state = LPFC_HBA_ERROR;
5006 			mempool_free(pmb, phba->mbox_mem_pool);
5007 			return -ENXIO;
5008 		}
5009 	}
5010 	phba->hbq_count = hbq_count;
5011 
5012 	mempool_free(pmb, phba->mbox_mem_pool);
5013 
5014 	/* Initially populate or replenish the HBQs */
5015 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5016 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5017 	return 0;
5018 }
5019 
5020 /**
5021  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5022  * @phba: Pointer to HBA context object.
5023  *
5024  * This function is called during the SLI initialization to configure
5025  * all the HBQs and post buffers to the HBQ. The caller is not
5026  * required to hold any locks. This function will return zero if successful
5027  * else it will return negative error code.
5028  **/
5029 static int
5030 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5031 {
5032 	phba->hbq_in_use = 1;
5033 	/**
5034 	 * Specific case when the MDS diagnostics is enabled and supported.
5035 	 * The receive buffer count is truncated to manage the incoming
5036 	 * traffic.
5037 	 **/
5038 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5039 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5040 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5041 	else
5042 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5043 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5044 	phba->hbq_count = 1;
5045 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5046 	/* Initially populate or replenish the HBQs */
5047 	return 0;
5048 }
5049 
5050 /**
5051  * lpfc_sli_config_port - Issue config port mailbox command
5052  * @phba: Pointer to HBA context object.
5053  * @sli_mode: sli mode - 2/3
5054  *
5055  * This function is called by the sli initialization code path
5056  * to issue config_port mailbox command. This function restarts the
5057  * HBA firmware and issues a config_port mailbox command to configure
5058  * the SLI interface in the sli mode specified by sli_mode
5059  * variable. The caller is not required to hold any locks.
5060  * The function returns 0 if successful, else returns negative error
5061  * code.
5062  **/
5063 int
5064 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5065 {
5066 	LPFC_MBOXQ_t *pmb;
5067 	uint32_t resetcount = 0, rc = 0, done = 0;
5068 
5069 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5070 	if (!pmb) {
5071 		phba->link_state = LPFC_HBA_ERROR;
5072 		return -ENOMEM;
5073 	}
5074 
5075 	phba->sli_rev = sli_mode;
5076 	while (resetcount < 2 && !done) {
5077 		spin_lock_irq(&phba->hbalock);
5078 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5079 		spin_unlock_irq(&phba->hbalock);
5080 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5081 		lpfc_sli_brdrestart(phba);
5082 		rc = lpfc_sli_chipset_init(phba);
5083 		if (rc)
5084 			break;
5085 
5086 		spin_lock_irq(&phba->hbalock);
5087 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5088 		spin_unlock_irq(&phba->hbalock);
5089 		resetcount++;
5090 
5091 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5092 		 * value of 0 means the call was successful.  Any other
5093 		 * nonzero value is a failure, but if ERESTART is returned,
5094 		 * the driver may reset the HBA and try again.
5095 		 */
5096 		rc = lpfc_config_port_prep(phba);
5097 		if (rc == -ERESTART) {
5098 			phba->link_state = LPFC_LINK_UNKNOWN;
5099 			continue;
5100 		} else if (rc)
5101 			break;
5102 
5103 		phba->link_state = LPFC_INIT_MBX_CMDS;
5104 		lpfc_config_port(phba, pmb);
5105 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5106 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5107 					LPFC_SLI3_HBQ_ENABLED |
5108 					LPFC_SLI3_CRP_ENABLED |
5109 					LPFC_SLI3_DSS_ENABLED);
5110 		if (rc != MBX_SUCCESS) {
5111 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5112 				"0442 Adapter failed to init, mbxCmd x%x "
5113 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5114 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5115 			spin_lock_irq(&phba->hbalock);
5116 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5117 			spin_unlock_irq(&phba->hbalock);
5118 			rc = -ENXIO;
5119 		} else {
5120 			/* Allow asynchronous mailbox command to go through */
5121 			spin_lock_irq(&phba->hbalock);
5122 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5123 			spin_unlock_irq(&phba->hbalock);
5124 			done = 1;
5125 
5126 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5127 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5128 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5129 					"3110 Port did not grant ASABT\n");
5130 		}
5131 	}
5132 	if (!done) {
5133 		rc = -EINVAL;
5134 		goto do_prep_failed;
5135 	}
5136 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5137 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5138 			rc = -ENXIO;
5139 			goto do_prep_failed;
5140 		}
5141 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5142 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5143 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5144 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5145 				phba->max_vpi : phba->max_vports;
5146 
5147 		} else
5148 			phba->max_vpi = 0;
5149 		if (pmb->u.mb.un.varCfgPort.gerbm)
5150 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5151 		if (pmb->u.mb.un.varCfgPort.gcrp)
5152 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5153 
5154 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5155 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5156 
5157 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5158 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5159 				phba->cfg_enable_bg = 0;
5160 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5161 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5162 						"0443 Adapter did not grant "
5163 						"BlockGuard\n");
5164 			}
5165 		}
5166 	} else {
5167 		phba->hbq_get = NULL;
5168 		phba->port_gp = phba->mbox->us.s2.port;
5169 		phba->max_vpi = 0;
5170 	}
5171 do_prep_failed:
5172 	mempool_free(pmb, phba->mbox_mem_pool);
5173 	return rc;
5174 }
5175 
5176 
5177 /**
5178  * lpfc_sli_hba_setup - SLI initialization function
5179  * @phba: Pointer to HBA context object.
5180  *
5181  * This function is the main SLI initialization function. This function
5182  * is called by the HBA initialization code, HBA reset code and HBA
5183  * error attention handler code. Caller is not required to hold any
5184  * locks. This function issues config_port mailbox command to configure
5185  * the SLI, setup iocb rings and HBQ rings. In the end the function
5186  * calls the config_port_post function to issue init_link mailbox
5187  * command and to start the discovery. The function will return zero
5188  * if successful, else it will return negative error code.
5189  **/
5190 int
5191 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5192 {
5193 	uint32_t rc;
5194 	int  mode = 3, i;
5195 	int longs;
5196 
5197 	switch (phba->cfg_sli_mode) {
5198 	case 2:
5199 		if (phba->cfg_enable_npiv) {
5200 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
5201 				"1824 NPIV enabled: Override sli_mode "
5202 				"parameter (%d) to auto (0).\n",
5203 				phba->cfg_sli_mode);
5204 			break;
5205 		}
5206 		mode = 2;
5207 		break;
5208 	case 0:
5209 	case 3:
5210 		break;
5211 	default:
5212 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
5213 				"1819 Unrecognized sli_mode parameter: %d.\n",
5214 				phba->cfg_sli_mode);
5215 
5216 		break;
5217 	}
5218 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5219 
5220 	rc = lpfc_sli_config_port(phba, mode);
5221 
5222 	if (rc && phba->cfg_sli_mode == 3)
5223 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
5224 				"1820 Unable to select SLI-3.  "
5225 				"Not supported by adapter.\n");
5226 	if (rc && mode != 2)
5227 		rc = lpfc_sli_config_port(phba, 2);
5228 	else if (rc && mode == 2)
5229 		rc = lpfc_sli_config_port(phba, 3);
5230 	if (rc)
5231 		goto lpfc_sli_hba_setup_error;
5232 
5233 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
5234 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
5235 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
5236 		if (!rc) {
5237 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5238 					"2709 This device supports "
5239 					"Advanced Error Reporting (AER)\n");
5240 			spin_lock_irq(&phba->hbalock);
5241 			phba->hba_flag |= HBA_AER_ENABLED;
5242 			spin_unlock_irq(&phba->hbalock);
5243 		} else {
5244 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5245 					"2708 This device does not support "
5246 					"Advanced Error Reporting (AER): %d\n",
5247 					rc);
5248 			phba->cfg_aer_support = 0;
5249 		}
5250 	}
5251 
5252 	if (phba->sli_rev == 3) {
5253 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5254 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5255 	} else {
5256 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5257 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5258 		phba->sli3_options = 0;
5259 	}
5260 
5261 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5262 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5263 			phba->sli_rev, phba->max_vpi);
5264 	rc = lpfc_sli_ring_map(phba);
5265 
5266 	if (rc)
5267 		goto lpfc_sli_hba_setup_error;
5268 
5269 	/* Initialize VPIs. */
5270 	if (phba->sli_rev == LPFC_SLI_REV3) {
5271 		/*
5272 		 * The VPI bitmask and physical ID array are allocated
5273 		 * and initialized once only - at driver load.  A port
5274 		 * reset doesn't need to reinitialize this memory.
5275 		 */
5276 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5277 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5278 			phba->vpi_bmask = kcalloc(longs,
5279 						  sizeof(unsigned long),
5280 						  GFP_KERNEL);
5281 			if (!phba->vpi_bmask) {
5282 				rc = -ENOMEM;
5283 				goto lpfc_sli_hba_setup_error;
5284 			}
5285 
5286 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5287 						sizeof(uint16_t),
5288 						GFP_KERNEL);
5289 			if (!phba->vpi_ids) {
5290 				kfree(phba->vpi_bmask);
5291 				rc = -ENOMEM;
5292 				goto lpfc_sli_hba_setup_error;
5293 			}
5294 			for (i = 0; i < phba->max_vpi; i++)
5295 				phba->vpi_ids[i] = i;
5296 		}
5297 	}
5298 
5299 	/* Init HBQs */
5300 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5301 		rc = lpfc_sli_hbq_setup(phba);
5302 		if (rc)
5303 			goto lpfc_sli_hba_setup_error;
5304 	}
5305 	spin_lock_irq(&phba->hbalock);
5306 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5307 	spin_unlock_irq(&phba->hbalock);
5308 
5309 	rc = lpfc_config_port_post(phba);
5310 	if (rc)
5311 		goto lpfc_sli_hba_setup_error;
5312 
5313 	return rc;
5314 
5315 lpfc_sli_hba_setup_error:
5316 	phba->link_state = LPFC_HBA_ERROR;
5317 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5318 			"0445 Firmware initialization failed\n");
5319 	return rc;
5320 }
5321 
5322 /**
5323  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5324  * @phba: Pointer to HBA context object.
5325  * @mboxq: mailbox pointer.
5326  * This function issue a dump mailbox command to read config region
5327  * 23 and parse the records in the region and populate driver
5328  * data structure.
5329  **/
5330 static int
5331 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5332 {
5333 	LPFC_MBOXQ_t *mboxq;
5334 	struct lpfc_dmabuf *mp;
5335 	struct lpfc_mqe *mqe;
5336 	uint32_t data_length;
5337 	int rc;
5338 
5339 	/* Program the default value of vlan_id and fc_map */
5340 	phba->valid_vlan = 0;
5341 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5342 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5343 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5344 
5345 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5346 	if (!mboxq)
5347 		return -ENOMEM;
5348 
5349 	mqe = &mboxq->u.mqe;
5350 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5351 		rc = -ENOMEM;
5352 		goto out_free_mboxq;
5353 	}
5354 
5355 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5356 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5357 
5358 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5359 			"(%d):2571 Mailbox cmd x%x Status x%x "
5360 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5361 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5362 			"CQ: x%x x%x x%x x%x\n",
5363 			mboxq->vport ? mboxq->vport->vpi : 0,
5364 			bf_get(lpfc_mqe_command, mqe),
5365 			bf_get(lpfc_mqe_status, mqe),
5366 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5367 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5368 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5369 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5370 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5371 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5372 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5373 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5374 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5375 			mboxq->mcqe.word0,
5376 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5377 			mboxq->mcqe.trailer);
5378 
5379 	if (rc) {
5380 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5381 		kfree(mp);
5382 		rc = -EIO;
5383 		goto out_free_mboxq;
5384 	}
5385 	data_length = mqe->un.mb_words[5];
5386 	if (data_length > DMP_RGN23_SIZE) {
5387 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5388 		kfree(mp);
5389 		rc = -EIO;
5390 		goto out_free_mboxq;
5391 	}
5392 
5393 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5394 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
5395 	kfree(mp);
5396 	rc = 0;
5397 
5398 out_free_mboxq:
5399 	mempool_free(mboxq, phba->mbox_mem_pool);
5400 	return rc;
5401 }
5402 
5403 /**
5404  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5405  * @phba: pointer to lpfc hba data structure.
5406  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5407  * @vpd: pointer to the memory to hold resulting port vpd data.
5408  * @vpd_size: On input, the number of bytes allocated to @vpd.
5409  *	      On output, the number of data bytes in @vpd.
5410  *
5411  * This routine executes a READ_REV SLI4 mailbox command.  In
5412  * addition, this routine gets the port vpd data.
5413  *
5414  * Return codes
5415  * 	0 - successful
5416  * 	-ENOMEM - could not allocated memory.
5417  **/
5418 static int
5419 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5420 		    uint8_t *vpd, uint32_t *vpd_size)
5421 {
5422 	int rc = 0;
5423 	uint32_t dma_size;
5424 	struct lpfc_dmabuf *dmabuf;
5425 	struct lpfc_mqe *mqe;
5426 
5427 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5428 	if (!dmabuf)
5429 		return -ENOMEM;
5430 
5431 	/*
5432 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5433 	 * mailbox command.
5434 	 */
5435 	dma_size = *vpd_size;
5436 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5437 					  &dmabuf->phys, GFP_KERNEL);
5438 	if (!dmabuf->virt) {
5439 		kfree(dmabuf);
5440 		return -ENOMEM;
5441 	}
5442 
5443 	/*
5444 	 * The SLI4 implementation of READ_REV conflicts at word1,
5445 	 * bits 31:16 and SLI4 adds vpd functionality not present
5446 	 * in SLI3.  This code corrects the conflicts.
5447 	 */
5448 	lpfc_read_rev(phba, mboxq);
5449 	mqe = &mboxq->u.mqe;
5450 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5451 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5452 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5453 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5454 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5455 
5456 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5457 	if (rc) {
5458 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5459 				  dmabuf->virt, dmabuf->phys);
5460 		kfree(dmabuf);
5461 		return -EIO;
5462 	}
5463 
5464 	/*
5465 	 * The available vpd length cannot be bigger than the
5466 	 * DMA buffer passed to the port.  Catch the less than
5467 	 * case and update the caller's size.
5468 	 */
5469 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5470 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5471 
5472 	memcpy(vpd, dmabuf->virt, *vpd_size);
5473 
5474 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5475 			  dmabuf->virt, dmabuf->phys);
5476 	kfree(dmabuf);
5477 	return 0;
5478 }
5479 
5480 /**
5481  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5482  * @phba: pointer to lpfc hba data structure.
5483  *
5484  * This routine retrieves SLI4 device physical port name this PCI function
5485  * is attached to.
5486  *
5487  * Return codes
5488  *      0 - successful
5489  *      otherwise - failed to retrieve controller attributes
5490  **/
5491 static int
5492 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5493 {
5494 	LPFC_MBOXQ_t *mboxq;
5495 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5496 	struct lpfc_controller_attribute *cntl_attr;
5497 	void *virtaddr = NULL;
5498 	uint32_t alloclen, reqlen;
5499 	uint32_t shdr_status, shdr_add_status;
5500 	union lpfc_sli4_cfg_shdr *shdr;
5501 	int rc;
5502 
5503 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5504 	if (!mboxq)
5505 		return -ENOMEM;
5506 
5507 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5508 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5509 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5510 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5511 			LPFC_SLI4_MBX_NEMBED);
5512 
5513 	if (alloclen < reqlen) {
5514 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5515 				"3084 Allocated DMA memory size (%d) is "
5516 				"less than the requested DMA memory size "
5517 				"(%d)\n", alloclen, reqlen);
5518 		rc = -ENOMEM;
5519 		goto out_free_mboxq;
5520 	}
5521 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5522 	virtaddr = mboxq->sge_array->addr[0];
5523 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5524 	shdr = &mbx_cntl_attr->cfg_shdr;
5525 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5526 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5527 	if (shdr_status || shdr_add_status || rc) {
5528 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5529 				"3085 Mailbox x%x (x%x/x%x) failed, "
5530 				"rc:x%x, status:x%x, add_status:x%x\n",
5531 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5532 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5533 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5534 				rc, shdr_status, shdr_add_status);
5535 		rc = -ENXIO;
5536 		goto out_free_mboxq;
5537 	}
5538 
5539 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5540 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5541 	phba->sli4_hba.lnk_info.lnk_tp =
5542 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5543 	phba->sli4_hba.lnk_info.lnk_no =
5544 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5545 
5546 	memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
5547 	strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
5548 		sizeof(phba->BIOSVersion));
5549 
5550 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5551 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s\n",
5552 			phba->sli4_hba.lnk_info.lnk_tp,
5553 			phba->sli4_hba.lnk_info.lnk_no,
5554 			phba->BIOSVersion);
5555 out_free_mboxq:
5556 	if (rc != MBX_TIMEOUT) {
5557 		if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5558 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
5559 		else
5560 			mempool_free(mboxq, phba->mbox_mem_pool);
5561 	}
5562 	return rc;
5563 }
5564 
5565 /**
5566  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
5567  * @phba: pointer to lpfc hba data structure.
5568  *
5569  * This routine retrieves SLI4 device physical port name this PCI function
5570  * is attached to.
5571  *
5572  * Return codes
5573  *      0 - successful
5574  *      otherwise - failed to retrieve physical port name
5575  **/
5576 static int
5577 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
5578 {
5579 	LPFC_MBOXQ_t *mboxq;
5580 	struct lpfc_mbx_get_port_name *get_port_name;
5581 	uint32_t shdr_status, shdr_add_status;
5582 	union lpfc_sli4_cfg_shdr *shdr;
5583 	char cport_name = 0;
5584 	int rc;
5585 
5586 	/* We assume nothing at this point */
5587 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5588 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
5589 
5590 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5591 	if (!mboxq)
5592 		return -ENOMEM;
5593 	/* obtain link type and link number via READ_CONFIG */
5594 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5595 	lpfc_sli4_read_config(phba);
5596 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
5597 		goto retrieve_ppname;
5598 
5599 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
5600 	rc = lpfc_sli4_get_ctl_attr(phba);
5601 	if (rc)
5602 		goto out_free_mboxq;
5603 
5604 retrieve_ppname:
5605 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5606 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
5607 		sizeof(struct lpfc_mbx_get_port_name) -
5608 		sizeof(struct lpfc_sli4_cfg_mhdr),
5609 		LPFC_SLI4_MBX_EMBED);
5610 	get_port_name = &mboxq->u.mqe.un.get_port_name;
5611 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5612 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
5613 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
5614 		phba->sli4_hba.lnk_info.lnk_tp);
5615 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5616 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5617 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5618 	if (shdr_status || shdr_add_status || rc) {
5619 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5620 				"3087 Mailbox x%x (x%x/x%x) failed: "
5621 				"rc:x%x, status:x%x, add_status:x%x\n",
5622 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5623 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5624 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5625 				rc, shdr_status, shdr_add_status);
5626 		rc = -ENXIO;
5627 		goto out_free_mboxq;
5628 	}
5629 	switch (phba->sli4_hba.lnk_info.lnk_no) {
5630 	case LPFC_LINK_NUMBER_0:
5631 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
5632 				&get_port_name->u.response);
5633 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5634 		break;
5635 	case LPFC_LINK_NUMBER_1:
5636 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
5637 				&get_port_name->u.response);
5638 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5639 		break;
5640 	case LPFC_LINK_NUMBER_2:
5641 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
5642 				&get_port_name->u.response);
5643 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5644 		break;
5645 	case LPFC_LINK_NUMBER_3:
5646 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
5647 				&get_port_name->u.response);
5648 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5649 		break;
5650 	default:
5651 		break;
5652 	}
5653 
5654 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
5655 		phba->Port[0] = cport_name;
5656 		phba->Port[1] = '\0';
5657 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5658 				"3091 SLI get port name: %s\n", phba->Port);
5659 	}
5660 
5661 out_free_mboxq:
5662 	if (rc != MBX_TIMEOUT) {
5663 		if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5664 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
5665 		else
5666 			mempool_free(mboxq, phba->mbox_mem_pool);
5667 	}
5668 	return rc;
5669 }
5670 
5671 /**
5672  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
5673  * @phba: pointer to lpfc hba data structure.
5674  *
5675  * This routine is called to explicitly arm the SLI4 device's completion and
5676  * event queues
5677  **/
5678 static void
5679 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
5680 {
5681 	int qidx;
5682 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
5683 	struct lpfc_sli4_hdw_queue *qp;
5684 	struct lpfc_queue *eq;
5685 
5686 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
5687 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
5688 	if (sli4_hba->nvmels_cq)
5689 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
5690 					   LPFC_QUEUE_REARM);
5691 
5692 	if (sli4_hba->hdwq) {
5693 		/* Loop thru all Hardware Queues */
5694 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
5695 			qp = &sli4_hba->hdwq[qidx];
5696 			/* ARM the corresponding CQ */
5697 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
5698 						LPFC_QUEUE_REARM);
5699 		}
5700 
5701 		/* Loop thru all IRQ vectors */
5702 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
5703 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
5704 			/* ARM the corresponding EQ */
5705 			sli4_hba->sli4_write_eq_db(phba, eq,
5706 						   0, LPFC_QUEUE_REARM);
5707 		}
5708 	}
5709 
5710 	if (phba->nvmet_support) {
5711 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
5712 			sli4_hba->sli4_write_cq_db(phba,
5713 				sli4_hba->nvmet_cqset[qidx], 0,
5714 				LPFC_QUEUE_REARM);
5715 		}
5716 	}
5717 }
5718 
5719 /**
5720  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
5721  * @phba: Pointer to HBA context object.
5722  * @type: The resource extent type.
5723  * @extnt_count: buffer to hold port available extent count.
5724  * @extnt_size: buffer to hold element count per extent.
5725  *
5726  * This function calls the port and retrievs the number of available
5727  * extents and their size for a particular extent type.
5728  *
5729  * Returns: 0 if successful.  Nonzero otherwise.
5730  **/
5731 int
5732 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
5733 			       uint16_t *extnt_count, uint16_t *extnt_size)
5734 {
5735 	int rc = 0;
5736 	uint32_t length;
5737 	uint32_t mbox_tmo;
5738 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
5739 	LPFC_MBOXQ_t *mbox;
5740 
5741 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5742 	if (!mbox)
5743 		return -ENOMEM;
5744 
5745 	/* Find out how many extents are available for this resource type */
5746 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
5747 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5748 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5749 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
5750 			 length, LPFC_SLI4_MBX_EMBED);
5751 
5752 	/* Send an extents count of 0 - the GET doesn't use it. */
5753 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5754 					LPFC_SLI4_MBX_EMBED);
5755 	if (unlikely(rc)) {
5756 		rc = -EIO;
5757 		goto err_exit;
5758 	}
5759 
5760 	if (!phba->sli4_hba.intr_enable)
5761 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5762 	else {
5763 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5764 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5765 	}
5766 	if (unlikely(rc)) {
5767 		rc = -EIO;
5768 		goto err_exit;
5769 	}
5770 
5771 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
5772 	if (bf_get(lpfc_mbox_hdr_status,
5773 		   &rsrc_info->header.cfg_shdr.response)) {
5774 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5775 				"2930 Failed to get resource extents "
5776 				"Status 0x%x Add'l Status 0x%x\n",
5777 				bf_get(lpfc_mbox_hdr_status,
5778 				       &rsrc_info->header.cfg_shdr.response),
5779 				bf_get(lpfc_mbox_hdr_add_status,
5780 				       &rsrc_info->header.cfg_shdr.response));
5781 		rc = -EIO;
5782 		goto err_exit;
5783 	}
5784 
5785 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
5786 			      &rsrc_info->u.rsp);
5787 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
5788 			     &rsrc_info->u.rsp);
5789 
5790 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5791 			"3162 Retrieved extents type-%d from port: count:%d, "
5792 			"size:%d\n", type, *extnt_count, *extnt_size);
5793 
5794 err_exit:
5795 	mempool_free(mbox, phba->mbox_mem_pool);
5796 	return rc;
5797 }
5798 
5799 /**
5800  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
5801  * @phba: Pointer to HBA context object.
5802  * @type: The extent type to check.
5803  *
5804  * This function reads the current available extents from the port and checks
5805  * if the extent count or extent size has changed since the last access.
5806  * Callers use this routine post port reset to understand if there is a
5807  * extent reprovisioning requirement.
5808  *
5809  * Returns:
5810  *   -Error: error indicates problem.
5811  *   1: Extent count or size has changed.
5812  *   0: No changes.
5813  **/
5814 static int
5815 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
5816 {
5817 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
5818 	uint16_t size_diff, rsrc_ext_size;
5819 	int rc = 0;
5820 	struct lpfc_rsrc_blks *rsrc_entry;
5821 	struct list_head *rsrc_blk_list = NULL;
5822 
5823 	size_diff = 0;
5824 	curr_ext_cnt = 0;
5825 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5826 					    &rsrc_ext_cnt,
5827 					    &rsrc_ext_size);
5828 	if (unlikely(rc))
5829 		return -EIO;
5830 
5831 	switch (type) {
5832 	case LPFC_RSC_TYPE_FCOE_RPI:
5833 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5834 		break;
5835 	case LPFC_RSC_TYPE_FCOE_VPI:
5836 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
5837 		break;
5838 	case LPFC_RSC_TYPE_FCOE_XRI:
5839 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5840 		break;
5841 	case LPFC_RSC_TYPE_FCOE_VFI:
5842 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5843 		break;
5844 	default:
5845 		break;
5846 	}
5847 
5848 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
5849 		curr_ext_cnt++;
5850 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
5851 			size_diff++;
5852 	}
5853 
5854 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
5855 		rc = 1;
5856 
5857 	return rc;
5858 }
5859 
5860 /**
5861  * lpfc_sli4_cfg_post_extnts -
5862  * @phba: Pointer to HBA context object.
5863  * @extnt_cnt - number of available extents.
5864  * @type - the extent type (rpi, xri, vfi, vpi).
5865  * @emb - buffer to hold either MBX_EMBED or MBX_NEMBED operation.
5866  * @mbox - pointer to the caller's allocated mailbox structure.
5867  *
5868  * This function executes the extents allocation request.  It also
5869  * takes care of the amount of memory needed to allocate or get the
5870  * allocated extents. It is the caller's responsibility to evaluate
5871  * the response.
5872  *
5873  * Returns:
5874  *   -Error:  Error value describes the condition found.
5875  *   0: if successful
5876  **/
5877 static int
5878 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
5879 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
5880 {
5881 	int rc = 0;
5882 	uint32_t req_len;
5883 	uint32_t emb_len;
5884 	uint32_t alloc_len, mbox_tmo;
5885 
5886 	/* Calculate the total requested length of the dma memory */
5887 	req_len = extnt_cnt * sizeof(uint16_t);
5888 
5889 	/*
5890 	 * Calculate the size of an embedded mailbox.  The uint32_t
5891 	 * accounts for extents-specific word.
5892 	 */
5893 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
5894 		sizeof(uint32_t);
5895 
5896 	/*
5897 	 * Presume the allocation and response will fit into an embedded
5898 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
5899 	 */
5900 	*emb = LPFC_SLI4_MBX_EMBED;
5901 	if (req_len > emb_len) {
5902 		req_len = extnt_cnt * sizeof(uint16_t) +
5903 			sizeof(union lpfc_sli4_cfg_shdr) +
5904 			sizeof(uint32_t);
5905 		*emb = LPFC_SLI4_MBX_NEMBED;
5906 	}
5907 
5908 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5909 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
5910 				     req_len, *emb);
5911 	if (alloc_len < req_len) {
5912 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5913 			"2982 Allocated DMA memory size (x%x) is "
5914 			"less than the requested DMA memory "
5915 			"size (x%x)\n", alloc_len, req_len);
5916 		return -ENOMEM;
5917 	}
5918 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
5919 	if (unlikely(rc))
5920 		return -EIO;
5921 
5922 	if (!phba->sli4_hba.intr_enable)
5923 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5924 	else {
5925 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5926 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5927 	}
5928 
5929 	if (unlikely(rc))
5930 		rc = -EIO;
5931 	return rc;
5932 }
5933 
5934 /**
5935  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
5936  * @phba: Pointer to HBA context object.
5937  * @type:  The resource extent type to allocate.
5938  *
5939  * This function allocates the number of elements for the specified
5940  * resource type.
5941  **/
5942 static int
5943 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
5944 {
5945 	bool emb = false;
5946 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
5947 	uint16_t rsrc_id, rsrc_start, j, k;
5948 	uint16_t *ids;
5949 	int i, rc;
5950 	unsigned long longs;
5951 	unsigned long *bmask;
5952 	struct lpfc_rsrc_blks *rsrc_blks;
5953 	LPFC_MBOXQ_t *mbox;
5954 	uint32_t length;
5955 	struct lpfc_id_range *id_array = NULL;
5956 	void *virtaddr = NULL;
5957 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
5958 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
5959 	struct list_head *ext_blk_list;
5960 
5961 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5962 					    &rsrc_cnt,
5963 					    &rsrc_size);
5964 	if (unlikely(rc))
5965 		return -EIO;
5966 
5967 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
5968 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5969 			"3009 No available Resource Extents "
5970 			"for resource type 0x%x: Count: 0x%x, "
5971 			"Size 0x%x\n", type, rsrc_cnt,
5972 			rsrc_size);
5973 		return -ENOMEM;
5974 	}
5975 
5976 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
5977 			"2903 Post resource extents type-0x%x: "
5978 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
5979 
5980 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5981 	if (!mbox)
5982 		return -ENOMEM;
5983 
5984 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
5985 	if (unlikely(rc)) {
5986 		rc = -EIO;
5987 		goto err_exit;
5988 	}
5989 
5990 	/*
5991 	 * Figure out where the response is located.  Then get local pointers
5992 	 * to the response data.  The port does not guarantee to respond to
5993 	 * all extents counts request so update the local variable with the
5994 	 * allocated count from the port.
5995 	 */
5996 	if (emb == LPFC_SLI4_MBX_EMBED) {
5997 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
5998 		id_array = &rsrc_ext->u.rsp.id[0];
5999 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6000 	} else {
6001 		virtaddr = mbox->sge_array->addr[0];
6002 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6003 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6004 		id_array = &n_rsrc->id;
6005 	}
6006 
6007 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6008 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6009 
6010 	/*
6011 	 * Based on the resource size and count, correct the base and max
6012 	 * resource values.
6013 	 */
6014 	length = sizeof(struct lpfc_rsrc_blks);
6015 	switch (type) {
6016 	case LPFC_RSC_TYPE_FCOE_RPI:
6017 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6018 						   sizeof(unsigned long),
6019 						   GFP_KERNEL);
6020 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6021 			rc = -ENOMEM;
6022 			goto err_exit;
6023 		}
6024 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6025 						 sizeof(uint16_t),
6026 						 GFP_KERNEL);
6027 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6028 			kfree(phba->sli4_hba.rpi_bmask);
6029 			rc = -ENOMEM;
6030 			goto err_exit;
6031 		}
6032 
6033 		/*
6034 		 * The next_rpi was initialized with the maximum available
6035 		 * count but the port may allocate a smaller number.  Catch
6036 		 * that case and update the next_rpi.
6037 		 */
6038 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6039 
6040 		/* Initialize local ptrs for common extent processing later. */
6041 		bmask = phba->sli4_hba.rpi_bmask;
6042 		ids = phba->sli4_hba.rpi_ids;
6043 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6044 		break;
6045 	case LPFC_RSC_TYPE_FCOE_VPI:
6046 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6047 					  GFP_KERNEL);
6048 		if (unlikely(!phba->vpi_bmask)) {
6049 			rc = -ENOMEM;
6050 			goto err_exit;
6051 		}
6052 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6053 					 GFP_KERNEL);
6054 		if (unlikely(!phba->vpi_ids)) {
6055 			kfree(phba->vpi_bmask);
6056 			rc = -ENOMEM;
6057 			goto err_exit;
6058 		}
6059 
6060 		/* Initialize local ptrs for common extent processing later. */
6061 		bmask = phba->vpi_bmask;
6062 		ids = phba->vpi_ids;
6063 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6064 		break;
6065 	case LPFC_RSC_TYPE_FCOE_XRI:
6066 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6067 						   sizeof(unsigned long),
6068 						   GFP_KERNEL);
6069 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6070 			rc = -ENOMEM;
6071 			goto err_exit;
6072 		}
6073 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6074 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6075 						 sizeof(uint16_t),
6076 						 GFP_KERNEL);
6077 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6078 			kfree(phba->sli4_hba.xri_bmask);
6079 			rc = -ENOMEM;
6080 			goto err_exit;
6081 		}
6082 
6083 		/* Initialize local ptrs for common extent processing later. */
6084 		bmask = phba->sli4_hba.xri_bmask;
6085 		ids = phba->sli4_hba.xri_ids;
6086 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6087 		break;
6088 	case LPFC_RSC_TYPE_FCOE_VFI:
6089 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6090 						   sizeof(unsigned long),
6091 						   GFP_KERNEL);
6092 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6093 			rc = -ENOMEM;
6094 			goto err_exit;
6095 		}
6096 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6097 						 sizeof(uint16_t),
6098 						 GFP_KERNEL);
6099 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6100 			kfree(phba->sli4_hba.vfi_bmask);
6101 			rc = -ENOMEM;
6102 			goto err_exit;
6103 		}
6104 
6105 		/* Initialize local ptrs for common extent processing later. */
6106 		bmask = phba->sli4_hba.vfi_bmask;
6107 		ids = phba->sli4_hba.vfi_ids;
6108 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6109 		break;
6110 	default:
6111 		/* Unsupported Opcode.  Fail call. */
6112 		id_array = NULL;
6113 		bmask = NULL;
6114 		ids = NULL;
6115 		ext_blk_list = NULL;
6116 		goto err_exit;
6117 	}
6118 
6119 	/*
6120 	 * Complete initializing the extent configuration with the
6121 	 * allocated ids assigned to this function.  The bitmask serves
6122 	 * as an index into the array and manages the available ids.  The
6123 	 * array just stores the ids communicated to the port via the wqes.
6124 	 */
6125 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6126 		if ((i % 2) == 0)
6127 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6128 					 &id_array[k]);
6129 		else
6130 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6131 					 &id_array[k]);
6132 
6133 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6134 		if (unlikely(!rsrc_blks)) {
6135 			rc = -ENOMEM;
6136 			kfree(bmask);
6137 			kfree(ids);
6138 			goto err_exit;
6139 		}
6140 		rsrc_blks->rsrc_start = rsrc_id;
6141 		rsrc_blks->rsrc_size = rsrc_size;
6142 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6143 		rsrc_start = rsrc_id;
6144 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6145 			phba->sli4_hba.io_xri_start = rsrc_start +
6146 				lpfc_sli4_get_iocb_cnt(phba);
6147 		}
6148 
6149 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6150 			ids[j] = rsrc_id;
6151 			rsrc_id++;
6152 			j++;
6153 		}
6154 		/* Entire word processed.  Get next word.*/
6155 		if ((i % 2) == 1)
6156 			k++;
6157 	}
6158  err_exit:
6159 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6160 	return rc;
6161 }
6162 
6163 
6164 
6165 /**
6166  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6167  * @phba: Pointer to HBA context object.
6168  * @type: the extent's type.
6169  *
6170  * This function deallocates all extents of a particular resource type.
6171  * SLI4 does not allow for deallocating a particular extent range.  It
6172  * is the caller's responsibility to release all kernel memory resources.
6173  **/
6174 static int
6175 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6176 {
6177 	int rc;
6178 	uint32_t length, mbox_tmo = 0;
6179 	LPFC_MBOXQ_t *mbox;
6180 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6181 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6182 
6183 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6184 	if (!mbox)
6185 		return -ENOMEM;
6186 
6187 	/*
6188 	 * This function sends an embedded mailbox because it only sends the
6189 	 * the resource type.  All extents of this type are released by the
6190 	 * port.
6191 	 */
6192 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6193 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6194 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6195 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6196 			 length, LPFC_SLI4_MBX_EMBED);
6197 
6198 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6199 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6200 					LPFC_SLI4_MBX_EMBED);
6201 	if (unlikely(rc)) {
6202 		rc = -EIO;
6203 		goto out_free_mbox;
6204 	}
6205 	if (!phba->sli4_hba.intr_enable)
6206 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6207 	else {
6208 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6209 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6210 	}
6211 	if (unlikely(rc)) {
6212 		rc = -EIO;
6213 		goto out_free_mbox;
6214 	}
6215 
6216 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6217 	if (bf_get(lpfc_mbox_hdr_status,
6218 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6219 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
6220 				"2919 Failed to release resource extents "
6221 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6222 				"Resource memory not released.\n",
6223 				type,
6224 				bf_get(lpfc_mbox_hdr_status,
6225 				    &dealloc_rsrc->header.cfg_shdr.response),
6226 				bf_get(lpfc_mbox_hdr_add_status,
6227 				    &dealloc_rsrc->header.cfg_shdr.response));
6228 		rc = -EIO;
6229 		goto out_free_mbox;
6230 	}
6231 
6232 	/* Release kernel memory resources for the specific type. */
6233 	switch (type) {
6234 	case LPFC_RSC_TYPE_FCOE_VPI:
6235 		kfree(phba->vpi_bmask);
6236 		kfree(phba->vpi_ids);
6237 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6238 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6239 				    &phba->lpfc_vpi_blk_list, list) {
6240 			list_del_init(&rsrc_blk->list);
6241 			kfree(rsrc_blk);
6242 		}
6243 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6244 		break;
6245 	case LPFC_RSC_TYPE_FCOE_XRI:
6246 		kfree(phba->sli4_hba.xri_bmask);
6247 		kfree(phba->sli4_hba.xri_ids);
6248 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6249 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6250 			list_del_init(&rsrc_blk->list);
6251 			kfree(rsrc_blk);
6252 		}
6253 		break;
6254 	case LPFC_RSC_TYPE_FCOE_VFI:
6255 		kfree(phba->sli4_hba.vfi_bmask);
6256 		kfree(phba->sli4_hba.vfi_ids);
6257 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6258 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6259 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6260 			list_del_init(&rsrc_blk->list);
6261 			kfree(rsrc_blk);
6262 		}
6263 		break;
6264 	case LPFC_RSC_TYPE_FCOE_RPI:
6265 		/* RPI bitmask and physical id array are cleaned up earlier. */
6266 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6267 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6268 			list_del_init(&rsrc_blk->list);
6269 			kfree(rsrc_blk);
6270 		}
6271 		break;
6272 	default:
6273 		break;
6274 	}
6275 
6276 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6277 
6278  out_free_mbox:
6279 	mempool_free(mbox, phba->mbox_mem_pool);
6280 	return rc;
6281 }
6282 
6283 static void
6284 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6285 		  uint32_t feature)
6286 {
6287 	uint32_t len;
6288 
6289 	len = sizeof(struct lpfc_mbx_set_feature) -
6290 		sizeof(struct lpfc_sli4_cfg_mhdr);
6291 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6292 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6293 			 LPFC_SLI4_MBX_EMBED);
6294 
6295 	switch (feature) {
6296 	case LPFC_SET_UE_RECOVERY:
6297 		bf_set(lpfc_mbx_set_feature_UER,
6298 		       &mbox->u.mqe.un.set_feature, 1);
6299 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6300 		mbox->u.mqe.un.set_feature.param_len = 8;
6301 		break;
6302 	case LPFC_SET_MDS_DIAGS:
6303 		bf_set(lpfc_mbx_set_feature_mds,
6304 		       &mbox->u.mqe.un.set_feature, 1);
6305 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6306 		       &mbox->u.mqe.un.set_feature, 1);
6307 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6308 		mbox->u.mqe.un.set_feature.param_len = 8;
6309 		break;
6310 	case LPFC_SET_DUAL_DUMP:
6311 		bf_set(lpfc_mbx_set_feature_dd,
6312 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6313 		bf_set(lpfc_mbx_set_feature_ddquery,
6314 		       &mbox->u.mqe.un.set_feature, 0);
6315 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6316 		mbox->u.mqe.un.set_feature.param_len = 4;
6317 		break;
6318 	}
6319 
6320 	return;
6321 }
6322 
6323 /**
6324  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6325  * @phba: Pointer to HBA context object.
6326  *
6327  * Disable FW logging into host memory on the adapter. To
6328  * be done before reading logs from the host memory.
6329  **/
6330 void
6331 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6332 {
6333 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6334 
6335 	spin_lock_irq(&phba->hbalock);
6336 	ras_fwlog->state = INACTIVE;
6337 	spin_unlock_irq(&phba->hbalock);
6338 
6339 	/* Disable FW logging to host memory */
6340 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6341 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6342 
6343 	/* Wait 10ms for firmware to stop using DMA buffer */
6344 	usleep_range(10 * 1000, 20 * 1000);
6345 }
6346 
6347 /**
6348  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6349  * @phba: Pointer to HBA context object.
6350  *
6351  * This function is called to free memory allocated for RAS FW logging
6352  * support in the driver.
6353  **/
6354 void
6355 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6356 {
6357 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6358 	struct lpfc_dmabuf *dmabuf, *next;
6359 
6360 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6361 		list_for_each_entry_safe(dmabuf, next,
6362 				    &ras_fwlog->fwlog_buff_list,
6363 				    list) {
6364 			list_del(&dmabuf->list);
6365 			dma_free_coherent(&phba->pcidev->dev,
6366 					  LPFC_RAS_MAX_ENTRY_SIZE,
6367 					  dmabuf->virt, dmabuf->phys);
6368 			kfree(dmabuf);
6369 		}
6370 	}
6371 
6372 	if (ras_fwlog->lwpd.virt) {
6373 		dma_free_coherent(&phba->pcidev->dev,
6374 				  sizeof(uint32_t) * 2,
6375 				  ras_fwlog->lwpd.virt,
6376 				  ras_fwlog->lwpd.phys);
6377 		ras_fwlog->lwpd.virt = NULL;
6378 	}
6379 
6380 	spin_lock_irq(&phba->hbalock);
6381 	ras_fwlog->state = INACTIVE;
6382 	spin_unlock_irq(&phba->hbalock);
6383 }
6384 
6385 /**
6386  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6387  * @phba: Pointer to HBA context object.
6388  * @fwlog_buff_count: Count of buffers to be created.
6389  *
6390  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6391  * to update FW log is posted to the adapter.
6392  * Buffer count is calculated based on module param ras_fwlog_buffsize
6393  * Size of each buffer posted to FW is 64K.
6394  **/
6395 
6396 static int
6397 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6398 			uint32_t fwlog_buff_count)
6399 {
6400 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6401 	struct lpfc_dmabuf *dmabuf;
6402 	int rc = 0, i = 0;
6403 
6404 	/* Initialize List */
6405 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6406 
6407 	/* Allocate memory for the LWPD */
6408 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6409 					    sizeof(uint32_t) * 2,
6410 					    &ras_fwlog->lwpd.phys,
6411 					    GFP_KERNEL);
6412 	if (!ras_fwlog->lwpd.virt) {
6413 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6414 				"6185 LWPD Memory Alloc Failed\n");
6415 
6416 		return -ENOMEM;
6417 	}
6418 
6419 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6420 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6421 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6422 				 GFP_KERNEL);
6423 		if (!dmabuf) {
6424 			rc = -ENOMEM;
6425 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6426 					"6186 Memory Alloc failed FW logging");
6427 			goto free_mem;
6428 		}
6429 
6430 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6431 						  LPFC_RAS_MAX_ENTRY_SIZE,
6432 						  &dmabuf->phys, GFP_KERNEL);
6433 		if (!dmabuf->virt) {
6434 			kfree(dmabuf);
6435 			rc = -ENOMEM;
6436 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6437 					"6187 DMA Alloc Failed FW logging");
6438 			goto free_mem;
6439 		}
6440 		dmabuf->buffer_tag = i;
6441 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6442 	}
6443 
6444 free_mem:
6445 	if (rc)
6446 		lpfc_sli4_ras_dma_free(phba);
6447 
6448 	return rc;
6449 }
6450 
6451 /**
6452  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6453  * @phba: pointer to lpfc hba data structure.
6454  * @pmboxq: pointer to the driver internal queue element for mailbox command.
6455  *
6456  * Completion handler for driver's RAS MBX command to the device.
6457  **/
6458 static void
6459 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6460 {
6461 	MAILBOX_t *mb;
6462 	union lpfc_sli4_cfg_shdr *shdr;
6463 	uint32_t shdr_status, shdr_add_status;
6464 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6465 
6466 	mb = &pmb->u.mb;
6467 
6468 	shdr = (union lpfc_sli4_cfg_shdr *)
6469 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6470 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6471 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6472 
6473 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6474 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
6475 				"6188 FW LOG mailbox "
6476 				"completed with status x%x add_status x%x,"
6477 				" mbx status x%x\n",
6478 				shdr_status, shdr_add_status, mb->mbxStatus);
6479 
6480 		ras_fwlog->ras_hwsupport = false;
6481 		goto disable_ras;
6482 	}
6483 
6484 	spin_lock_irq(&phba->hbalock);
6485 	ras_fwlog->state = ACTIVE;
6486 	spin_unlock_irq(&phba->hbalock);
6487 	mempool_free(pmb, phba->mbox_mem_pool);
6488 
6489 	return;
6490 
6491 disable_ras:
6492 	/* Free RAS DMA memory */
6493 	lpfc_sli4_ras_dma_free(phba);
6494 	mempool_free(pmb, phba->mbox_mem_pool);
6495 }
6496 
6497 /**
6498  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
6499  * @phba: pointer to lpfc hba data structure.
6500  * @fwlog_level: Logging verbosity level.
6501  * @fwlog_enable: Enable/Disable logging.
6502  *
6503  * Initialize memory and post mailbox command to enable FW logging in host
6504  * memory.
6505  **/
6506 int
6507 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
6508 			 uint32_t fwlog_level,
6509 			 uint32_t fwlog_enable)
6510 {
6511 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6512 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
6513 	struct lpfc_dmabuf *dmabuf;
6514 	LPFC_MBOXQ_t *mbox;
6515 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
6516 	int rc = 0;
6517 
6518 	spin_lock_irq(&phba->hbalock);
6519 	ras_fwlog->state = INACTIVE;
6520 	spin_unlock_irq(&phba->hbalock);
6521 
6522 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
6523 			  phba->cfg_ras_fwlog_buffsize);
6524 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
6525 
6526 	/*
6527 	 * If re-enabling FW logging support use earlier allocated
6528 	 * DMA buffers while posting MBX command.
6529 	 **/
6530 	if (!ras_fwlog->lwpd.virt) {
6531 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
6532 		if (rc) {
6533 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6534 					"6189 FW Log Memory Allocation Failed");
6535 			return rc;
6536 		}
6537 	}
6538 
6539 	/* Setup Mailbox command */
6540 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6541 	if (!mbox) {
6542 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6543 				"6190 RAS MBX Alloc Failed");
6544 		rc = -ENOMEM;
6545 		goto mem_free;
6546 	}
6547 
6548 	ras_fwlog->fw_loglevel = fwlog_level;
6549 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
6550 		sizeof(struct lpfc_sli4_cfg_mhdr));
6551 
6552 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
6553 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
6554 			 len, LPFC_SLI4_MBX_EMBED);
6555 
6556 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
6557 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
6558 	       fwlog_enable);
6559 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
6560 	       ras_fwlog->fw_loglevel);
6561 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
6562 	       ras_fwlog->fw_buffcount);
6563 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
6564 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
6565 
6566 	/* Update DMA buffer address */
6567 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
6568 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
6569 
6570 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
6571 			putPaddrLow(dmabuf->phys);
6572 
6573 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
6574 			putPaddrHigh(dmabuf->phys);
6575 	}
6576 
6577 	/* Update LPWD address */
6578 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
6579 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
6580 
6581 	spin_lock_irq(&phba->hbalock);
6582 	ras_fwlog->state = REG_INPROGRESS;
6583 	spin_unlock_irq(&phba->hbalock);
6584 	mbox->vport = phba->pport;
6585 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
6586 
6587 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
6588 
6589 	if (rc == MBX_NOT_FINISHED) {
6590 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6591 				"6191 FW-Log Mailbox failed. "
6592 				"status %d mbxStatus : x%x", rc,
6593 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
6594 		mempool_free(mbox, phba->mbox_mem_pool);
6595 		rc = -EIO;
6596 		goto mem_free;
6597 	} else
6598 		rc = 0;
6599 mem_free:
6600 	if (rc)
6601 		lpfc_sli4_ras_dma_free(phba);
6602 
6603 	return rc;
6604 }
6605 
6606 /**
6607  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
6608  * @phba: Pointer to HBA context object.
6609  *
6610  * Check if RAS is supported on the adapter and initialize it.
6611  **/
6612 void
6613 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
6614 {
6615 	/* Check RAS FW Log needs to be enabled or not */
6616 	if (lpfc_check_fwlog_support(phba))
6617 		return;
6618 
6619 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
6620 				 LPFC_RAS_ENABLE_LOGGING);
6621 }
6622 
6623 /**
6624  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
6625  * @phba: Pointer to HBA context object.
6626  *
6627  * This function allocates all SLI4 resource identifiers.
6628  **/
6629 int
6630 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
6631 {
6632 	int i, rc, error = 0;
6633 	uint16_t count, base;
6634 	unsigned long longs;
6635 
6636 	if (!phba->sli4_hba.rpi_hdrs_in_use)
6637 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
6638 	if (phba->sli4_hba.extents_in_use) {
6639 		/*
6640 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
6641 		 * resource extent count must be read and allocated before
6642 		 * provisioning the resource id arrays.
6643 		 */
6644 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6645 		    LPFC_IDX_RSRC_RDY) {
6646 			/*
6647 			 * Extent-based resources are set - the driver could
6648 			 * be in a port reset. Figure out if any corrective
6649 			 * actions need to be taken.
6650 			 */
6651 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6652 						 LPFC_RSC_TYPE_FCOE_VFI);
6653 			if (rc != 0)
6654 				error++;
6655 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6656 						 LPFC_RSC_TYPE_FCOE_VPI);
6657 			if (rc != 0)
6658 				error++;
6659 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6660 						 LPFC_RSC_TYPE_FCOE_XRI);
6661 			if (rc != 0)
6662 				error++;
6663 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6664 						 LPFC_RSC_TYPE_FCOE_RPI);
6665 			if (rc != 0)
6666 				error++;
6667 
6668 			/*
6669 			 * It's possible that the number of resources
6670 			 * provided to this port instance changed between
6671 			 * resets.  Detect this condition and reallocate
6672 			 * resources.  Otherwise, there is no action.
6673 			 */
6674 			if (error) {
6675 				lpfc_printf_log(phba, KERN_INFO,
6676 						LOG_MBOX | LOG_INIT,
6677 						"2931 Detected extent resource "
6678 						"change.  Reallocating all "
6679 						"extents.\n");
6680 				rc = lpfc_sli4_dealloc_extent(phba,
6681 						 LPFC_RSC_TYPE_FCOE_VFI);
6682 				rc = lpfc_sli4_dealloc_extent(phba,
6683 						 LPFC_RSC_TYPE_FCOE_VPI);
6684 				rc = lpfc_sli4_dealloc_extent(phba,
6685 						 LPFC_RSC_TYPE_FCOE_XRI);
6686 				rc = lpfc_sli4_dealloc_extent(phba,
6687 						 LPFC_RSC_TYPE_FCOE_RPI);
6688 			} else
6689 				return 0;
6690 		}
6691 
6692 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6693 		if (unlikely(rc))
6694 			goto err_exit;
6695 
6696 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6697 		if (unlikely(rc))
6698 			goto err_exit;
6699 
6700 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6701 		if (unlikely(rc))
6702 			goto err_exit;
6703 
6704 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6705 		if (unlikely(rc))
6706 			goto err_exit;
6707 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6708 		       LPFC_IDX_RSRC_RDY);
6709 		return rc;
6710 	} else {
6711 		/*
6712 		 * The port does not support resource extents.  The XRI, VPI,
6713 		 * VFI, RPI resource ids were determined from READ_CONFIG.
6714 		 * Just allocate the bitmasks and provision the resource id
6715 		 * arrays.  If a port reset is active, the resources don't
6716 		 * need any action - just exit.
6717 		 */
6718 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6719 		    LPFC_IDX_RSRC_RDY) {
6720 			lpfc_sli4_dealloc_resource_identifiers(phba);
6721 			lpfc_sli4_remove_rpis(phba);
6722 		}
6723 		/* RPIs. */
6724 		count = phba->sli4_hba.max_cfg_param.max_rpi;
6725 		if (count <= 0) {
6726 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6727 					"3279 Invalid provisioning of "
6728 					"rpi:%d\n", count);
6729 			rc = -EINVAL;
6730 			goto err_exit;
6731 		}
6732 		base = phba->sli4_hba.max_cfg_param.rpi_base;
6733 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6734 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6735 						   sizeof(unsigned long),
6736 						   GFP_KERNEL);
6737 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6738 			rc = -ENOMEM;
6739 			goto err_exit;
6740 		}
6741 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
6742 						 GFP_KERNEL);
6743 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6744 			rc = -ENOMEM;
6745 			goto free_rpi_bmask;
6746 		}
6747 
6748 		for (i = 0; i < count; i++)
6749 			phba->sli4_hba.rpi_ids[i] = base + i;
6750 
6751 		/* VPIs. */
6752 		count = phba->sli4_hba.max_cfg_param.max_vpi;
6753 		if (count <= 0) {
6754 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6755 					"3280 Invalid provisioning of "
6756 					"vpi:%d\n", count);
6757 			rc = -EINVAL;
6758 			goto free_rpi_ids;
6759 		}
6760 		base = phba->sli4_hba.max_cfg_param.vpi_base;
6761 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6762 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6763 					  GFP_KERNEL);
6764 		if (unlikely(!phba->vpi_bmask)) {
6765 			rc = -ENOMEM;
6766 			goto free_rpi_ids;
6767 		}
6768 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
6769 					GFP_KERNEL);
6770 		if (unlikely(!phba->vpi_ids)) {
6771 			rc = -ENOMEM;
6772 			goto free_vpi_bmask;
6773 		}
6774 
6775 		for (i = 0; i < count; i++)
6776 			phba->vpi_ids[i] = base + i;
6777 
6778 		/* XRIs. */
6779 		count = phba->sli4_hba.max_cfg_param.max_xri;
6780 		if (count <= 0) {
6781 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6782 					"3281 Invalid provisioning of "
6783 					"xri:%d\n", count);
6784 			rc = -EINVAL;
6785 			goto free_vpi_ids;
6786 		}
6787 		base = phba->sli4_hba.max_cfg_param.xri_base;
6788 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6789 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6790 						   sizeof(unsigned long),
6791 						   GFP_KERNEL);
6792 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6793 			rc = -ENOMEM;
6794 			goto free_vpi_ids;
6795 		}
6796 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6797 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
6798 						 GFP_KERNEL);
6799 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6800 			rc = -ENOMEM;
6801 			goto free_xri_bmask;
6802 		}
6803 
6804 		for (i = 0; i < count; i++)
6805 			phba->sli4_hba.xri_ids[i] = base + i;
6806 
6807 		/* VFIs. */
6808 		count = phba->sli4_hba.max_cfg_param.max_vfi;
6809 		if (count <= 0) {
6810 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6811 					"3282 Invalid provisioning of "
6812 					"vfi:%d\n", count);
6813 			rc = -EINVAL;
6814 			goto free_xri_ids;
6815 		}
6816 		base = phba->sli4_hba.max_cfg_param.vfi_base;
6817 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6818 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6819 						   sizeof(unsigned long),
6820 						   GFP_KERNEL);
6821 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6822 			rc = -ENOMEM;
6823 			goto free_xri_ids;
6824 		}
6825 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
6826 						 GFP_KERNEL);
6827 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6828 			rc = -ENOMEM;
6829 			goto free_vfi_bmask;
6830 		}
6831 
6832 		for (i = 0; i < count; i++)
6833 			phba->sli4_hba.vfi_ids[i] = base + i;
6834 
6835 		/*
6836 		 * Mark all resources ready.  An HBA reset doesn't need
6837 		 * to reset the initialization.
6838 		 */
6839 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6840 		       LPFC_IDX_RSRC_RDY);
6841 		return 0;
6842 	}
6843 
6844  free_vfi_bmask:
6845 	kfree(phba->sli4_hba.vfi_bmask);
6846 	phba->sli4_hba.vfi_bmask = NULL;
6847  free_xri_ids:
6848 	kfree(phba->sli4_hba.xri_ids);
6849 	phba->sli4_hba.xri_ids = NULL;
6850  free_xri_bmask:
6851 	kfree(phba->sli4_hba.xri_bmask);
6852 	phba->sli4_hba.xri_bmask = NULL;
6853  free_vpi_ids:
6854 	kfree(phba->vpi_ids);
6855 	phba->vpi_ids = NULL;
6856  free_vpi_bmask:
6857 	kfree(phba->vpi_bmask);
6858 	phba->vpi_bmask = NULL;
6859  free_rpi_ids:
6860 	kfree(phba->sli4_hba.rpi_ids);
6861 	phba->sli4_hba.rpi_ids = NULL;
6862  free_rpi_bmask:
6863 	kfree(phba->sli4_hba.rpi_bmask);
6864 	phba->sli4_hba.rpi_bmask = NULL;
6865  err_exit:
6866 	return rc;
6867 }
6868 
6869 /**
6870  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
6871  * @phba: Pointer to HBA context object.
6872  *
6873  * This function allocates the number of elements for the specified
6874  * resource type.
6875  **/
6876 int
6877 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
6878 {
6879 	if (phba->sli4_hba.extents_in_use) {
6880 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6881 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6882 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6883 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6884 	} else {
6885 		kfree(phba->vpi_bmask);
6886 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6887 		kfree(phba->vpi_ids);
6888 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6889 		kfree(phba->sli4_hba.xri_bmask);
6890 		kfree(phba->sli4_hba.xri_ids);
6891 		kfree(phba->sli4_hba.vfi_bmask);
6892 		kfree(phba->sli4_hba.vfi_ids);
6893 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6894 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6895 	}
6896 
6897 	return 0;
6898 }
6899 
6900 /**
6901  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
6902  * @phba: Pointer to HBA context object.
6903  * @type: The resource extent type.
6904  * @extnt_count: buffer to hold port extent count response
6905  * @extnt_size: buffer to hold port extent size response.
6906  *
6907  * This function calls the port to read the host allocated extents
6908  * for a particular type.
6909  **/
6910 int
6911 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
6912 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
6913 {
6914 	bool emb;
6915 	int rc = 0;
6916 	uint16_t curr_blks = 0;
6917 	uint32_t req_len, emb_len;
6918 	uint32_t alloc_len, mbox_tmo;
6919 	struct list_head *blk_list_head;
6920 	struct lpfc_rsrc_blks *rsrc_blk;
6921 	LPFC_MBOXQ_t *mbox;
6922 	void *virtaddr = NULL;
6923 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6924 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6925 	union  lpfc_sli4_cfg_shdr *shdr;
6926 
6927 	switch (type) {
6928 	case LPFC_RSC_TYPE_FCOE_VPI:
6929 		blk_list_head = &phba->lpfc_vpi_blk_list;
6930 		break;
6931 	case LPFC_RSC_TYPE_FCOE_XRI:
6932 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
6933 		break;
6934 	case LPFC_RSC_TYPE_FCOE_VFI:
6935 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
6936 		break;
6937 	case LPFC_RSC_TYPE_FCOE_RPI:
6938 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
6939 		break;
6940 	default:
6941 		return -EIO;
6942 	}
6943 
6944 	/* Count the number of extents currently allocatd for this type. */
6945 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
6946 		if (curr_blks == 0) {
6947 			/*
6948 			 * The GET_ALLOCATED mailbox does not return the size,
6949 			 * just the count.  The size should be just the size
6950 			 * stored in the current allocated block and all sizes
6951 			 * for an extent type are the same so set the return
6952 			 * value now.
6953 			 */
6954 			*extnt_size = rsrc_blk->rsrc_size;
6955 		}
6956 		curr_blks++;
6957 	}
6958 
6959 	/*
6960 	 * Calculate the size of an embedded mailbox.  The uint32_t
6961 	 * accounts for extents-specific word.
6962 	 */
6963 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6964 		sizeof(uint32_t);
6965 
6966 	/*
6967 	 * Presume the allocation and response will fit into an embedded
6968 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6969 	 */
6970 	emb = LPFC_SLI4_MBX_EMBED;
6971 	req_len = emb_len;
6972 	if (req_len > emb_len) {
6973 		req_len = curr_blks * sizeof(uint16_t) +
6974 			sizeof(union lpfc_sli4_cfg_shdr) +
6975 			sizeof(uint32_t);
6976 		emb = LPFC_SLI4_MBX_NEMBED;
6977 	}
6978 
6979 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6980 	if (!mbox)
6981 		return -ENOMEM;
6982 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
6983 
6984 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6985 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
6986 				     req_len, emb);
6987 	if (alloc_len < req_len) {
6988 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6989 			"2983 Allocated DMA memory size (x%x) is "
6990 			"less than the requested DMA memory "
6991 			"size (x%x)\n", alloc_len, req_len);
6992 		rc = -ENOMEM;
6993 		goto err_exit;
6994 	}
6995 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
6996 	if (unlikely(rc)) {
6997 		rc = -EIO;
6998 		goto err_exit;
6999 	}
7000 
7001 	if (!phba->sli4_hba.intr_enable)
7002 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7003 	else {
7004 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7005 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7006 	}
7007 
7008 	if (unlikely(rc)) {
7009 		rc = -EIO;
7010 		goto err_exit;
7011 	}
7012 
7013 	/*
7014 	 * Figure out where the response is located.  Then get local pointers
7015 	 * to the response data.  The port does not guarantee to respond to
7016 	 * all extents counts request so update the local variable with the
7017 	 * allocated count from the port.
7018 	 */
7019 	if (emb == LPFC_SLI4_MBX_EMBED) {
7020 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7021 		shdr = &rsrc_ext->header.cfg_shdr;
7022 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7023 	} else {
7024 		virtaddr = mbox->sge_array->addr[0];
7025 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7026 		shdr = &n_rsrc->cfg_shdr;
7027 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7028 	}
7029 
7030 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7031 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
7032 			"2984 Failed to read allocated resources "
7033 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7034 			type,
7035 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7036 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7037 		rc = -EIO;
7038 		goto err_exit;
7039 	}
7040  err_exit:
7041 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7042 	return rc;
7043 }
7044 
7045 /**
7046  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7047  * @phba: pointer to lpfc hba data structure.
7048  * @pring: Pointer to driver SLI ring object.
7049  * @sgl_list: linked link of sgl buffers to post
7050  * @cnt: number of linked list buffers
7051  *
7052  * This routine walks the list of buffers that have been allocated and
7053  * repost them to the port by using SGL block post. This is needed after a
7054  * pci_function_reset/warm_start or start. It attempts to construct blocks
7055  * of buffer sgls which contains contiguous xris and uses the non-embedded
7056  * SGL block post mailbox commands to post them to the port. For single
7057  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7058  * mailbox command for posting.
7059  *
7060  * Returns: 0 = success, non-zero failure.
7061  **/
7062 static int
7063 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7064 			  struct list_head *sgl_list, int cnt)
7065 {
7066 	struct lpfc_sglq *sglq_entry = NULL;
7067 	struct lpfc_sglq *sglq_entry_next = NULL;
7068 	struct lpfc_sglq *sglq_entry_first = NULL;
7069 	int status, total_cnt;
7070 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7071 	int last_xritag = NO_XRI;
7072 	LIST_HEAD(prep_sgl_list);
7073 	LIST_HEAD(blck_sgl_list);
7074 	LIST_HEAD(allc_sgl_list);
7075 	LIST_HEAD(post_sgl_list);
7076 	LIST_HEAD(free_sgl_list);
7077 
7078 	spin_lock_irq(&phba->hbalock);
7079 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7080 	list_splice_init(sgl_list, &allc_sgl_list);
7081 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7082 	spin_unlock_irq(&phba->hbalock);
7083 
7084 	total_cnt = cnt;
7085 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7086 				 &allc_sgl_list, list) {
7087 		list_del_init(&sglq_entry->list);
7088 		block_cnt++;
7089 		if ((last_xritag != NO_XRI) &&
7090 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7091 			/* a hole in xri block, form a sgl posting block */
7092 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7093 			post_cnt = block_cnt - 1;
7094 			/* prepare list for next posting block */
7095 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7096 			block_cnt = 1;
7097 		} else {
7098 			/* prepare list for next posting block */
7099 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7100 			/* enough sgls for non-embed sgl mbox command */
7101 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7102 				list_splice_init(&prep_sgl_list,
7103 						 &blck_sgl_list);
7104 				post_cnt = block_cnt;
7105 				block_cnt = 0;
7106 			}
7107 		}
7108 		num_posted++;
7109 
7110 		/* keep track of last sgl's xritag */
7111 		last_xritag = sglq_entry->sli4_xritag;
7112 
7113 		/* end of repost sgl list condition for buffers */
7114 		if (num_posted == total_cnt) {
7115 			if (post_cnt == 0) {
7116 				list_splice_init(&prep_sgl_list,
7117 						 &blck_sgl_list);
7118 				post_cnt = block_cnt;
7119 			} else if (block_cnt == 1) {
7120 				status = lpfc_sli4_post_sgl(phba,
7121 						sglq_entry->phys, 0,
7122 						sglq_entry->sli4_xritag);
7123 				if (!status) {
7124 					/* successful, put sgl to posted list */
7125 					list_add_tail(&sglq_entry->list,
7126 						      &post_sgl_list);
7127 				} else {
7128 					/* Failure, put sgl to free list */
7129 					lpfc_printf_log(phba, KERN_WARNING,
7130 						LOG_SLI,
7131 						"3159 Failed to post "
7132 						"sgl, xritag:x%x\n",
7133 						sglq_entry->sli4_xritag);
7134 					list_add_tail(&sglq_entry->list,
7135 						      &free_sgl_list);
7136 					total_cnt--;
7137 				}
7138 			}
7139 		}
7140 
7141 		/* continue until a nembed page worth of sgls */
7142 		if (post_cnt == 0)
7143 			continue;
7144 
7145 		/* post the buffer list sgls as a block */
7146 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7147 						 post_cnt);
7148 
7149 		if (!status) {
7150 			/* success, put sgl list to posted sgl list */
7151 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7152 		} else {
7153 			/* Failure, put sgl list to free sgl list */
7154 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7155 							    struct lpfc_sglq,
7156 							    list);
7157 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7158 					"3160 Failed to post sgl-list, "
7159 					"xritag:x%x-x%x\n",
7160 					sglq_entry_first->sli4_xritag,
7161 					(sglq_entry_first->sli4_xritag +
7162 					 post_cnt - 1));
7163 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7164 			total_cnt -= post_cnt;
7165 		}
7166 
7167 		/* don't reset xirtag due to hole in xri block */
7168 		if (block_cnt == 0)
7169 			last_xritag = NO_XRI;
7170 
7171 		/* reset sgl post count for next round of posting */
7172 		post_cnt = 0;
7173 	}
7174 
7175 	/* free the sgls failed to post */
7176 	lpfc_free_sgl_list(phba, &free_sgl_list);
7177 
7178 	/* push sgls posted to the available list */
7179 	if (!list_empty(&post_sgl_list)) {
7180 		spin_lock_irq(&phba->hbalock);
7181 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7182 		list_splice_init(&post_sgl_list, sgl_list);
7183 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7184 		spin_unlock_irq(&phba->hbalock);
7185 	} else {
7186 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7187 				"3161 Failure to post sgl to port.\n");
7188 		return -EIO;
7189 	}
7190 
7191 	/* return the number of XRIs actually posted */
7192 	return total_cnt;
7193 }
7194 
7195 /**
7196  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7197  * @phba: pointer to lpfc hba data structure.
7198  *
7199  * This routine walks the list of nvme buffers that have been allocated and
7200  * repost them to the port by using SGL block post. This is needed after a
7201  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7202  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7203  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7204  *
7205  * Returns: 0 = success, non-zero failure.
7206  **/
7207 static int
7208 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7209 {
7210 	LIST_HEAD(post_nblist);
7211 	int num_posted, rc = 0;
7212 
7213 	/* get all NVME buffers need to repost to a local list */
7214 	lpfc_io_buf_flush(phba, &post_nblist);
7215 
7216 	/* post the list of nvme buffer sgls to port if available */
7217 	if (!list_empty(&post_nblist)) {
7218 		num_posted = lpfc_sli4_post_io_sgl_list(
7219 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7220 		/* failed to post any nvme buffer, return error */
7221 		if (num_posted == 0)
7222 			rc = -EIO;
7223 	}
7224 	return rc;
7225 }
7226 
7227 static void
7228 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7229 {
7230 	uint32_t len;
7231 
7232 	len = sizeof(struct lpfc_mbx_set_host_data) -
7233 		sizeof(struct lpfc_sli4_cfg_mhdr);
7234 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7235 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7236 			 LPFC_SLI4_MBX_EMBED);
7237 
7238 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7239 	mbox->u.mqe.un.set_host_data.param_len =
7240 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7241 	snprintf(mbox->u.mqe.un.set_host_data.data,
7242 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7243 		 "Linux %s v"LPFC_DRIVER_VERSION,
7244 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7245 }
7246 
7247 int
7248 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7249 		    struct lpfc_queue *drq, int count, int idx)
7250 {
7251 	int rc, i;
7252 	struct lpfc_rqe hrqe;
7253 	struct lpfc_rqe drqe;
7254 	struct lpfc_rqb *rqbp;
7255 	unsigned long flags;
7256 	struct rqb_dmabuf *rqb_buffer;
7257 	LIST_HEAD(rqb_buf_list);
7258 
7259 	spin_lock_irqsave(&phba->hbalock, flags);
7260 	rqbp = hrq->rqbp;
7261 	for (i = 0; i < count; i++) {
7262 		/* IF RQ is already full, don't bother */
7263 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1)
7264 			break;
7265 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7266 		if (!rqb_buffer)
7267 			break;
7268 		rqb_buffer->hrq = hrq;
7269 		rqb_buffer->drq = drq;
7270 		rqb_buffer->idx = idx;
7271 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7272 	}
7273 	while (!list_empty(&rqb_buf_list)) {
7274 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7275 				 hbuf.list);
7276 
7277 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7278 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7279 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7280 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7281 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7282 		if (rc < 0) {
7283 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7284 					"6421 Cannot post to HRQ %d: %x %x %x "
7285 					"DRQ %x %x\n",
7286 					hrq->queue_id,
7287 					hrq->host_index,
7288 					hrq->hba_index,
7289 					hrq->entry_count,
7290 					drq->host_index,
7291 					drq->hba_index);
7292 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7293 		} else {
7294 			list_add_tail(&rqb_buffer->hbuf.list,
7295 				      &rqbp->rqb_buffer_list);
7296 			rqbp->buffer_count++;
7297 		}
7298 	}
7299 	spin_unlock_irqrestore(&phba->hbalock, flags);
7300 	return 1;
7301 }
7302 
7303 /**
7304  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
7305  * @phba: Pointer to HBA context object.
7306  *
7307  * This function is the main SLI4 device initialization PCI function. This
7308  * function is called by the HBA initialization code, HBA reset code and
7309  * HBA error attention handler code. Caller is not required to hold any
7310  * locks.
7311  **/
7312 int
7313 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
7314 {
7315 	int rc, i, cnt, len, dd;
7316 	LPFC_MBOXQ_t *mboxq;
7317 	struct lpfc_mqe *mqe;
7318 	uint8_t *vpd;
7319 	uint32_t vpd_size;
7320 	uint32_t ftr_rsp = 0;
7321 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
7322 	struct lpfc_vport *vport = phba->pport;
7323 	struct lpfc_dmabuf *mp;
7324 	struct lpfc_rqb *rqbp;
7325 
7326 	/* Perform a PCI function reset to start from clean */
7327 	rc = lpfc_pci_function_reset(phba);
7328 	if (unlikely(rc))
7329 		return -ENODEV;
7330 
7331 	/* Check the HBA Host Status Register for readyness */
7332 	rc = lpfc_sli4_post_status_check(phba);
7333 	if (unlikely(rc))
7334 		return -ENODEV;
7335 	else {
7336 		spin_lock_irq(&phba->hbalock);
7337 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
7338 		spin_unlock_irq(&phba->hbalock);
7339 	}
7340 
7341 	/*
7342 	 * Allocate a single mailbox container for initializing the
7343 	 * port.
7344 	 */
7345 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7346 	if (!mboxq)
7347 		return -ENOMEM;
7348 
7349 	/* Issue READ_REV to collect vpd and FW information. */
7350 	vpd_size = SLI4_PAGE_SIZE;
7351 	vpd = kzalloc(vpd_size, GFP_KERNEL);
7352 	if (!vpd) {
7353 		rc = -ENOMEM;
7354 		goto out_free_mbox;
7355 	}
7356 
7357 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
7358 	if (unlikely(rc)) {
7359 		kfree(vpd);
7360 		goto out_free_mbox;
7361 	}
7362 
7363 	mqe = &mboxq->u.mqe;
7364 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
7365 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
7366 		phba->hba_flag |= HBA_FCOE_MODE;
7367 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
7368 	} else {
7369 		phba->hba_flag &= ~HBA_FCOE_MODE;
7370 	}
7371 
7372 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
7373 		LPFC_DCBX_CEE_MODE)
7374 		phba->hba_flag |= HBA_FIP_SUPPORT;
7375 	else
7376 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
7377 
7378 	phba->hba_flag &= ~HBA_IOQ_FLUSH;
7379 
7380 	if (phba->sli_rev != LPFC_SLI_REV4) {
7381 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7382 			"0376 READ_REV Error. SLI Level %d "
7383 			"FCoE enabled %d\n",
7384 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
7385 		rc = -EIO;
7386 		kfree(vpd);
7387 		goto out_free_mbox;
7388 	}
7389 
7390 	/*
7391 	 * Continue initialization with default values even if driver failed
7392 	 * to read FCoE param config regions, only read parameters if the
7393 	 * board is FCoE
7394 	 */
7395 	if (phba->hba_flag & HBA_FCOE_MODE &&
7396 	    lpfc_sli4_read_fcoe_params(phba))
7397 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
7398 			"2570 Failed to read FCoE parameters\n");
7399 
7400 	/*
7401 	 * Retrieve sli4 device physical port name, failure of doing it
7402 	 * is considered as non-fatal.
7403 	 */
7404 	rc = lpfc_sli4_retrieve_pport_name(phba);
7405 	if (!rc)
7406 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7407 				"3080 Successful retrieving SLI4 device "
7408 				"physical port name: %s.\n", phba->Port);
7409 
7410 	rc = lpfc_sli4_get_ctl_attr(phba);
7411 	if (!rc)
7412 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7413 				"8351 Successful retrieving SLI4 device "
7414 				"CTL ATTR\n");
7415 
7416 	/*
7417 	 * Evaluate the read rev and vpd data. Populate the driver
7418 	 * state with the results. If this routine fails, the failure
7419 	 * is not fatal as the driver will use generic values.
7420 	 */
7421 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
7422 	if (unlikely(!rc)) {
7423 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7424 				"0377 Error %d parsing vpd. "
7425 				"Using defaults.\n", rc);
7426 		rc = 0;
7427 	}
7428 	kfree(vpd);
7429 
7430 	/* Save information as VPD data */
7431 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
7432 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
7433 
7434 	/*
7435 	 * This is because first G7 ASIC doesn't support the standard
7436 	 * 0x5a NVME cmd descriptor type/subtype
7437 	 */
7438 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7439 			LPFC_SLI_INTF_IF_TYPE_6) &&
7440 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
7441 	    (phba->vpd.rev.smRev == 0) &&
7442 	    (phba->cfg_nvme_embed_cmd == 1))
7443 		phba->cfg_nvme_embed_cmd = 0;
7444 
7445 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
7446 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
7447 					 &mqe->un.read_rev);
7448 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
7449 				       &mqe->un.read_rev);
7450 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
7451 					    &mqe->un.read_rev);
7452 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
7453 					   &mqe->un.read_rev);
7454 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
7455 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
7456 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
7457 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
7458 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
7459 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
7460 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7461 			"(%d):0380 READ_REV Status x%x "
7462 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
7463 			mboxq->vport ? mboxq->vport->vpi : 0,
7464 			bf_get(lpfc_mqe_status, mqe),
7465 			phba->vpd.rev.opFwName,
7466 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
7467 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
7468 
7469 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7470 	    LPFC_SLI_INTF_IF_TYPE_0) {
7471 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
7472 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7473 		if (rc == MBX_SUCCESS) {
7474 			phba->hba_flag |= HBA_RECOVERABLE_UE;
7475 			/* Set 1Sec interval to detect UE */
7476 			phba->eratt_poll_interval = 1;
7477 			phba->sli4_hba.ue_to_sr = bf_get(
7478 					lpfc_mbx_set_feature_UESR,
7479 					&mboxq->u.mqe.un.set_feature);
7480 			phba->sli4_hba.ue_to_rp = bf_get(
7481 					lpfc_mbx_set_feature_UERP,
7482 					&mboxq->u.mqe.un.set_feature);
7483 		}
7484 	}
7485 
7486 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
7487 		/* Enable MDS Diagnostics only if the SLI Port supports it */
7488 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
7489 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7490 		if (rc != MBX_SUCCESS)
7491 			phba->mds_diags_support = 0;
7492 	}
7493 
7494 	/*
7495 	 * Discover the port's supported feature set and match it against the
7496 	 * hosts requests.
7497 	 */
7498 	lpfc_request_features(phba, mboxq);
7499 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7500 	if (unlikely(rc)) {
7501 		rc = -EIO;
7502 		goto out_free_mbox;
7503 	}
7504 
7505 	/*
7506 	 * The port must support FCP initiator mode as this is the
7507 	 * only mode running in the host.
7508 	 */
7509 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
7510 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7511 				"0378 No support for fcpi mode.\n");
7512 		ftr_rsp++;
7513 	}
7514 
7515 	/* Performance Hints are ONLY for FCoE */
7516 	if (phba->hba_flag & HBA_FCOE_MODE) {
7517 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
7518 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
7519 		else
7520 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
7521 	}
7522 
7523 	/*
7524 	 * If the port cannot support the host's requested features
7525 	 * then turn off the global config parameters to disable the
7526 	 * feature in the driver.  This is not a fatal error.
7527 	 */
7528 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
7529 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
7530 			phba->cfg_enable_bg = 0;
7531 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
7532 			ftr_rsp++;
7533 		}
7534 	}
7535 
7536 	if (phba->max_vpi && phba->cfg_enable_npiv &&
7537 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7538 		ftr_rsp++;
7539 
7540 	if (ftr_rsp) {
7541 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7542 				"0379 Feature Mismatch Data: x%08x %08x "
7543 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
7544 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
7545 				phba->cfg_enable_npiv, phba->max_vpi);
7546 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
7547 			phba->cfg_enable_bg = 0;
7548 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7549 			phba->cfg_enable_npiv = 0;
7550 	}
7551 
7552 	/* These SLI3 features are assumed in SLI4 */
7553 	spin_lock_irq(&phba->hbalock);
7554 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
7555 	spin_unlock_irq(&phba->hbalock);
7556 
7557 	/* Always try to enable dual dump feature if we can */
7558 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
7559 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7560 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
7561 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
7562 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_INIT,
7563 				"6448 Dual Dump is enabled\n");
7564 	else
7565 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
7566 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
7567 				"rc:x%x dd:x%x\n",
7568 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7569 				lpfc_sli_config_mbox_subsys_get(
7570 					phba, mboxq),
7571 				lpfc_sli_config_mbox_opcode_get(
7572 					phba, mboxq),
7573 				rc, dd);
7574 	/*
7575 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
7576 	 * calls depends on these resources to complete port setup.
7577 	 */
7578 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
7579 	if (rc) {
7580 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7581 				"2920 Failed to alloc Resource IDs "
7582 				"rc = x%x\n", rc);
7583 		goto out_free_mbox;
7584 	}
7585 
7586 	lpfc_set_host_data(phba, mboxq);
7587 
7588 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7589 	if (rc) {
7590 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7591 				"2134 Failed to set host os driver version %x",
7592 				rc);
7593 	}
7594 
7595 	/* Read the port's service parameters. */
7596 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
7597 	if (rc) {
7598 		phba->link_state = LPFC_HBA_ERROR;
7599 		rc = -ENOMEM;
7600 		goto out_free_mbox;
7601 	}
7602 
7603 	mboxq->vport = vport;
7604 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7605 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
7606 	if (rc == MBX_SUCCESS) {
7607 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
7608 		rc = 0;
7609 	}
7610 
7611 	/*
7612 	 * This memory was allocated by the lpfc_read_sparam routine. Release
7613 	 * it to the mbuf pool.
7614 	 */
7615 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
7616 	kfree(mp);
7617 	mboxq->ctx_buf = NULL;
7618 	if (unlikely(rc)) {
7619 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7620 				"0382 READ_SPARAM command failed "
7621 				"status %d, mbxStatus x%x\n",
7622 				rc, bf_get(lpfc_mqe_status, mqe));
7623 		phba->link_state = LPFC_HBA_ERROR;
7624 		rc = -EIO;
7625 		goto out_free_mbox;
7626 	}
7627 
7628 	lpfc_update_vport_wwn(vport);
7629 
7630 	/* Update the fc_host data structures with new wwn. */
7631 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
7632 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
7633 
7634 	/* Create all the SLI4 queues */
7635 	rc = lpfc_sli4_queue_create(phba);
7636 	if (rc) {
7637 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7638 				"3089 Failed to allocate queues\n");
7639 		rc = -ENODEV;
7640 		goto out_free_mbox;
7641 	}
7642 	/* Set up all the queues to the device */
7643 	rc = lpfc_sli4_queue_setup(phba);
7644 	if (unlikely(rc)) {
7645 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7646 				"0381 Error %d during queue setup.\n ", rc);
7647 		goto out_stop_timers;
7648 	}
7649 	/* Initialize the driver internal SLI layer lists. */
7650 	lpfc_sli4_setup(phba);
7651 	lpfc_sli4_queue_init(phba);
7652 
7653 	/* update host els xri-sgl sizes and mappings */
7654 	rc = lpfc_sli4_els_sgl_update(phba);
7655 	if (unlikely(rc)) {
7656 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7657 				"1400 Failed to update xri-sgl size and "
7658 				"mapping: %d\n", rc);
7659 		goto out_destroy_queue;
7660 	}
7661 
7662 	/* register the els sgl pool to the port */
7663 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
7664 				       phba->sli4_hba.els_xri_cnt);
7665 	if (unlikely(rc < 0)) {
7666 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7667 				"0582 Error %d during els sgl post "
7668 				"operation\n", rc);
7669 		rc = -ENODEV;
7670 		goto out_destroy_queue;
7671 	}
7672 	phba->sli4_hba.els_xri_cnt = rc;
7673 
7674 	if (phba->nvmet_support) {
7675 		/* update host nvmet xri-sgl sizes and mappings */
7676 		rc = lpfc_sli4_nvmet_sgl_update(phba);
7677 		if (unlikely(rc)) {
7678 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7679 					"6308 Failed to update nvmet-sgl size "
7680 					"and mapping: %d\n", rc);
7681 			goto out_destroy_queue;
7682 		}
7683 
7684 		/* register the nvmet sgl pool to the port */
7685 		rc = lpfc_sli4_repost_sgl_list(
7686 			phba,
7687 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
7688 			phba->sli4_hba.nvmet_xri_cnt);
7689 		if (unlikely(rc < 0)) {
7690 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7691 					"3117 Error %d during nvmet "
7692 					"sgl post\n", rc);
7693 			rc = -ENODEV;
7694 			goto out_destroy_queue;
7695 		}
7696 		phba->sli4_hba.nvmet_xri_cnt = rc;
7697 
7698 		/* We allocate an iocbq for every receive context SGL.
7699 		 * The additional allocation is for abort and ls handling.
7700 		 */
7701 		cnt = phba->sli4_hba.nvmet_xri_cnt +
7702 			phba->sli4_hba.max_cfg_param.max_xri;
7703 	} else {
7704 		/* update host common xri-sgl sizes and mappings */
7705 		rc = lpfc_sli4_io_sgl_update(phba);
7706 		if (unlikely(rc)) {
7707 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7708 					"6082 Failed to update nvme-sgl size "
7709 					"and mapping: %d\n", rc);
7710 			goto out_destroy_queue;
7711 		}
7712 
7713 		/* register the allocated common sgl pool to the port */
7714 		rc = lpfc_sli4_repost_io_sgl_list(phba);
7715 		if (unlikely(rc)) {
7716 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7717 					"6116 Error %d during nvme sgl post "
7718 					"operation\n", rc);
7719 			/* Some NVME buffers were moved to abort nvme list */
7720 			/* A pci function reset will repost them */
7721 			rc = -ENODEV;
7722 			goto out_destroy_queue;
7723 		}
7724 		/* Each lpfc_io_buf job structure has an iocbq element.
7725 		 * This cnt provides for abort, els, ct and ls requests.
7726 		 */
7727 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
7728 	}
7729 
7730 	if (!phba->sli.iocbq_lookup) {
7731 		/* Initialize and populate the iocb list per host */
7732 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7733 				"2821 initialize iocb list with %d entries\n",
7734 				cnt);
7735 		rc = lpfc_init_iocb_list(phba, cnt);
7736 		if (rc) {
7737 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7738 					"1413 Failed to init iocb list.\n");
7739 			goto out_destroy_queue;
7740 		}
7741 	}
7742 
7743 	if (phba->nvmet_support)
7744 		lpfc_nvmet_create_targetport(phba);
7745 
7746 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
7747 		/* Post initial buffers to all RQs created */
7748 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
7749 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
7750 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
7751 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
7752 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
7753 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
7754 			rqbp->buffer_count = 0;
7755 
7756 			lpfc_post_rq_buffer(
7757 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
7758 				phba->sli4_hba.nvmet_mrq_data[i],
7759 				phba->cfg_nvmet_mrq_post, i);
7760 		}
7761 	}
7762 
7763 	/* Post the rpi header region to the device. */
7764 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
7765 	if (unlikely(rc)) {
7766 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7767 				"0393 Error %d during rpi post operation\n",
7768 				rc);
7769 		rc = -ENODEV;
7770 		goto out_destroy_queue;
7771 	}
7772 	lpfc_sli4_node_prep(phba);
7773 
7774 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
7775 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
7776 			/*
7777 			 * The FC Port needs to register FCFI (index 0)
7778 			 */
7779 			lpfc_reg_fcfi(phba, mboxq);
7780 			mboxq->vport = phba->pport;
7781 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7782 			if (rc != MBX_SUCCESS)
7783 				goto out_unset_queue;
7784 			rc = 0;
7785 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
7786 						&mboxq->u.mqe.un.reg_fcfi);
7787 		} else {
7788 			/* We are a NVME Target mode with MRQ > 1 */
7789 
7790 			/* First register the FCFI */
7791 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
7792 			mboxq->vport = phba->pport;
7793 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7794 			if (rc != MBX_SUCCESS)
7795 				goto out_unset_queue;
7796 			rc = 0;
7797 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
7798 						&mboxq->u.mqe.un.reg_fcfi_mrq);
7799 
7800 			/* Next register the MRQs */
7801 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
7802 			mboxq->vport = phba->pport;
7803 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7804 			if (rc != MBX_SUCCESS)
7805 				goto out_unset_queue;
7806 			rc = 0;
7807 		}
7808 		/* Check if the port is configured to be disabled */
7809 		lpfc_sli_read_link_ste(phba);
7810 	}
7811 
7812 	/* Don't post more new bufs if repost already recovered
7813 	 * the nvme sgls.
7814 	 */
7815 	if (phba->nvmet_support == 0) {
7816 		if (phba->sli4_hba.io_xri_cnt == 0) {
7817 			len = lpfc_new_io_buf(
7818 					      phba, phba->sli4_hba.io_xri_max);
7819 			if (len == 0) {
7820 				rc = -ENOMEM;
7821 				goto out_unset_queue;
7822 			}
7823 
7824 			if (phba->cfg_xri_rebalancing)
7825 				lpfc_create_multixri_pools(phba);
7826 		}
7827 	} else {
7828 		phba->cfg_xri_rebalancing = 0;
7829 	}
7830 
7831 	/* Allow asynchronous mailbox command to go through */
7832 	spin_lock_irq(&phba->hbalock);
7833 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7834 	spin_unlock_irq(&phba->hbalock);
7835 
7836 	/* Post receive buffers to the device */
7837 	lpfc_sli4_rb_setup(phba);
7838 
7839 	/* Reset HBA FCF states after HBA reset */
7840 	phba->fcf.fcf_flag = 0;
7841 	phba->fcf.current_rec.flag = 0;
7842 
7843 	/* Start the ELS watchdog timer */
7844 	mod_timer(&vport->els_tmofunc,
7845 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
7846 
7847 	/* Start heart beat timer */
7848 	mod_timer(&phba->hb_tmofunc,
7849 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
7850 	phba->hb_outstanding = 0;
7851 	phba->last_completion_time = jiffies;
7852 
7853 	/* start eq_delay heartbeat */
7854 	if (phba->cfg_auto_imax)
7855 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
7856 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
7857 
7858 	/* Start error attention (ERATT) polling timer */
7859 	mod_timer(&phba->eratt_poll,
7860 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
7861 
7862 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
7863 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
7864 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
7865 		if (!rc) {
7866 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7867 					"2829 This device supports "
7868 					"Advanced Error Reporting (AER)\n");
7869 			spin_lock_irq(&phba->hbalock);
7870 			phba->hba_flag |= HBA_AER_ENABLED;
7871 			spin_unlock_irq(&phba->hbalock);
7872 		} else {
7873 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7874 					"2830 This device does not support "
7875 					"Advanced Error Reporting (AER)\n");
7876 			phba->cfg_aer_support = 0;
7877 		}
7878 		rc = 0;
7879 	}
7880 
7881 	/*
7882 	 * The port is ready, set the host's link state to LINK_DOWN
7883 	 * in preparation for link interrupts.
7884 	 */
7885 	spin_lock_irq(&phba->hbalock);
7886 	phba->link_state = LPFC_LINK_DOWN;
7887 
7888 	/* Check if physical ports are trunked */
7889 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
7890 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
7891 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
7892 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
7893 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
7894 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
7895 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
7896 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
7897 	spin_unlock_irq(&phba->hbalock);
7898 
7899 	/* Arm the CQs and then EQs on device */
7900 	lpfc_sli4_arm_cqeq_intr(phba);
7901 
7902 	/* Indicate device interrupt mode */
7903 	phba->sli4_hba.intr_enable = 1;
7904 
7905 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
7906 	    (phba->hba_flag & LINK_DISABLED)) {
7907 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
7908 				"3103 Adapter Link is disabled.\n");
7909 		lpfc_down_link(phba, mboxq);
7910 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7911 		if (rc != MBX_SUCCESS) {
7912 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
7913 					"3104 Adapter failed to issue "
7914 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
7915 			goto out_io_buff_free;
7916 		}
7917 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
7918 		/* don't perform init_link on SLI4 FC port loopback test */
7919 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
7920 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
7921 			if (rc)
7922 				goto out_io_buff_free;
7923 		}
7924 	}
7925 	mempool_free(mboxq, phba->mbox_mem_pool);
7926 	return rc;
7927 out_io_buff_free:
7928 	/* Free allocated IO Buffers */
7929 	lpfc_io_free(phba);
7930 out_unset_queue:
7931 	/* Unset all the queues set up in this routine when error out */
7932 	lpfc_sli4_queue_unset(phba);
7933 out_destroy_queue:
7934 	lpfc_free_iocb_list(phba);
7935 	lpfc_sli4_queue_destroy(phba);
7936 out_stop_timers:
7937 	lpfc_stop_hba_timers(phba);
7938 out_free_mbox:
7939 	mempool_free(mboxq, phba->mbox_mem_pool);
7940 	return rc;
7941 }
7942 
7943 /**
7944  * lpfc_mbox_timeout - Timeout call back function for mbox timer
7945  * @ptr: context object - pointer to hba structure.
7946  *
7947  * This is the callback function for mailbox timer. The mailbox
7948  * timer is armed when a new mailbox command is issued and the timer
7949  * is deleted when the mailbox complete. The function is called by
7950  * the kernel timer code when a mailbox does not complete within
7951  * expected time. This function wakes up the worker thread to
7952  * process the mailbox timeout and returns. All the processing is
7953  * done by the worker thread function lpfc_mbox_timeout_handler.
7954  **/
7955 void
7956 lpfc_mbox_timeout(struct timer_list *t)
7957 {
7958 	struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
7959 	unsigned long iflag;
7960 	uint32_t tmo_posted;
7961 
7962 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
7963 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
7964 	if (!tmo_posted)
7965 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
7966 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
7967 
7968 	if (!tmo_posted)
7969 		lpfc_worker_wake_up(phba);
7970 	return;
7971 }
7972 
7973 /**
7974  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
7975  *                                    are pending
7976  * @phba: Pointer to HBA context object.
7977  *
7978  * This function checks if any mailbox completions are present on the mailbox
7979  * completion queue.
7980  **/
7981 static bool
7982 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
7983 {
7984 
7985 	uint32_t idx;
7986 	struct lpfc_queue *mcq;
7987 	struct lpfc_mcqe *mcqe;
7988 	bool pending_completions = false;
7989 	uint8_t	qe_valid;
7990 
7991 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
7992 		return false;
7993 
7994 	/* Check for completions on mailbox completion queue */
7995 
7996 	mcq = phba->sli4_hba.mbx_cq;
7997 	idx = mcq->hba_index;
7998 	qe_valid = mcq->qe_valid;
7999 	while (bf_get_le32(lpfc_cqe_valid,
8000 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
8001 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
8002 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
8003 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
8004 			pending_completions = true;
8005 			break;
8006 		}
8007 		idx = (idx + 1) % mcq->entry_count;
8008 		if (mcq->hba_index == idx)
8009 			break;
8010 
8011 		/* if the index wrapped around, toggle the valid bit */
8012 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
8013 			qe_valid = (qe_valid) ? 0 : 1;
8014 	}
8015 	return pending_completions;
8016 
8017 }
8018 
8019 /**
8020  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
8021  *					      that were missed.
8022  * @phba: Pointer to HBA context object.
8023  *
8024  * For sli4, it is possible to miss an interrupt. As such mbox completions
8025  * maybe missed causing erroneous mailbox timeouts to occur. This function
8026  * checks to see if mbox completions are on the mailbox completion queue
8027  * and will process all the completions associated with the eq for the
8028  * mailbox completion queue.
8029  **/
8030 static bool
8031 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
8032 {
8033 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
8034 	uint32_t eqidx;
8035 	struct lpfc_queue *fpeq = NULL;
8036 	struct lpfc_queue *eq;
8037 	bool mbox_pending;
8038 
8039 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8040 		return false;
8041 
8042 	/* Find the EQ associated with the mbox CQ */
8043 	if (sli4_hba->hdwq) {
8044 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
8045 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
8046 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
8047 				fpeq = eq;
8048 				break;
8049 			}
8050 		}
8051 	}
8052 	if (!fpeq)
8053 		return false;
8054 
8055 	/* Turn off interrupts from this EQ */
8056 
8057 	sli4_hba->sli4_eq_clr_intr(fpeq);
8058 
8059 	/* Check to see if a mbox completion is pending */
8060 
8061 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
8062 
8063 	/*
8064 	 * If a mbox completion is pending, process all the events on EQ
8065 	 * associated with the mbox completion queue (this could include
8066 	 * mailbox commands, async events, els commands, receive queue data
8067 	 * and fcp commands)
8068 	 */
8069 
8070 	if (mbox_pending)
8071 		/* process and rearm the EQ */
8072 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
8073 	else
8074 		/* Always clear and re-arm the EQ */
8075 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
8076 
8077 	return mbox_pending;
8078 
8079 }
8080 
8081 /**
8082  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
8083  * @phba: Pointer to HBA context object.
8084  *
8085  * This function is called from worker thread when a mailbox command times out.
8086  * The caller is not required to hold any locks. This function will reset the
8087  * HBA and recover all the pending commands.
8088  **/
8089 void
8090 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
8091 {
8092 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
8093 	MAILBOX_t *mb = NULL;
8094 
8095 	struct lpfc_sli *psli = &phba->sli;
8096 
8097 	/* If the mailbox completed, process the completion and return */
8098 	if (lpfc_sli4_process_missed_mbox_completions(phba))
8099 		return;
8100 
8101 	if (pmbox != NULL)
8102 		mb = &pmbox->u.mb;
8103 	/* Check the pmbox pointer first.  There is a race condition
8104 	 * between the mbox timeout handler getting executed in the
8105 	 * worklist and the mailbox actually completing. When this
8106 	 * race condition occurs, the mbox_active will be NULL.
8107 	 */
8108 	spin_lock_irq(&phba->hbalock);
8109 	if (pmbox == NULL) {
8110 		lpfc_printf_log(phba, KERN_WARNING,
8111 				LOG_MBOX | LOG_SLI,
8112 				"0353 Active Mailbox cleared - mailbox timeout "
8113 				"exiting\n");
8114 		spin_unlock_irq(&phba->hbalock);
8115 		return;
8116 	}
8117 
8118 	/* Mbox cmd <mbxCommand> timeout */
8119 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8120 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
8121 			mb->mbxCommand,
8122 			phba->pport->port_state,
8123 			phba->sli.sli_flag,
8124 			phba->sli.mbox_active);
8125 	spin_unlock_irq(&phba->hbalock);
8126 
8127 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
8128 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
8129 	 * it to fail all outstanding SCSI IO.
8130 	 */
8131 	spin_lock_irq(&phba->pport->work_port_lock);
8132 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
8133 	spin_unlock_irq(&phba->pport->work_port_lock);
8134 	spin_lock_irq(&phba->hbalock);
8135 	phba->link_state = LPFC_LINK_UNKNOWN;
8136 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
8137 	spin_unlock_irq(&phba->hbalock);
8138 
8139 	lpfc_sli_abort_fcp_rings(phba);
8140 
8141 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8142 			"0345 Resetting board due to mailbox timeout\n");
8143 
8144 	/* Reset the HBA device */
8145 	lpfc_reset_hba(phba);
8146 }
8147 
8148 /**
8149  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
8150  * @phba: Pointer to HBA context object.
8151  * @pmbox: Pointer to mailbox object.
8152  * @flag: Flag indicating how the mailbox need to be processed.
8153  *
8154  * This function is called by discovery code and HBA management code
8155  * to submit a mailbox command to firmware with SLI-3 interface spec. This
8156  * function gets the hbalock to protect the data structures.
8157  * The mailbox command can be submitted in polling mode, in which case
8158  * this function will wait in a polling loop for the completion of the
8159  * mailbox.
8160  * If the mailbox is submitted in no_wait mode (not polling) the
8161  * function will submit the command and returns immediately without waiting
8162  * for the mailbox completion. The no_wait is supported only when HBA
8163  * is in SLI2/SLI3 mode - interrupts are enabled.
8164  * The SLI interface allows only one mailbox pending at a time. If the
8165  * mailbox is issued in polling mode and there is already a mailbox
8166  * pending, then the function will return an error. If the mailbox is issued
8167  * in NO_WAIT mode and there is a mailbox pending already, the function
8168  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
8169  * The sli layer owns the mailbox object until the completion of mailbox
8170  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
8171  * return codes the caller owns the mailbox command after the return of
8172  * the function.
8173  **/
8174 static int
8175 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
8176 		       uint32_t flag)
8177 {
8178 	MAILBOX_t *mbx;
8179 	struct lpfc_sli *psli = &phba->sli;
8180 	uint32_t status, evtctr;
8181 	uint32_t ha_copy, hc_copy;
8182 	int i;
8183 	unsigned long timeout;
8184 	unsigned long drvr_flag = 0;
8185 	uint32_t word0, ldata;
8186 	void __iomem *to_slim;
8187 	int processing_queue = 0;
8188 
8189 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
8190 	if (!pmbox) {
8191 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8192 		/* processing mbox queue from intr_handler */
8193 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8194 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8195 			return MBX_SUCCESS;
8196 		}
8197 		processing_queue = 1;
8198 		pmbox = lpfc_mbox_get(phba);
8199 		if (!pmbox) {
8200 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8201 			return MBX_SUCCESS;
8202 		}
8203 	}
8204 
8205 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
8206 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
8207 		if(!pmbox->vport) {
8208 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8209 			lpfc_printf_log(phba, KERN_ERR,
8210 					LOG_MBOX | LOG_VPORT,
8211 					"1806 Mbox x%x failed. No vport\n",
8212 					pmbox->u.mb.mbxCommand);
8213 			dump_stack();
8214 			goto out_not_finished;
8215 		}
8216 	}
8217 
8218 	/* If the PCI channel is in offline state, do not post mbox. */
8219 	if (unlikely(pci_channel_offline(phba->pcidev))) {
8220 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8221 		goto out_not_finished;
8222 	}
8223 
8224 	/* If HBA has a deferred error attention, fail the iocb. */
8225 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
8226 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8227 		goto out_not_finished;
8228 	}
8229 
8230 	psli = &phba->sli;
8231 
8232 	mbx = &pmbox->u.mb;
8233 	status = MBX_SUCCESS;
8234 
8235 	if (phba->link_state == LPFC_HBA_ERROR) {
8236 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8237 
8238 		/* Mbox command <mbxCommand> cannot issue */
8239 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8240 				"(%d):0311 Mailbox command x%x cannot "
8241 				"issue Data: x%x x%x\n",
8242 				pmbox->vport ? pmbox->vport->vpi : 0,
8243 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8244 		goto out_not_finished;
8245 	}
8246 
8247 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
8248 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
8249 			!(hc_copy & HC_MBINT_ENA)) {
8250 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8251 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8252 				"(%d):2528 Mailbox command x%x cannot "
8253 				"issue Data: x%x x%x\n",
8254 				pmbox->vport ? pmbox->vport->vpi : 0,
8255 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8256 			goto out_not_finished;
8257 		}
8258 	}
8259 
8260 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8261 		/* Polling for a mbox command when another one is already active
8262 		 * is not allowed in SLI. Also, the driver must have established
8263 		 * SLI2 mode to queue and process multiple mbox commands.
8264 		 */
8265 
8266 		if (flag & MBX_POLL) {
8267 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8268 
8269 			/* Mbox command <mbxCommand> cannot issue */
8270 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8271 					"(%d):2529 Mailbox command x%x "
8272 					"cannot issue Data: x%x x%x\n",
8273 					pmbox->vport ? pmbox->vport->vpi : 0,
8274 					pmbox->u.mb.mbxCommand,
8275 					psli->sli_flag, flag);
8276 			goto out_not_finished;
8277 		}
8278 
8279 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
8280 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8281 			/* Mbox command <mbxCommand> cannot issue */
8282 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8283 					"(%d):2530 Mailbox command x%x "
8284 					"cannot issue Data: x%x x%x\n",
8285 					pmbox->vport ? pmbox->vport->vpi : 0,
8286 					pmbox->u.mb.mbxCommand,
8287 					psli->sli_flag, flag);
8288 			goto out_not_finished;
8289 		}
8290 
8291 		/* Another mailbox command is still being processed, queue this
8292 		 * command to be processed later.
8293 		 */
8294 		lpfc_mbox_put(phba, pmbox);
8295 
8296 		/* Mbox cmd issue - BUSY */
8297 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8298 				"(%d):0308 Mbox cmd issue - BUSY Data: "
8299 				"x%x x%x x%x x%x\n",
8300 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
8301 				mbx->mbxCommand,
8302 				phba->pport ? phba->pport->port_state : 0xff,
8303 				psli->sli_flag, flag);
8304 
8305 		psli->slistat.mbox_busy++;
8306 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8307 
8308 		if (pmbox->vport) {
8309 			lpfc_debugfs_disc_trc(pmbox->vport,
8310 				LPFC_DISC_TRC_MBOX_VPORT,
8311 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
8312 				(uint32_t)mbx->mbxCommand,
8313 				mbx->un.varWords[0], mbx->un.varWords[1]);
8314 		}
8315 		else {
8316 			lpfc_debugfs_disc_trc(phba->pport,
8317 				LPFC_DISC_TRC_MBOX,
8318 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
8319 				(uint32_t)mbx->mbxCommand,
8320 				mbx->un.varWords[0], mbx->un.varWords[1]);
8321 		}
8322 
8323 		return MBX_BUSY;
8324 	}
8325 
8326 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8327 
8328 	/* If we are not polling, we MUST be in SLI2 mode */
8329 	if (flag != MBX_POLL) {
8330 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
8331 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
8332 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8333 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8334 			/* Mbox command <mbxCommand> cannot issue */
8335 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8336 					"(%d):2531 Mailbox command x%x "
8337 					"cannot issue Data: x%x x%x\n",
8338 					pmbox->vport ? pmbox->vport->vpi : 0,
8339 					pmbox->u.mb.mbxCommand,
8340 					psli->sli_flag, flag);
8341 			goto out_not_finished;
8342 		}
8343 		/* timeout active mbox command */
8344 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8345 					   1000);
8346 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
8347 	}
8348 
8349 	/* Mailbox cmd <cmd> issue */
8350 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8351 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
8352 			"x%x\n",
8353 			pmbox->vport ? pmbox->vport->vpi : 0,
8354 			mbx->mbxCommand,
8355 			phba->pport ? phba->pport->port_state : 0xff,
8356 			psli->sli_flag, flag);
8357 
8358 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
8359 		if (pmbox->vport) {
8360 			lpfc_debugfs_disc_trc(pmbox->vport,
8361 				LPFC_DISC_TRC_MBOX_VPORT,
8362 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
8363 				(uint32_t)mbx->mbxCommand,
8364 				mbx->un.varWords[0], mbx->un.varWords[1]);
8365 		}
8366 		else {
8367 			lpfc_debugfs_disc_trc(phba->pport,
8368 				LPFC_DISC_TRC_MBOX,
8369 				"MBOX Send:       cmd:x%x mb:x%x x%x",
8370 				(uint32_t)mbx->mbxCommand,
8371 				mbx->un.varWords[0], mbx->un.varWords[1]);
8372 		}
8373 	}
8374 
8375 	psli->slistat.mbox_cmd++;
8376 	evtctr = psli->slistat.mbox_event;
8377 
8378 	/* next set own bit for the adapter and copy over command word */
8379 	mbx->mbxOwner = OWN_CHIP;
8380 
8381 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8382 		/* Populate mbox extension offset word. */
8383 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
8384 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8385 				= (uint8_t *)phba->mbox_ext
8386 				  - (uint8_t *)phba->mbox;
8387 		}
8388 
8389 		/* Copy the mailbox extension data */
8390 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
8391 			lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
8392 					      (uint8_t *)phba->mbox_ext,
8393 					      pmbox->in_ext_byte_len);
8394 		}
8395 		/* Copy command data to host SLIM area */
8396 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
8397 	} else {
8398 		/* Populate mbox extension offset word. */
8399 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
8400 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8401 				= MAILBOX_HBA_EXT_OFFSET;
8402 
8403 		/* Copy the mailbox extension data */
8404 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
8405 			lpfc_memcpy_to_slim(phba->MBslimaddr +
8406 				MAILBOX_HBA_EXT_OFFSET,
8407 				pmbox->ctx_buf, pmbox->in_ext_byte_len);
8408 
8409 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8410 			/* copy command data into host mbox for cmpl */
8411 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
8412 					      MAILBOX_CMD_SIZE);
8413 
8414 		/* First copy mbox command data to HBA SLIM, skip past first
8415 		   word */
8416 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
8417 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
8418 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
8419 
8420 		/* Next copy over first word, with mbxOwner set */
8421 		ldata = *((uint32_t *)mbx);
8422 		to_slim = phba->MBslimaddr;
8423 		writel(ldata, to_slim);
8424 		readl(to_slim); /* flush */
8425 
8426 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8427 			/* switch over to host mailbox */
8428 			psli->sli_flag |= LPFC_SLI_ACTIVE;
8429 	}
8430 
8431 	wmb();
8432 
8433 	switch (flag) {
8434 	case MBX_NOWAIT:
8435 		/* Set up reference to mailbox command */
8436 		psli->mbox_active = pmbox;
8437 		/* Interrupt board to do it */
8438 		writel(CA_MBATT, phba->CAregaddr);
8439 		readl(phba->CAregaddr); /* flush */
8440 		/* Don't wait for it to finish, just return */
8441 		break;
8442 
8443 	case MBX_POLL:
8444 		/* Set up null reference to mailbox command */
8445 		psli->mbox_active = NULL;
8446 		/* Interrupt board to do it */
8447 		writel(CA_MBATT, phba->CAregaddr);
8448 		readl(phba->CAregaddr); /* flush */
8449 
8450 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8451 			/* First read mbox status word */
8452 			word0 = *((uint32_t *)phba->mbox);
8453 			word0 = le32_to_cpu(word0);
8454 		} else {
8455 			/* First read mbox status word */
8456 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
8457 				spin_unlock_irqrestore(&phba->hbalock,
8458 						       drvr_flag);
8459 				goto out_not_finished;
8460 			}
8461 		}
8462 
8463 		/* Read the HBA Host Attention Register */
8464 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8465 			spin_unlock_irqrestore(&phba->hbalock,
8466 						       drvr_flag);
8467 			goto out_not_finished;
8468 		}
8469 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8470 							1000) + jiffies;
8471 		i = 0;
8472 		/* Wait for command to complete */
8473 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
8474 		       (!(ha_copy & HA_MBATT) &&
8475 			(phba->link_state > LPFC_WARM_START))) {
8476 			if (time_after(jiffies, timeout)) {
8477 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8478 				spin_unlock_irqrestore(&phba->hbalock,
8479 						       drvr_flag);
8480 				goto out_not_finished;
8481 			}
8482 
8483 			/* Check if we took a mbox interrupt while we were
8484 			   polling */
8485 			if (((word0 & OWN_CHIP) != OWN_CHIP)
8486 			    && (evtctr != psli->slistat.mbox_event))
8487 				break;
8488 
8489 			if (i++ > 10) {
8490 				spin_unlock_irqrestore(&phba->hbalock,
8491 						       drvr_flag);
8492 				msleep(1);
8493 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
8494 			}
8495 
8496 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8497 				/* First copy command data */
8498 				word0 = *((uint32_t *)phba->mbox);
8499 				word0 = le32_to_cpu(word0);
8500 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
8501 					MAILBOX_t *slimmb;
8502 					uint32_t slimword0;
8503 					/* Check real SLIM for any errors */
8504 					slimword0 = readl(phba->MBslimaddr);
8505 					slimmb = (MAILBOX_t *) & slimword0;
8506 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
8507 					    && slimmb->mbxStatus) {
8508 						psli->sli_flag &=
8509 						    ~LPFC_SLI_ACTIVE;
8510 						word0 = slimword0;
8511 					}
8512 				}
8513 			} else {
8514 				/* First copy command data */
8515 				word0 = readl(phba->MBslimaddr);
8516 			}
8517 			/* Read the HBA Host Attention Register */
8518 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8519 				spin_unlock_irqrestore(&phba->hbalock,
8520 						       drvr_flag);
8521 				goto out_not_finished;
8522 			}
8523 		}
8524 
8525 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8526 			/* copy results back to user */
8527 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
8528 						MAILBOX_CMD_SIZE);
8529 			/* Copy the mailbox extension data */
8530 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8531 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
8532 						      pmbox->ctx_buf,
8533 						      pmbox->out_ext_byte_len);
8534 			}
8535 		} else {
8536 			/* First copy command data */
8537 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
8538 						MAILBOX_CMD_SIZE);
8539 			/* Copy the mailbox extension data */
8540 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8541 				lpfc_memcpy_from_slim(
8542 					pmbox->ctx_buf,
8543 					phba->MBslimaddr +
8544 					MAILBOX_HBA_EXT_OFFSET,
8545 					pmbox->out_ext_byte_len);
8546 			}
8547 		}
8548 
8549 		writel(HA_MBATT, phba->HAregaddr);
8550 		readl(phba->HAregaddr); /* flush */
8551 
8552 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8553 		status = mbx->mbxStatus;
8554 	}
8555 
8556 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8557 	return status;
8558 
8559 out_not_finished:
8560 	if (processing_queue) {
8561 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
8562 		lpfc_mbox_cmpl_put(phba, pmbox);
8563 	}
8564 	return MBX_NOT_FINISHED;
8565 }
8566 
8567 /**
8568  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
8569  * @phba: Pointer to HBA context object.
8570  *
8571  * The function blocks the posting of SLI4 asynchronous mailbox commands from
8572  * the driver internal pending mailbox queue. It will then try to wait out the
8573  * possible outstanding mailbox command before return.
8574  *
8575  * Returns:
8576  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
8577  * 	the outstanding mailbox command timed out.
8578  **/
8579 static int
8580 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
8581 {
8582 	struct lpfc_sli *psli = &phba->sli;
8583 	int rc = 0;
8584 	unsigned long timeout = 0;
8585 
8586 	/* Mark the asynchronous mailbox command posting as blocked */
8587 	spin_lock_irq(&phba->hbalock);
8588 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
8589 	/* Determine how long we might wait for the active mailbox
8590 	 * command to be gracefully completed by firmware.
8591 	 */
8592 	if (phba->sli.mbox_active)
8593 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
8594 						phba->sli.mbox_active) *
8595 						1000) + jiffies;
8596 	spin_unlock_irq(&phba->hbalock);
8597 
8598 	/* Make sure the mailbox is really active */
8599 	if (timeout)
8600 		lpfc_sli4_process_missed_mbox_completions(phba);
8601 
8602 	/* Wait for the outstnading mailbox command to complete */
8603 	while (phba->sli.mbox_active) {
8604 		/* Check active mailbox complete status every 2ms */
8605 		msleep(2);
8606 		if (time_after(jiffies, timeout)) {
8607 			/* Timeout, marked the outstanding cmd not complete */
8608 			rc = 1;
8609 			break;
8610 		}
8611 	}
8612 
8613 	/* Can not cleanly block async mailbox command, fails it */
8614 	if (rc) {
8615 		spin_lock_irq(&phba->hbalock);
8616 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8617 		spin_unlock_irq(&phba->hbalock);
8618 	}
8619 	return rc;
8620 }
8621 
8622 /**
8623  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
8624  * @phba: Pointer to HBA context object.
8625  *
8626  * The function unblocks and resume posting of SLI4 asynchronous mailbox
8627  * commands from the driver internal pending mailbox queue. It makes sure
8628  * that there is no outstanding mailbox command before resuming posting
8629  * asynchronous mailbox commands. If, for any reason, there is outstanding
8630  * mailbox command, it will try to wait it out before resuming asynchronous
8631  * mailbox command posting.
8632  **/
8633 static void
8634 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
8635 {
8636 	struct lpfc_sli *psli = &phba->sli;
8637 
8638 	spin_lock_irq(&phba->hbalock);
8639 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8640 		/* Asynchronous mailbox posting is not blocked, do nothing */
8641 		spin_unlock_irq(&phba->hbalock);
8642 		return;
8643 	}
8644 
8645 	/* Outstanding synchronous mailbox command is guaranteed to be done,
8646 	 * successful or timeout, after timing-out the outstanding mailbox
8647 	 * command shall always be removed, so just unblock posting async
8648 	 * mailbox command and resume
8649 	 */
8650 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8651 	spin_unlock_irq(&phba->hbalock);
8652 
8653 	/* wake up worker thread to post asynchronous mailbox command */
8654 	lpfc_worker_wake_up(phba);
8655 }
8656 
8657 /**
8658  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
8659  * @phba: Pointer to HBA context object.
8660  * @mboxq: Pointer to mailbox object.
8661  *
8662  * The function waits for the bootstrap mailbox register ready bit from
8663  * port for twice the regular mailbox command timeout value.
8664  *
8665  *      0 - no timeout on waiting for bootstrap mailbox register ready.
8666  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
8667  **/
8668 static int
8669 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8670 {
8671 	uint32_t db_ready;
8672 	unsigned long timeout;
8673 	struct lpfc_register bmbx_reg;
8674 
8675 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
8676 				   * 1000) + jiffies;
8677 
8678 	do {
8679 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
8680 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
8681 		if (!db_ready)
8682 			mdelay(2);
8683 
8684 		if (time_after(jiffies, timeout))
8685 			return MBXERR_ERROR;
8686 	} while (!db_ready);
8687 
8688 	return 0;
8689 }
8690 
8691 /**
8692  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
8693  * @phba: Pointer to HBA context object.
8694  * @mboxq: Pointer to mailbox object.
8695  *
8696  * The function posts a mailbox to the port.  The mailbox is expected
8697  * to be comletely filled in and ready for the port to operate on it.
8698  * This routine executes a synchronous completion operation on the
8699  * mailbox by polling for its completion.
8700  *
8701  * The caller must not be holding any locks when calling this routine.
8702  *
8703  * Returns:
8704  *	MBX_SUCCESS - mailbox posted successfully
8705  *	Any of the MBX error values.
8706  **/
8707 static int
8708 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8709 {
8710 	int rc = MBX_SUCCESS;
8711 	unsigned long iflag;
8712 	uint32_t mcqe_status;
8713 	uint32_t mbx_cmnd;
8714 	struct lpfc_sli *psli = &phba->sli;
8715 	struct lpfc_mqe *mb = &mboxq->u.mqe;
8716 	struct lpfc_bmbx_create *mbox_rgn;
8717 	struct dma_address *dma_address;
8718 
8719 	/*
8720 	 * Only one mailbox can be active to the bootstrap mailbox region
8721 	 * at a time and there is no queueing provided.
8722 	 */
8723 	spin_lock_irqsave(&phba->hbalock, iflag);
8724 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8725 		spin_unlock_irqrestore(&phba->hbalock, iflag);
8726 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8727 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
8728 				"cannot issue Data: x%x x%x\n",
8729 				mboxq->vport ? mboxq->vport->vpi : 0,
8730 				mboxq->u.mb.mbxCommand,
8731 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8732 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8733 				psli->sli_flag, MBX_POLL);
8734 		return MBXERR_ERROR;
8735 	}
8736 	/* The server grabs the token and owns it until release */
8737 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8738 	phba->sli.mbox_active = mboxq;
8739 	spin_unlock_irqrestore(&phba->hbalock, iflag);
8740 
8741 	/* wait for bootstrap mbox register for readyness */
8742 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8743 	if (rc)
8744 		goto exit;
8745 	/*
8746 	 * Initialize the bootstrap memory region to avoid stale data areas
8747 	 * in the mailbox post.  Then copy the caller's mailbox contents to
8748 	 * the bmbx mailbox region.
8749 	 */
8750 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
8751 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
8752 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
8753 			       sizeof(struct lpfc_mqe));
8754 
8755 	/* Post the high mailbox dma address to the port and wait for ready. */
8756 	dma_address = &phba->sli4_hba.bmbx.dma_address;
8757 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
8758 
8759 	/* wait for bootstrap mbox register for hi-address write done */
8760 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8761 	if (rc)
8762 		goto exit;
8763 
8764 	/* Post the low mailbox dma address to the port. */
8765 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
8766 
8767 	/* wait for bootstrap mbox register for low address write done */
8768 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8769 	if (rc)
8770 		goto exit;
8771 
8772 	/*
8773 	 * Read the CQ to ensure the mailbox has completed.
8774 	 * If so, update the mailbox status so that the upper layers
8775 	 * can complete the request normally.
8776 	 */
8777 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
8778 			       sizeof(struct lpfc_mqe));
8779 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
8780 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
8781 			       sizeof(struct lpfc_mcqe));
8782 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
8783 	/*
8784 	 * When the CQE status indicates a failure and the mailbox status
8785 	 * indicates success then copy the CQE status into the mailbox status
8786 	 * (and prefix it with x4000).
8787 	 */
8788 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
8789 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
8790 			bf_set(lpfc_mqe_status, mb,
8791 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
8792 		rc = MBXERR_ERROR;
8793 	} else
8794 		lpfc_sli4_swap_str(phba, mboxq);
8795 
8796 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8797 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
8798 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
8799 			" x%x x%x CQ: x%x x%x x%x x%x\n",
8800 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
8801 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8802 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8803 			bf_get(lpfc_mqe_status, mb),
8804 			mb->un.mb_words[0], mb->un.mb_words[1],
8805 			mb->un.mb_words[2], mb->un.mb_words[3],
8806 			mb->un.mb_words[4], mb->un.mb_words[5],
8807 			mb->un.mb_words[6], mb->un.mb_words[7],
8808 			mb->un.mb_words[8], mb->un.mb_words[9],
8809 			mb->un.mb_words[10], mb->un.mb_words[11],
8810 			mb->un.mb_words[12], mboxq->mcqe.word0,
8811 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
8812 			mboxq->mcqe.trailer);
8813 exit:
8814 	/* We are holding the token, no needed for lock when release */
8815 	spin_lock_irqsave(&phba->hbalock, iflag);
8816 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8817 	phba->sli.mbox_active = NULL;
8818 	spin_unlock_irqrestore(&phba->hbalock, iflag);
8819 	return rc;
8820 }
8821 
8822 /**
8823  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
8824  * @phba: Pointer to HBA context object.
8825  * @pmbox: Pointer to mailbox object.
8826  * @flag: Flag indicating how the mailbox need to be processed.
8827  *
8828  * This function is called by discovery code and HBA management code to submit
8829  * a mailbox command to firmware with SLI-4 interface spec.
8830  *
8831  * Return codes the caller owns the mailbox command after the return of the
8832  * function.
8833  **/
8834 static int
8835 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
8836 		       uint32_t flag)
8837 {
8838 	struct lpfc_sli *psli = &phba->sli;
8839 	unsigned long iflags;
8840 	int rc;
8841 
8842 	/* dump from issue mailbox command if setup */
8843 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
8844 
8845 	rc = lpfc_mbox_dev_check(phba);
8846 	if (unlikely(rc)) {
8847 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8848 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
8849 				"cannot issue Data: x%x x%x\n",
8850 				mboxq->vport ? mboxq->vport->vpi : 0,
8851 				mboxq->u.mb.mbxCommand,
8852 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8853 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8854 				psli->sli_flag, flag);
8855 		goto out_not_finished;
8856 	}
8857 
8858 	/* Detect polling mode and jump to a handler */
8859 	if (!phba->sli4_hba.intr_enable) {
8860 		if (flag == MBX_POLL)
8861 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
8862 		else
8863 			rc = -EIO;
8864 		if (rc != MBX_SUCCESS)
8865 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8866 					"(%d):2541 Mailbox command x%x "
8867 					"(x%x/x%x) failure: "
8868 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
8869 					"Data: x%x x%x\n,",
8870 					mboxq->vport ? mboxq->vport->vpi : 0,
8871 					mboxq->u.mb.mbxCommand,
8872 					lpfc_sli_config_mbox_subsys_get(phba,
8873 									mboxq),
8874 					lpfc_sli_config_mbox_opcode_get(phba,
8875 									mboxq),
8876 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
8877 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
8878 					bf_get(lpfc_mcqe_ext_status,
8879 					       &mboxq->mcqe),
8880 					psli->sli_flag, flag);
8881 		return rc;
8882 	} else if (flag == MBX_POLL) {
8883 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8884 				"(%d):2542 Try to issue mailbox command "
8885 				"x%x (x%x/x%x) synchronously ahead of async "
8886 				"mailbox command queue: x%x x%x\n",
8887 				mboxq->vport ? mboxq->vport->vpi : 0,
8888 				mboxq->u.mb.mbxCommand,
8889 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8890 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8891 				psli->sli_flag, flag);
8892 		/* Try to block the asynchronous mailbox posting */
8893 		rc = lpfc_sli4_async_mbox_block(phba);
8894 		if (!rc) {
8895 			/* Successfully blocked, now issue sync mbox cmd */
8896 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
8897 			if (rc != MBX_SUCCESS)
8898 				lpfc_printf_log(phba, KERN_WARNING,
8899 					LOG_MBOX | LOG_SLI,
8900 					"(%d):2597 Sync Mailbox command "
8901 					"x%x (x%x/x%x) failure: "
8902 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
8903 					"Data: x%x x%x\n,",
8904 					mboxq->vport ? mboxq->vport->vpi : 0,
8905 					mboxq->u.mb.mbxCommand,
8906 					lpfc_sli_config_mbox_subsys_get(phba,
8907 									mboxq),
8908 					lpfc_sli_config_mbox_opcode_get(phba,
8909 									mboxq),
8910 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
8911 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
8912 					bf_get(lpfc_mcqe_ext_status,
8913 					       &mboxq->mcqe),
8914 					psli->sli_flag, flag);
8915 			/* Unblock the async mailbox posting afterward */
8916 			lpfc_sli4_async_mbox_unblock(phba);
8917 		}
8918 		return rc;
8919 	}
8920 
8921 	/* Now, interrupt mode asynchronous mailbox command */
8922 	rc = lpfc_mbox_cmd_check(phba, mboxq);
8923 	if (rc) {
8924 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8925 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
8926 				"cannot issue Data: x%x x%x\n",
8927 				mboxq->vport ? mboxq->vport->vpi : 0,
8928 				mboxq->u.mb.mbxCommand,
8929 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8930 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8931 				psli->sli_flag, flag);
8932 		goto out_not_finished;
8933 	}
8934 
8935 	/* Put the mailbox command to the driver internal FIFO */
8936 	psli->slistat.mbox_busy++;
8937 	spin_lock_irqsave(&phba->hbalock, iflags);
8938 	lpfc_mbox_put(phba, mboxq);
8939 	spin_unlock_irqrestore(&phba->hbalock, iflags);
8940 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8941 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
8942 			"x%x (x%x/x%x) x%x x%x x%x\n",
8943 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
8944 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8945 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8946 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8947 			phba->pport->port_state,
8948 			psli->sli_flag, MBX_NOWAIT);
8949 	/* Wake up worker thread to transport mailbox command from head */
8950 	lpfc_worker_wake_up(phba);
8951 
8952 	return MBX_BUSY;
8953 
8954 out_not_finished:
8955 	return MBX_NOT_FINISHED;
8956 }
8957 
8958 /**
8959  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
8960  * @phba: Pointer to HBA context object.
8961  *
8962  * This function is called by worker thread to send a mailbox command to
8963  * SLI4 HBA firmware.
8964  *
8965  **/
8966 int
8967 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
8968 {
8969 	struct lpfc_sli *psli = &phba->sli;
8970 	LPFC_MBOXQ_t *mboxq;
8971 	int rc = MBX_SUCCESS;
8972 	unsigned long iflags;
8973 	struct lpfc_mqe *mqe;
8974 	uint32_t mbx_cmnd;
8975 
8976 	/* Check interrupt mode before post async mailbox command */
8977 	if (unlikely(!phba->sli4_hba.intr_enable))
8978 		return MBX_NOT_FINISHED;
8979 
8980 	/* Check for mailbox command service token */
8981 	spin_lock_irqsave(&phba->hbalock, iflags);
8982 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8983 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8984 		return MBX_NOT_FINISHED;
8985 	}
8986 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8987 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8988 		return MBX_NOT_FINISHED;
8989 	}
8990 	if (unlikely(phba->sli.mbox_active)) {
8991 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8992 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8993 				"0384 There is pending active mailbox cmd\n");
8994 		return MBX_NOT_FINISHED;
8995 	}
8996 	/* Take the mailbox command service token */
8997 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8998 
8999 	/* Get the next mailbox command from head of queue */
9000 	mboxq = lpfc_mbox_get(phba);
9001 
9002 	/* If no more mailbox command waiting for post, we're done */
9003 	if (!mboxq) {
9004 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9005 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9006 		return MBX_SUCCESS;
9007 	}
9008 	phba->sli.mbox_active = mboxq;
9009 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9010 
9011 	/* Check device readiness for posting mailbox command */
9012 	rc = lpfc_mbox_dev_check(phba);
9013 	if (unlikely(rc))
9014 		/* Driver clean routine will clean up pending mailbox */
9015 		goto out_not_finished;
9016 
9017 	/* Prepare the mbox command to be posted */
9018 	mqe = &mboxq->u.mqe;
9019 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
9020 
9021 	/* Start timer for the mbox_tmo and log some mailbox post messages */
9022 	mod_timer(&psli->mbox_tmo, (jiffies +
9023 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
9024 
9025 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9026 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
9027 			"x%x x%x\n",
9028 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
9029 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9030 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9031 			phba->pport->port_state, psli->sli_flag);
9032 
9033 	if (mbx_cmnd != MBX_HEARTBEAT) {
9034 		if (mboxq->vport) {
9035 			lpfc_debugfs_disc_trc(mboxq->vport,
9036 				LPFC_DISC_TRC_MBOX_VPORT,
9037 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9038 				mbx_cmnd, mqe->un.mb_words[0],
9039 				mqe->un.mb_words[1]);
9040 		} else {
9041 			lpfc_debugfs_disc_trc(phba->pport,
9042 				LPFC_DISC_TRC_MBOX,
9043 				"MBOX Send: cmd:x%x mb:x%x x%x",
9044 				mbx_cmnd, mqe->un.mb_words[0],
9045 				mqe->un.mb_words[1]);
9046 		}
9047 	}
9048 	psli->slistat.mbox_cmd++;
9049 
9050 	/* Post the mailbox command to the port */
9051 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
9052 	if (rc != MBX_SUCCESS) {
9053 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
9054 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
9055 				"cannot issue Data: x%x x%x\n",
9056 				mboxq->vport ? mboxq->vport->vpi : 0,
9057 				mboxq->u.mb.mbxCommand,
9058 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9059 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9060 				psli->sli_flag, MBX_NOWAIT);
9061 		goto out_not_finished;
9062 	}
9063 
9064 	return rc;
9065 
9066 out_not_finished:
9067 	spin_lock_irqsave(&phba->hbalock, iflags);
9068 	if (phba->sli.mbox_active) {
9069 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
9070 		__lpfc_mbox_cmpl_put(phba, mboxq);
9071 		/* Release the token */
9072 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9073 		phba->sli.mbox_active = NULL;
9074 	}
9075 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9076 
9077 	return MBX_NOT_FINISHED;
9078 }
9079 
9080 /**
9081  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
9082  * @phba: Pointer to HBA context object.
9083  * @pmbox: Pointer to mailbox object.
9084  * @flag: Flag indicating how the mailbox need to be processed.
9085  *
9086  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
9087  * the API jump table function pointer from the lpfc_hba struct.
9088  *
9089  * Return codes the caller owns the mailbox command after the return of the
9090  * function.
9091  **/
9092 int
9093 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
9094 {
9095 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
9096 }
9097 
9098 /**
9099  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
9100  * @phba: The hba struct for which this call is being executed.
9101  * @dev_grp: The HBA PCI-Device group number.
9102  *
9103  * This routine sets up the mbox interface API function jump table in @phba
9104  * struct.
9105  * Returns: 0 - success, -ENODEV - failure.
9106  **/
9107 int
9108 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
9109 {
9110 
9111 	switch (dev_grp) {
9112 	case LPFC_PCI_DEV_LP:
9113 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
9114 		phba->lpfc_sli_handle_slow_ring_event =
9115 				lpfc_sli_handle_slow_ring_event_s3;
9116 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
9117 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
9118 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
9119 		break;
9120 	case LPFC_PCI_DEV_OC:
9121 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
9122 		phba->lpfc_sli_handle_slow_ring_event =
9123 				lpfc_sli_handle_slow_ring_event_s4;
9124 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
9125 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
9126 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
9127 		break;
9128 	default:
9129 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9130 				"1420 Invalid HBA PCI-device group: 0x%x\n",
9131 				dev_grp);
9132 		return -ENODEV;
9133 		break;
9134 	}
9135 	return 0;
9136 }
9137 
9138 /**
9139  * __lpfc_sli_ringtx_put - Add an iocb to the txq
9140  * @phba: Pointer to HBA context object.
9141  * @pring: Pointer to driver SLI ring object.
9142  * @piocb: Pointer to address of newly added command iocb.
9143  *
9144  * This function is called with hbalock held for SLI3 ports or
9145  * the ring lock held for SLI4 ports to add a command
9146  * iocb to the txq when SLI layer cannot submit the command iocb
9147  * to the ring.
9148  **/
9149 void
9150 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9151 		    struct lpfc_iocbq *piocb)
9152 {
9153 	if (phba->sli_rev == LPFC_SLI_REV4)
9154 		lockdep_assert_held(&pring->ring_lock);
9155 	else
9156 		lockdep_assert_held(&phba->hbalock);
9157 	/* Insert the caller's iocb in the txq tail for later processing. */
9158 	list_add_tail(&piocb->list, &pring->txq);
9159 }
9160 
9161 /**
9162  * lpfc_sli_next_iocb - Get the next iocb in the txq
9163  * @phba: Pointer to HBA context object.
9164  * @pring: Pointer to driver SLI ring object.
9165  * @piocb: Pointer to address of newly added command iocb.
9166  *
9167  * This function is called with hbalock held before a new
9168  * iocb is submitted to the firmware. This function checks
9169  * txq to flush the iocbs in txq to Firmware before
9170  * submitting new iocbs to the Firmware.
9171  * If there are iocbs in the txq which need to be submitted
9172  * to firmware, lpfc_sli_next_iocb returns the first element
9173  * of the txq after dequeuing it from txq.
9174  * If there is no iocb in the txq then the function will return
9175  * *piocb and *piocb is set to NULL. Caller needs to check
9176  * *piocb to find if there are more commands in the txq.
9177  **/
9178 static struct lpfc_iocbq *
9179 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9180 		   struct lpfc_iocbq **piocb)
9181 {
9182 	struct lpfc_iocbq * nextiocb;
9183 
9184 	lockdep_assert_held(&phba->hbalock);
9185 
9186 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
9187 	if (!nextiocb) {
9188 		nextiocb = *piocb;
9189 		*piocb = NULL;
9190 	}
9191 
9192 	return nextiocb;
9193 }
9194 
9195 /**
9196  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
9197  * @phba: Pointer to HBA context object.
9198  * @ring_number: SLI ring number to issue iocb on.
9199  * @piocb: Pointer to command iocb.
9200  * @flag: Flag indicating if this command can be put into txq.
9201  *
9202  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
9203  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
9204  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
9205  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
9206  * this function allows only iocbs for posting buffers. This function finds
9207  * next available slot in the command ring and posts the command to the
9208  * available slot and writes the port attention register to request HBA start
9209  * processing new iocb. If there is no slot available in the ring and
9210  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
9211  * the function returns IOCB_BUSY.
9212  *
9213  * This function is called with hbalock held. The function will return success
9214  * after it successfully submit the iocb to firmware or after adding to the
9215  * txq.
9216  **/
9217 static int
9218 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
9219 		    struct lpfc_iocbq *piocb, uint32_t flag)
9220 {
9221 	struct lpfc_iocbq *nextiocb;
9222 	IOCB_t *iocb;
9223 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
9224 
9225 	lockdep_assert_held(&phba->hbalock);
9226 
9227 	if (piocb->iocb_cmpl && (!piocb->vport) &&
9228 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
9229 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
9230 		lpfc_printf_log(phba, KERN_ERR,
9231 				LOG_SLI | LOG_VPORT,
9232 				"1807 IOCB x%x failed. No vport\n",
9233 				piocb->iocb.ulpCommand);
9234 		dump_stack();
9235 		return IOCB_ERROR;
9236 	}
9237 
9238 
9239 	/* If the PCI channel is in offline state, do not post iocbs. */
9240 	if (unlikely(pci_channel_offline(phba->pcidev)))
9241 		return IOCB_ERROR;
9242 
9243 	/* If HBA has a deferred error attention, fail the iocb. */
9244 	if (unlikely(phba->hba_flag & DEFER_ERATT))
9245 		return IOCB_ERROR;
9246 
9247 	/*
9248 	 * We should never get an IOCB if we are in a < LINK_DOWN state
9249 	 */
9250 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
9251 		return IOCB_ERROR;
9252 
9253 	/*
9254 	 * Check to see if we are blocking IOCB processing because of a
9255 	 * outstanding event.
9256 	 */
9257 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
9258 		goto iocb_busy;
9259 
9260 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
9261 		/*
9262 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
9263 		 * can be issued if the link is not up.
9264 		 */
9265 		switch (piocb->iocb.ulpCommand) {
9266 		case CMD_GEN_REQUEST64_CR:
9267 		case CMD_GEN_REQUEST64_CX:
9268 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
9269 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
9270 					FC_RCTL_DD_UNSOL_CMD) ||
9271 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
9272 					MENLO_TRANSPORT_TYPE))
9273 
9274 				goto iocb_busy;
9275 			break;
9276 		case CMD_QUE_RING_BUF_CN:
9277 		case CMD_QUE_RING_BUF64_CN:
9278 			/*
9279 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
9280 			 * completion, iocb_cmpl MUST be 0.
9281 			 */
9282 			if (piocb->iocb_cmpl)
9283 				piocb->iocb_cmpl = NULL;
9284 			/*FALLTHROUGH*/
9285 		case CMD_CREATE_XRI_CR:
9286 		case CMD_CLOSE_XRI_CN:
9287 		case CMD_CLOSE_XRI_CX:
9288 			break;
9289 		default:
9290 			goto iocb_busy;
9291 		}
9292 
9293 	/*
9294 	 * For FCP commands, we must be in a state where we can process link
9295 	 * attention events.
9296 	 */
9297 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
9298 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
9299 		goto iocb_busy;
9300 	}
9301 
9302 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
9303 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
9304 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
9305 
9306 	if (iocb)
9307 		lpfc_sli_update_ring(phba, pring);
9308 	else
9309 		lpfc_sli_update_full_ring(phba, pring);
9310 
9311 	if (!piocb)
9312 		return IOCB_SUCCESS;
9313 
9314 	goto out_busy;
9315 
9316  iocb_busy:
9317 	pring->stats.iocb_cmd_delay++;
9318 
9319  out_busy:
9320 
9321 	if (!(flag & SLI_IOCB_RET_IOCB)) {
9322 		__lpfc_sli_ringtx_put(phba, pring, piocb);
9323 		return IOCB_SUCCESS;
9324 	}
9325 
9326 	return IOCB_BUSY;
9327 }
9328 
9329 /**
9330  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
9331  * @phba: Pointer to HBA context object.
9332  * @piocb: Pointer to command iocb.
9333  * @sglq: Pointer to the scatter gather queue object.
9334  *
9335  * This routine converts the bpl or bde that is in the IOCB
9336  * to a sgl list for the sli4 hardware. The physical address
9337  * of the bpl/bde is converted back to a virtual address.
9338  * If the IOCB contains a BPL then the list of BDE's is
9339  * converted to sli4_sge's. If the IOCB contains a single
9340  * BDE then it is converted to a single sli_sge.
9341  * The IOCB is still in cpu endianess so the contents of
9342  * the bpl can be used without byte swapping.
9343  *
9344  * Returns valid XRI = Success, NO_XRI = Failure.
9345 **/
9346 static uint16_t
9347 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
9348 		struct lpfc_sglq *sglq)
9349 {
9350 	uint16_t xritag = NO_XRI;
9351 	struct ulp_bde64 *bpl = NULL;
9352 	struct ulp_bde64 bde;
9353 	struct sli4_sge *sgl  = NULL;
9354 	struct lpfc_dmabuf *dmabuf;
9355 	IOCB_t *icmd;
9356 	int numBdes = 0;
9357 	int i = 0;
9358 	uint32_t offset = 0; /* accumulated offset in the sg request list */
9359 	int inbound = 0; /* number of sg reply entries inbound from firmware */
9360 
9361 	if (!piocbq || !sglq)
9362 		return xritag;
9363 
9364 	sgl  = (struct sli4_sge *)sglq->sgl;
9365 	icmd = &piocbq->iocb;
9366 	if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
9367 		return sglq->sli4_xritag;
9368 	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9369 		numBdes = icmd->un.genreq64.bdl.bdeSize /
9370 				sizeof(struct ulp_bde64);
9371 		/* The addrHigh and addrLow fields within the IOCB
9372 		 * have not been byteswapped yet so there is no
9373 		 * need to swap them back.
9374 		 */
9375 		if (piocbq->context3)
9376 			dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
9377 		else
9378 			return xritag;
9379 
9380 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
9381 		if (!bpl)
9382 			return xritag;
9383 
9384 		for (i = 0; i < numBdes; i++) {
9385 			/* Should already be byte swapped. */
9386 			sgl->addr_hi = bpl->addrHigh;
9387 			sgl->addr_lo = bpl->addrLow;
9388 
9389 			sgl->word2 = le32_to_cpu(sgl->word2);
9390 			if ((i+1) == numBdes)
9391 				bf_set(lpfc_sli4_sge_last, sgl, 1);
9392 			else
9393 				bf_set(lpfc_sli4_sge_last, sgl, 0);
9394 			/* swap the size field back to the cpu so we
9395 			 * can assign it to the sgl.
9396 			 */
9397 			bde.tus.w = le32_to_cpu(bpl->tus.w);
9398 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
9399 			/* The offsets in the sgl need to be accumulated
9400 			 * separately for the request and reply lists.
9401 			 * The request is always first, the reply follows.
9402 			 */
9403 			if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
9404 				/* add up the reply sg entries */
9405 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
9406 					inbound++;
9407 				/* first inbound? reset the offset */
9408 				if (inbound == 1)
9409 					offset = 0;
9410 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
9411 				bf_set(lpfc_sli4_sge_type, sgl,
9412 					LPFC_SGE_TYPE_DATA);
9413 				offset += bde.tus.f.bdeSize;
9414 			}
9415 			sgl->word2 = cpu_to_le32(sgl->word2);
9416 			bpl++;
9417 			sgl++;
9418 		}
9419 	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
9420 			/* The addrHigh and addrLow fields of the BDE have not
9421 			 * been byteswapped yet so they need to be swapped
9422 			 * before putting them in the sgl.
9423 			 */
9424 			sgl->addr_hi =
9425 				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
9426 			sgl->addr_lo =
9427 				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
9428 			sgl->word2 = le32_to_cpu(sgl->word2);
9429 			bf_set(lpfc_sli4_sge_last, sgl, 1);
9430 			sgl->word2 = cpu_to_le32(sgl->word2);
9431 			sgl->sge_len =
9432 				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
9433 	}
9434 	return sglq->sli4_xritag;
9435 }
9436 
9437 /**
9438  * lpfc_sli_iocb2wqe - Convert the IOCB to a work queue entry.
9439  * @phba: Pointer to HBA context object.
9440  * @piocb: Pointer to command iocb.
9441  * @wqe: Pointer to the work queue entry.
9442  *
9443  * This routine converts the iocb command to its Work Queue Entry
9444  * equivalent. The wqe pointer should not have any fields set when
9445  * this routine is called because it will memcpy over them.
9446  * This routine does not set the CQ_ID or the WQEC bits in the
9447  * wqe.
9448  *
9449  * Returns: 0 = Success, IOCB_ERROR = Failure.
9450  **/
9451 static int
9452 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
9453 		union lpfc_wqe128 *wqe)
9454 {
9455 	uint32_t xmit_len = 0, total_len = 0;
9456 	uint8_t ct = 0;
9457 	uint32_t fip;
9458 	uint32_t abort_tag;
9459 	uint8_t command_type = ELS_COMMAND_NON_FIP;
9460 	uint8_t cmnd;
9461 	uint16_t xritag;
9462 	uint16_t abrt_iotag;
9463 	struct lpfc_iocbq *abrtiocbq;
9464 	struct ulp_bde64 *bpl = NULL;
9465 	uint32_t els_id = LPFC_ELS_ID_DEFAULT;
9466 	int numBdes, i;
9467 	struct ulp_bde64 bde;
9468 	struct lpfc_nodelist *ndlp;
9469 	uint32_t *pcmd;
9470 	uint32_t if_type;
9471 
9472 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
9473 	/* The fcp commands will set command type */
9474 	if (iocbq->iocb_flag &  LPFC_IO_FCP)
9475 		command_type = FCP_COMMAND;
9476 	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
9477 		command_type = ELS_COMMAND_FIP;
9478 	else
9479 		command_type = ELS_COMMAND_NON_FIP;
9480 
9481 	if (phba->fcp_embed_io)
9482 		memset(wqe, 0, sizeof(union lpfc_wqe128));
9483 	/* Some of the fields are in the right position already */
9484 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
9485 	/* The ct field has moved so reset */
9486 	wqe->generic.wqe_com.word7 = 0;
9487 	wqe->generic.wqe_com.word10 = 0;
9488 
9489 	abort_tag = (uint32_t) iocbq->iotag;
9490 	xritag = iocbq->sli4_xritag;
9491 	/* words0-2 bpl convert bde */
9492 	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9493 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
9494 				sizeof(struct ulp_bde64);
9495 		bpl  = (struct ulp_bde64 *)
9496 			((struct lpfc_dmabuf *)iocbq->context3)->virt;
9497 		if (!bpl)
9498 			return IOCB_ERROR;
9499 
9500 		/* Should already be byte swapped. */
9501 		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
9502 		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
9503 		/* swap the size field back to the cpu so we
9504 		 * can assign it to the sgl.
9505 		 */
9506 		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
9507 		xmit_len = wqe->generic.bde.tus.f.bdeSize;
9508 		total_len = 0;
9509 		for (i = 0; i < numBdes; i++) {
9510 			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
9511 			total_len += bde.tus.f.bdeSize;
9512 		}
9513 	} else
9514 		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
9515 
9516 	iocbq->iocb.ulpIoTag = iocbq->iotag;
9517 	cmnd = iocbq->iocb.ulpCommand;
9518 
9519 	switch (iocbq->iocb.ulpCommand) {
9520 	case CMD_ELS_REQUEST64_CR:
9521 		if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
9522 			ndlp = iocbq->context_un.ndlp;
9523 		else
9524 			ndlp = (struct lpfc_nodelist *)iocbq->context1;
9525 		if (!iocbq->iocb.ulpLe) {
9526 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9527 				"2007 Only Limited Edition cmd Format"
9528 				" supported 0x%x\n",
9529 				iocbq->iocb.ulpCommand);
9530 			return IOCB_ERROR;
9531 		}
9532 
9533 		wqe->els_req.payload_len = xmit_len;
9534 		/* Els_reguest64 has a TMO */
9535 		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
9536 			iocbq->iocb.ulpTimeout);
9537 		/* Need a VF for word 4 set the vf bit*/
9538 		bf_set(els_req64_vf, &wqe->els_req, 0);
9539 		/* And a VFID for word 12 */
9540 		bf_set(els_req64_vfid, &wqe->els_req, 0);
9541 		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
9542 		bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9543 		       iocbq->iocb.ulpContext);
9544 		bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
9545 		bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
9546 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
9547 		if (command_type == ELS_COMMAND_FIP)
9548 			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
9549 					>> LPFC_FIP_ELS_ID_SHIFT);
9550 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9551 					iocbq->context2)->virt);
9552 		if_type = bf_get(lpfc_sli_intf_if_type,
9553 					&phba->sli4_hba.sli_intf);
9554 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9555 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
9556 				*pcmd == ELS_CMD_SCR ||
9557 				*pcmd == ELS_CMD_RDF ||
9558 				*pcmd == ELS_CMD_RSCN_XMT ||
9559 				*pcmd == ELS_CMD_FDISC ||
9560 				*pcmd == ELS_CMD_LOGO ||
9561 				*pcmd == ELS_CMD_PLOGI)) {
9562 				bf_set(els_req64_sp, &wqe->els_req, 1);
9563 				bf_set(els_req64_sid, &wqe->els_req,
9564 					iocbq->vport->fc_myDID);
9565 				if ((*pcmd == ELS_CMD_FLOGI) &&
9566 					!(phba->fc_topology ==
9567 						LPFC_TOPOLOGY_LOOP))
9568 					bf_set(els_req64_sid, &wqe->els_req, 0);
9569 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
9570 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9571 					phba->vpi_ids[iocbq->vport->vpi]);
9572 			} else if (pcmd && iocbq->context1) {
9573 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
9574 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9575 					phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9576 			}
9577 		}
9578 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
9579 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9580 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
9581 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
9582 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
9583 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
9584 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
9585 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
9586 		wqe->els_req.max_response_payload_len = total_len - xmit_len;
9587 		break;
9588 	case CMD_XMIT_SEQUENCE64_CX:
9589 		bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
9590 		       iocbq->iocb.un.ulpWord[3]);
9591 		bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
9592 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
9593 		/* The entire sequence is transmitted for this IOCB */
9594 		xmit_len = total_len;
9595 		cmnd = CMD_XMIT_SEQUENCE64_CR;
9596 		if (phba->link_flag & LS_LOOPBACK_MODE)
9597 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
9598 		/* fall through */
9599 	case CMD_XMIT_SEQUENCE64_CR:
9600 		/* word3 iocb=io_tag32 wqe=reserved */
9601 		wqe->xmit_sequence.rsvd3 = 0;
9602 		/* word4 relative_offset memcpy */
9603 		/* word5 r_ctl/df_ctl memcpy */
9604 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
9605 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
9606 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
9607 		       LPFC_WQE_IOD_WRITE);
9608 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
9609 		       LPFC_WQE_LENLOC_WORD12);
9610 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
9611 		wqe->xmit_sequence.xmit_len = xmit_len;
9612 		command_type = OTHER_COMMAND;
9613 		break;
9614 	case CMD_XMIT_BCAST64_CN:
9615 		/* word3 iocb=iotag32 wqe=seq_payload_len */
9616 		wqe->xmit_bcast64.seq_payload_len = xmit_len;
9617 		/* word4 iocb=rsvd wqe=rsvd */
9618 		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
9619 		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
9620 		bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
9621 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9622 		bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
9623 		bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
9624 		bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
9625 		       LPFC_WQE_LENLOC_WORD3);
9626 		bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
9627 		break;
9628 	case CMD_FCP_IWRITE64_CR:
9629 		command_type = FCP_COMMAND_DATA_OUT;
9630 		/* word3 iocb=iotag wqe=payload_offset_len */
9631 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9632 		bf_set(payload_offset_len, &wqe->fcp_iwrite,
9633 		       xmit_len + sizeof(struct fcp_rsp));
9634 		bf_set(cmd_buff_len, &wqe->fcp_iwrite,
9635 		       0);
9636 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9637 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9638 		bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
9639 		       iocbq->iocb.ulpFCP2Rcvy);
9640 		bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
9641 		/* Always open the exchange */
9642 		bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
9643 		bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
9644 		       LPFC_WQE_LENLOC_WORD4);
9645 		bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
9646 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
9647 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9648 			bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
9649 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
9650 			if (iocbq->priority) {
9651 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9652 				       (iocbq->priority << 1));
9653 			} else {
9654 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9655 				       (phba->cfg_XLanePriority << 1));
9656 			}
9657 		}
9658 		/* Note, word 10 is already initialized to 0 */
9659 
9660 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9661 		if (phba->cfg_enable_pbde)
9662 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 1);
9663 		else
9664 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
9665 
9666 		if (phba->fcp_embed_io) {
9667 			struct lpfc_io_buf *lpfc_cmd;
9668 			struct sli4_sge *sgl;
9669 			struct fcp_cmnd *fcp_cmnd;
9670 			uint32_t *ptr;
9671 
9672 			/* 128 byte wqe support here */
9673 
9674 			lpfc_cmd = iocbq->context1;
9675 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9676 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9677 
9678 			/* Word 0-2 - FCP_CMND */
9679 			wqe->generic.bde.tus.f.bdeFlags =
9680 				BUFF_TYPE_BDE_IMMED;
9681 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9682 			wqe->generic.bde.addrHigh = 0;
9683 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9684 
9685 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
9686 			bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
9687 
9688 			/* Word 22-29  FCP CMND Payload */
9689 			ptr = &wqe->words[22];
9690 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9691 		}
9692 		break;
9693 	case CMD_FCP_IREAD64_CR:
9694 		/* word3 iocb=iotag wqe=payload_offset_len */
9695 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9696 		bf_set(payload_offset_len, &wqe->fcp_iread,
9697 		       xmit_len + sizeof(struct fcp_rsp));
9698 		bf_set(cmd_buff_len, &wqe->fcp_iread,
9699 		       0);
9700 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9701 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9702 		bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
9703 		       iocbq->iocb.ulpFCP2Rcvy);
9704 		bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
9705 		/* Always open the exchange */
9706 		bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
9707 		bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
9708 		       LPFC_WQE_LENLOC_WORD4);
9709 		bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
9710 		bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
9711 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9712 			bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
9713 			bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
9714 			if (iocbq->priority) {
9715 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9716 				       (iocbq->priority << 1));
9717 			} else {
9718 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9719 				       (phba->cfg_XLanePriority << 1));
9720 			}
9721 		}
9722 		/* Note, word 10 is already initialized to 0 */
9723 
9724 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9725 		if (phba->cfg_enable_pbde)
9726 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 1);
9727 		else
9728 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
9729 
9730 		if (phba->fcp_embed_io) {
9731 			struct lpfc_io_buf *lpfc_cmd;
9732 			struct sli4_sge *sgl;
9733 			struct fcp_cmnd *fcp_cmnd;
9734 			uint32_t *ptr;
9735 
9736 			/* 128 byte wqe support here */
9737 
9738 			lpfc_cmd = iocbq->context1;
9739 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9740 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9741 
9742 			/* Word 0-2 - FCP_CMND */
9743 			wqe->generic.bde.tus.f.bdeFlags =
9744 				BUFF_TYPE_BDE_IMMED;
9745 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9746 			wqe->generic.bde.addrHigh = 0;
9747 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9748 
9749 			bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
9750 			bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
9751 
9752 			/* Word 22-29  FCP CMND Payload */
9753 			ptr = &wqe->words[22];
9754 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9755 		}
9756 		break;
9757 	case CMD_FCP_ICMND64_CR:
9758 		/* word3 iocb=iotag wqe=payload_offset_len */
9759 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9760 		bf_set(payload_offset_len, &wqe->fcp_icmd,
9761 		       xmit_len + sizeof(struct fcp_rsp));
9762 		bf_set(cmd_buff_len, &wqe->fcp_icmd,
9763 		       0);
9764 		/* word3 iocb=IO_TAG wqe=reserved */
9765 		bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
9766 		/* Always open the exchange */
9767 		bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
9768 		bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
9769 		bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
9770 		bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
9771 		       LPFC_WQE_LENLOC_NONE);
9772 		bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
9773 		       iocbq->iocb.ulpFCP2Rcvy);
9774 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9775 			bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
9776 			bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
9777 			if (iocbq->priority) {
9778 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9779 				       (iocbq->priority << 1));
9780 			} else {
9781 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9782 				       (phba->cfg_XLanePriority << 1));
9783 			}
9784 		}
9785 		/* Note, word 10 is already initialized to 0 */
9786 
9787 		if (phba->fcp_embed_io) {
9788 			struct lpfc_io_buf *lpfc_cmd;
9789 			struct sli4_sge *sgl;
9790 			struct fcp_cmnd *fcp_cmnd;
9791 			uint32_t *ptr;
9792 
9793 			/* 128 byte wqe support here */
9794 
9795 			lpfc_cmd = iocbq->context1;
9796 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9797 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9798 
9799 			/* Word 0-2 - FCP_CMND */
9800 			wqe->generic.bde.tus.f.bdeFlags =
9801 				BUFF_TYPE_BDE_IMMED;
9802 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9803 			wqe->generic.bde.addrHigh = 0;
9804 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9805 
9806 			bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
9807 			bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
9808 
9809 			/* Word 22-29  FCP CMND Payload */
9810 			ptr = &wqe->words[22];
9811 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9812 		}
9813 		break;
9814 	case CMD_GEN_REQUEST64_CR:
9815 		/* For this command calculate the xmit length of the
9816 		 * request bde.
9817 		 */
9818 		xmit_len = 0;
9819 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
9820 			sizeof(struct ulp_bde64);
9821 		for (i = 0; i < numBdes; i++) {
9822 			bde.tus.w = le32_to_cpu(bpl[i].tus.w);
9823 			if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
9824 				break;
9825 			xmit_len += bde.tus.f.bdeSize;
9826 		}
9827 		/* word3 iocb=IO_TAG wqe=request_payload_len */
9828 		wqe->gen_req.request_payload_len = xmit_len;
9829 		/* word4 iocb=parameter wqe=relative_offset memcpy */
9830 		/* word5 [rctl, type, df_ctl, la] copied in memcpy */
9831 		/* word6 context tag copied in memcpy */
9832 		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
9833 			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
9834 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9835 				"2015 Invalid CT %x command 0x%x\n",
9836 				ct, iocbq->iocb.ulpCommand);
9837 			return IOCB_ERROR;
9838 		}
9839 		bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
9840 		bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
9841 		bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
9842 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
9843 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
9844 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
9845 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
9846 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
9847 		wqe->gen_req.max_response_payload_len = total_len - xmit_len;
9848 		command_type = OTHER_COMMAND;
9849 		break;
9850 	case CMD_XMIT_ELS_RSP64_CX:
9851 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
9852 		/* words0-2 BDE memcpy */
9853 		/* word3 iocb=iotag32 wqe=response_payload_len */
9854 		wqe->xmit_els_rsp.response_payload_len = xmit_len;
9855 		/* word4 */
9856 		wqe->xmit_els_rsp.word4 = 0;
9857 		/* word5 iocb=rsvd wge=did */
9858 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
9859 			 iocbq->iocb.un.xseq64.xmit_els_remoteID);
9860 
9861 		if_type = bf_get(lpfc_sli_intf_if_type,
9862 					&phba->sli4_hba.sli_intf);
9863 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9864 			if (iocbq->vport->fc_flag & FC_PT2PT) {
9865 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
9866 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
9867 					iocbq->vport->fc_myDID);
9868 				if (iocbq->vport->fc_myDID == Fabric_DID) {
9869 					bf_set(wqe_els_did,
9870 						&wqe->xmit_els_rsp.wqe_dest, 0);
9871 				}
9872 			}
9873 		}
9874 		bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
9875 		       ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9876 		bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
9877 		bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
9878 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
9879 		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
9880 			bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
9881 			       phba->vpi_ids[iocbq->vport->vpi]);
9882 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
9883 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
9884 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
9885 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
9886 		       LPFC_WQE_LENLOC_WORD3);
9887 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
9888 		bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
9889 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9890 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9891 					iocbq->context2)->virt);
9892 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
9893 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
9894 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
9895 					iocbq->vport->fc_myDID);
9896 				bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
9897 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
9898 					phba->vpi_ids[phba->pport->vpi]);
9899 		}
9900 		command_type = OTHER_COMMAND;
9901 		break;
9902 	case CMD_CLOSE_XRI_CN:
9903 	case CMD_ABORT_XRI_CN:
9904 	case CMD_ABORT_XRI_CX:
9905 		/* words 0-2 memcpy should be 0 rserved */
9906 		/* port will send abts */
9907 		abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
9908 		if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
9909 			abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
9910 			fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
9911 		} else
9912 			fip = 0;
9913 
9914 		if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
9915 			/*
9916 			 * The link is down, or the command was ELS_FIP
9917 			 * so the fw does not need to send abts
9918 			 * on the wire.
9919 			 */
9920 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
9921 		else
9922 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
9923 		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
9924 		/* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
9925 		wqe->abort_cmd.rsrvd5 = 0;
9926 		bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
9927 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9928 		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
9929 		/*
9930 		 * The abort handler will send us CMD_ABORT_XRI_CN or
9931 		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
9932 		 */
9933 		bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
9934 		bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
9935 		bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
9936 		       LPFC_WQE_LENLOC_NONE);
9937 		cmnd = CMD_ABORT_XRI_CX;
9938 		command_type = OTHER_COMMAND;
9939 		xritag = 0;
9940 		break;
9941 	case CMD_XMIT_BLS_RSP64_CX:
9942 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
9943 		/* As BLS ABTS RSP WQE is very different from other WQEs,
9944 		 * we re-construct this WQE here based on information in
9945 		 * iocbq from scratch.
9946 		 */
9947 		memset(wqe, 0, sizeof(*wqe));
9948 		/* OX_ID is invariable to who sent ABTS to CT exchange */
9949 		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
9950 		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
9951 		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
9952 		    LPFC_ABTS_UNSOL_INT) {
9953 			/* ABTS sent by initiator to CT exchange, the
9954 			 * RX_ID field will be filled with the newly
9955 			 * allocated responder XRI.
9956 			 */
9957 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
9958 			       iocbq->sli4_xritag);
9959 		} else {
9960 			/* ABTS sent by responder to CT exchange, the
9961 			 * RX_ID field will be filled with the responder
9962 			 * RX_ID from ABTS.
9963 			 */
9964 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
9965 			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
9966 		}
9967 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
9968 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
9969 
9970 		/* Use CT=VPI */
9971 		bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
9972 			ndlp->nlp_DID);
9973 		bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
9974 			iocbq->iocb.ulpContext);
9975 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
9976 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
9977 			phba->vpi_ids[phba->pport->vpi]);
9978 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
9979 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
9980 		       LPFC_WQE_LENLOC_NONE);
9981 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
9982 		command_type = OTHER_COMMAND;
9983 		if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
9984 			bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
9985 			       bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
9986 			bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
9987 			       bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
9988 			bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
9989 			       bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
9990 		}
9991 
9992 		break;
9993 	case CMD_SEND_FRAME:
9994 		bf_set(wqe_cmnd, &wqe->generic.wqe_com, CMD_SEND_FRAME);
9995 		bf_set(wqe_sof, &wqe->generic.wqe_com, 0x2E); /* SOF byte */
9996 		bf_set(wqe_eof, &wqe->generic.wqe_com, 0x41); /* EOF byte */
9997 		bf_set(wqe_lenloc, &wqe->generic.wqe_com, 1);
9998 		bf_set(wqe_xbl, &wqe->generic.wqe_com, 1);
9999 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10000 		bf_set(wqe_xc, &wqe->generic.wqe_com, 1);
10001 		bf_set(wqe_cmd_type, &wqe->generic.wqe_com, 0xA);
10002 		bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10003 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10004 		bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10005 		return 0;
10006 	case CMD_XRI_ABORTED_CX:
10007 	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
10008 	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
10009 	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
10010 	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
10011 	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
10012 	default:
10013 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10014 				"2014 Invalid command 0x%x\n",
10015 				iocbq->iocb.ulpCommand);
10016 		return IOCB_ERROR;
10017 		break;
10018 	}
10019 
10020 	if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
10021 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
10022 	else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
10023 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
10024 	else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
10025 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
10026 	iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
10027 			      LPFC_IO_DIF_INSERT);
10028 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10029 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10030 	wqe->generic.wqe_com.abort_tag = abort_tag;
10031 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
10032 	bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
10033 	bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
10034 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10035 	return 0;
10036 }
10037 
10038 /**
10039  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10040  * @phba: Pointer to HBA context object.
10041  * @ring_number: SLI ring number to issue iocb on.
10042  * @piocb: Pointer to command iocb.
10043  * @flag: Flag indicating if this command can be put into txq.
10044  *
10045  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10046  * an iocb command to an HBA with SLI-4 interface spec.
10047  *
10048  * This function is called with ringlock held. The function will return success
10049  * after it successfully submit the iocb to firmware or after adding to the
10050  * txq.
10051  **/
10052 static int
10053 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10054 			 struct lpfc_iocbq *piocb, uint32_t flag)
10055 {
10056 	struct lpfc_sglq *sglq;
10057 	union lpfc_wqe128 wqe;
10058 	struct lpfc_queue *wq;
10059 	struct lpfc_sli_ring *pring;
10060 
10061 	/* Get the WQ */
10062 	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
10063 	    (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
10064 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10065 	} else {
10066 		wq = phba->sli4_hba.els_wq;
10067 	}
10068 
10069 	/* Get corresponding ring */
10070 	pring = wq->pring;
10071 
10072 	/*
10073 	 * The WQE can be either 64 or 128 bytes,
10074 	 */
10075 
10076 	lockdep_assert_held(&pring->ring_lock);
10077 
10078 	if (piocb->sli4_xritag == NO_XRI) {
10079 		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
10080 		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
10081 			sglq = NULL;
10082 		else {
10083 			if (!list_empty(&pring->txq)) {
10084 				if (!(flag & SLI_IOCB_RET_IOCB)) {
10085 					__lpfc_sli_ringtx_put(phba,
10086 						pring, piocb);
10087 					return IOCB_SUCCESS;
10088 				} else {
10089 					return IOCB_BUSY;
10090 				}
10091 			} else {
10092 				sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10093 				if (!sglq) {
10094 					if (!(flag & SLI_IOCB_RET_IOCB)) {
10095 						__lpfc_sli_ringtx_put(phba,
10096 								pring,
10097 								piocb);
10098 						return IOCB_SUCCESS;
10099 					} else
10100 						return IOCB_BUSY;
10101 				}
10102 			}
10103 		}
10104 	} else if (piocb->iocb_flag &  LPFC_IO_FCP)
10105 		/* These IO's already have an XRI and a mapped sgl. */
10106 		sglq = NULL;
10107 	else {
10108 		/*
10109 		 * This is a continuation of a commandi,(CX) so this
10110 		 * sglq is on the active list
10111 		 */
10112 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10113 		if (!sglq)
10114 			return IOCB_ERROR;
10115 	}
10116 
10117 	if (sglq) {
10118 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10119 		piocb->sli4_xritag = sglq->sli4_xritag;
10120 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
10121 			return IOCB_ERROR;
10122 	}
10123 
10124 	if (lpfc_sli4_iocb2wqe(phba, piocb, &wqe))
10125 		return IOCB_ERROR;
10126 
10127 	if (lpfc_sli4_wq_put(wq, &wqe))
10128 		return IOCB_ERROR;
10129 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10130 
10131 	return 0;
10132 }
10133 
10134 /**
10135  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10136  *
10137  * This routine wraps the actual lockless version for issusing IOCB function
10138  * pointer from the lpfc_hba struct.
10139  *
10140  * Return codes:
10141  * IOCB_ERROR - Error
10142  * IOCB_SUCCESS - Success
10143  * IOCB_BUSY - Busy
10144  **/
10145 int
10146 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10147 		struct lpfc_iocbq *piocb, uint32_t flag)
10148 {
10149 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10150 }
10151 
10152 /**
10153  * lpfc_sli_api_table_setup - Set up sli api function jump table
10154  * @phba: The hba struct for which this call is being executed.
10155  * @dev_grp: The HBA PCI-Device group number.
10156  *
10157  * This routine sets up the SLI interface API function jump table in @phba
10158  * struct.
10159  * Returns: 0 - success, -ENODEV - failure.
10160  **/
10161 int
10162 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10163 {
10164 
10165 	switch (dev_grp) {
10166 	case LPFC_PCI_DEV_LP:
10167 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
10168 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
10169 		break;
10170 	case LPFC_PCI_DEV_OC:
10171 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
10172 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
10173 		break;
10174 	default:
10175 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10176 				"1419 Invalid HBA PCI-device group: 0x%x\n",
10177 				dev_grp);
10178 		return -ENODEV;
10179 		break;
10180 	}
10181 	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
10182 	return 0;
10183 }
10184 
10185 /**
10186  * lpfc_sli4_calc_ring - Calculates which ring to use
10187  * @phba: Pointer to HBA context object.
10188  * @piocb: Pointer to command iocb.
10189  *
10190  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
10191  * hba_wqidx, thus we need to calculate the corresponding ring.
10192  * Since ABORTS must go on the same WQ of the command they are
10193  * aborting, we use command's hba_wqidx.
10194  */
10195 struct lpfc_sli_ring *
10196 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
10197 {
10198 	struct lpfc_io_buf *lpfc_cmd;
10199 
10200 	if (piocb->iocb_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
10201 		if (unlikely(!phba->sli4_hba.hdwq))
10202 			return NULL;
10203 		/*
10204 		 * for abort iocb hba_wqidx should already
10205 		 * be setup based on what work queue we used.
10206 		 */
10207 		if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
10208 			lpfc_cmd = (struct lpfc_io_buf *)piocb->context1;
10209 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
10210 		}
10211 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
10212 	} else {
10213 		if (unlikely(!phba->sli4_hba.els_wq))
10214 			return NULL;
10215 		piocb->hba_wqidx = 0;
10216 		return phba->sli4_hba.els_wq->pring;
10217 	}
10218 }
10219 
10220 /**
10221  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
10222  * @phba: Pointer to HBA context object.
10223  * @pring: Pointer to driver SLI ring object.
10224  * @piocb: Pointer to command iocb.
10225  * @flag: Flag indicating if this command can be put into txq.
10226  *
10227  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
10228  * function. This function gets the hbalock and calls
10229  * __lpfc_sli_issue_iocb function and will return the error returned
10230  * by __lpfc_sli_issue_iocb function. This wrapper is used by
10231  * functions which do not hold hbalock.
10232  **/
10233 int
10234 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10235 		    struct lpfc_iocbq *piocb, uint32_t flag)
10236 {
10237 	struct lpfc_sli_ring *pring;
10238 	struct lpfc_queue *eq;
10239 	unsigned long iflags;
10240 	int rc;
10241 
10242 	if (phba->sli_rev == LPFC_SLI_REV4) {
10243 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
10244 
10245 		pring = lpfc_sli4_calc_ring(phba, piocb);
10246 		if (unlikely(pring == NULL))
10247 			return IOCB_ERROR;
10248 
10249 		spin_lock_irqsave(&pring->ring_lock, iflags);
10250 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10251 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
10252 
10253 		lpfc_sli4_poll_eq(eq, LPFC_POLL_FASTPATH);
10254 	} else {
10255 		/* For now, SLI2/3 will still use hbalock */
10256 		spin_lock_irqsave(&phba->hbalock, iflags);
10257 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10258 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10259 	}
10260 	return rc;
10261 }
10262 
10263 /**
10264  * lpfc_extra_ring_setup - Extra ring setup function
10265  * @phba: Pointer to HBA context object.
10266  *
10267  * This function is called while driver attaches with the
10268  * HBA to setup the extra ring. The extra ring is used
10269  * only when driver needs to support target mode functionality
10270  * or IP over FC functionalities.
10271  *
10272  * This function is called with no lock held. SLI3 only.
10273  **/
10274 static int
10275 lpfc_extra_ring_setup( struct lpfc_hba *phba)
10276 {
10277 	struct lpfc_sli *psli;
10278 	struct lpfc_sli_ring *pring;
10279 
10280 	psli = &phba->sli;
10281 
10282 	/* Adjust cmd/rsp ring iocb entries more evenly */
10283 
10284 	/* Take some away from the FCP ring */
10285 	pring = &psli->sli3_ring[LPFC_FCP_RING];
10286 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10287 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10288 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10289 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10290 
10291 	/* and give them to the extra ring */
10292 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
10293 
10294 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10295 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10296 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10297 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10298 
10299 	/* Setup default profile for this ring */
10300 	pring->iotag_max = 4096;
10301 	pring->num_mask = 1;
10302 	pring->prt[0].profile = 0;      /* Mask 0 */
10303 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
10304 	pring->prt[0].type = phba->cfg_multi_ring_type;
10305 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
10306 	return 0;
10307 }
10308 
10309 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
10310  * @phba: Pointer to HBA context object.
10311  * @iocbq: Pointer to iocb object.
10312  *
10313  * The async_event handler calls this routine when it receives
10314  * an ASYNC_STATUS_CN event from the port.  The port generates
10315  * this event when an Abort Sequence request to an rport fails
10316  * twice in succession.  The abort could be originated by the
10317  * driver or by the port.  The ABTS could have been for an ELS
10318  * or FCP IO.  The port only generates this event when an ABTS
10319  * fails to complete after one retry.
10320  */
10321 static void
10322 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
10323 			  struct lpfc_iocbq *iocbq)
10324 {
10325 	struct lpfc_nodelist *ndlp = NULL;
10326 	uint16_t rpi = 0, vpi = 0;
10327 	struct lpfc_vport *vport = NULL;
10328 
10329 	/* The rpi in the ulpContext is vport-sensitive. */
10330 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
10331 	rpi = iocbq->iocb.ulpContext;
10332 
10333 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10334 			"3092 Port generated ABTS async event "
10335 			"on vpi %d rpi %d status 0x%x\n",
10336 			vpi, rpi, iocbq->iocb.ulpStatus);
10337 
10338 	vport = lpfc_find_vport_by_vpid(phba, vpi);
10339 	if (!vport)
10340 		goto err_exit;
10341 	ndlp = lpfc_findnode_rpi(vport, rpi);
10342 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp))
10343 		goto err_exit;
10344 
10345 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
10346 		lpfc_sli_abts_recover_port(vport, ndlp);
10347 	return;
10348 
10349  err_exit:
10350 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10351 			"3095 Event Context not found, no "
10352 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
10353 			iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
10354 			vpi, rpi);
10355 }
10356 
10357 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
10358  * @phba: pointer to HBA context object.
10359  * @ndlp: nodelist pointer for the impacted rport.
10360  * @axri: pointer to the wcqe containing the failed exchange.
10361  *
10362  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
10363  * port.  The port generates this event when an abort exchange request to an
10364  * rport fails twice in succession with no reply.  The abort could be originated
10365  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
10366  */
10367 void
10368 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
10369 			   struct lpfc_nodelist *ndlp,
10370 			   struct sli4_wcqe_xri_aborted *axri)
10371 {
10372 	struct lpfc_vport *vport;
10373 	uint32_t ext_status = 0;
10374 
10375 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
10376 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10377 				"3115 Node Context not found, driver "
10378 				"ignoring abts err event\n");
10379 		return;
10380 	}
10381 
10382 	vport = ndlp->vport;
10383 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10384 			"3116 Port generated FCP XRI ABORT event on "
10385 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
10386 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
10387 			bf_get(lpfc_wcqe_xa_xri, axri),
10388 			bf_get(lpfc_wcqe_xa_status, axri),
10389 			axri->parameter);
10390 
10391 	/*
10392 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
10393 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
10394 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
10395 	 */
10396 	ext_status = axri->parameter & IOERR_PARAM_MASK;
10397 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
10398 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
10399 		lpfc_sli_abts_recover_port(vport, ndlp);
10400 }
10401 
10402 /**
10403  * lpfc_sli_async_event_handler - ASYNC iocb handler function
10404  * @phba: Pointer to HBA context object.
10405  * @pring: Pointer to driver SLI ring object.
10406  * @iocbq: Pointer to iocb object.
10407  *
10408  * This function is called by the slow ring event handler
10409  * function when there is an ASYNC event iocb in the ring.
10410  * This function is called with no lock held.
10411  * Currently this function handles only temperature related
10412  * ASYNC events. The function decodes the temperature sensor
10413  * event message and posts events for the management applications.
10414  **/
10415 static void
10416 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
10417 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
10418 {
10419 	IOCB_t *icmd;
10420 	uint16_t evt_code;
10421 	struct temp_event temp_event_data;
10422 	struct Scsi_Host *shost;
10423 	uint32_t *iocb_w;
10424 
10425 	icmd = &iocbq->iocb;
10426 	evt_code = icmd->un.asyncstat.evt_code;
10427 
10428 	switch (evt_code) {
10429 	case ASYNC_TEMP_WARN:
10430 	case ASYNC_TEMP_SAFE:
10431 		temp_event_data.data = (uint32_t) icmd->ulpContext;
10432 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
10433 		if (evt_code == ASYNC_TEMP_WARN) {
10434 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
10435 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
10436 				"0347 Adapter is very hot, please take "
10437 				"corrective action. temperature : %d Celsius\n",
10438 				(uint32_t) icmd->ulpContext);
10439 		} else {
10440 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
10441 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
10442 				"0340 Adapter temperature is OK now. "
10443 				"temperature : %d Celsius\n",
10444 				(uint32_t) icmd->ulpContext);
10445 		}
10446 
10447 		/* Send temperature change event to applications */
10448 		shost = lpfc_shost_from_vport(phba->pport);
10449 		fc_host_post_vendor_event(shost, fc_get_event_number(),
10450 			sizeof(temp_event_data), (char *) &temp_event_data,
10451 			LPFC_NL_VENDOR_ID);
10452 		break;
10453 	case ASYNC_STATUS_CN:
10454 		lpfc_sli_abts_err_handler(phba, iocbq);
10455 		break;
10456 	default:
10457 		iocb_w = (uint32_t *) icmd;
10458 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10459 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
10460 			" evt_code 0x%x\n"
10461 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
10462 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
10463 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
10464 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
10465 			pring->ringno, icmd->un.asyncstat.evt_code,
10466 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
10467 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
10468 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
10469 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
10470 
10471 		break;
10472 	}
10473 }
10474 
10475 
10476 /**
10477  * lpfc_sli4_setup - SLI ring setup function
10478  * @phba: Pointer to HBA context object.
10479  *
10480  * lpfc_sli_setup sets up rings of the SLI interface with
10481  * number of iocbs per ring and iotags. This function is
10482  * called while driver attach to the HBA and before the
10483  * interrupts are enabled. So there is no need for locking.
10484  *
10485  * This function always returns 0.
10486  **/
10487 int
10488 lpfc_sli4_setup(struct lpfc_hba *phba)
10489 {
10490 	struct lpfc_sli_ring *pring;
10491 
10492 	pring = phba->sli4_hba.els_wq->pring;
10493 	pring->num_mask = LPFC_MAX_RING_MASK;
10494 	pring->prt[0].profile = 0;	/* Mask 0 */
10495 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10496 	pring->prt[0].type = FC_TYPE_ELS;
10497 	pring->prt[0].lpfc_sli_rcv_unsol_event =
10498 	    lpfc_els_unsol_event;
10499 	pring->prt[1].profile = 0;	/* Mask 1 */
10500 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
10501 	pring->prt[1].type = FC_TYPE_ELS;
10502 	pring->prt[1].lpfc_sli_rcv_unsol_event =
10503 	    lpfc_els_unsol_event;
10504 	pring->prt[2].profile = 0;	/* Mask 2 */
10505 	/* NameServer Inquiry */
10506 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10507 	/* NameServer */
10508 	pring->prt[2].type = FC_TYPE_CT;
10509 	pring->prt[2].lpfc_sli_rcv_unsol_event =
10510 	    lpfc_ct_unsol_event;
10511 	pring->prt[3].profile = 0;	/* Mask 3 */
10512 	/* NameServer response */
10513 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10514 	/* NameServer */
10515 	pring->prt[3].type = FC_TYPE_CT;
10516 	pring->prt[3].lpfc_sli_rcv_unsol_event =
10517 	    lpfc_ct_unsol_event;
10518 	return 0;
10519 }
10520 
10521 /**
10522  * lpfc_sli_setup - SLI ring setup function
10523  * @phba: Pointer to HBA context object.
10524  *
10525  * lpfc_sli_setup sets up rings of the SLI interface with
10526  * number of iocbs per ring and iotags. This function is
10527  * called while driver attach to the HBA and before the
10528  * interrupts are enabled. So there is no need for locking.
10529  *
10530  * This function always returns 0. SLI3 only.
10531  **/
10532 int
10533 lpfc_sli_setup(struct lpfc_hba *phba)
10534 {
10535 	int i, totiocbsize = 0;
10536 	struct lpfc_sli *psli = &phba->sli;
10537 	struct lpfc_sli_ring *pring;
10538 
10539 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
10540 	psli->sli_flag = 0;
10541 
10542 	psli->iocbq_lookup = NULL;
10543 	psli->iocbq_lookup_len = 0;
10544 	psli->last_iotag = 0;
10545 
10546 	for (i = 0; i < psli->num_rings; i++) {
10547 		pring = &psli->sli3_ring[i];
10548 		switch (i) {
10549 		case LPFC_FCP_RING:	/* ring 0 - FCP */
10550 			/* numCiocb and numRiocb are used in config_port */
10551 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
10552 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
10553 			pring->sli.sli3.numCiocb +=
10554 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10555 			pring->sli.sli3.numRiocb +=
10556 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10557 			pring->sli.sli3.numCiocb +=
10558 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10559 			pring->sli.sli3.numRiocb +=
10560 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10561 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10562 							SLI3_IOCB_CMD_SIZE :
10563 							SLI2_IOCB_CMD_SIZE;
10564 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10565 							SLI3_IOCB_RSP_SIZE :
10566 							SLI2_IOCB_RSP_SIZE;
10567 			pring->iotag_ctr = 0;
10568 			pring->iotag_max =
10569 			    (phba->cfg_hba_queue_depth * 2);
10570 			pring->fast_iotag = pring->iotag_max;
10571 			pring->num_mask = 0;
10572 			break;
10573 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
10574 			/* numCiocb and numRiocb are used in config_port */
10575 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
10576 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
10577 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10578 							SLI3_IOCB_CMD_SIZE :
10579 							SLI2_IOCB_CMD_SIZE;
10580 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10581 							SLI3_IOCB_RSP_SIZE :
10582 							SLI2_IOCB_RSP_SIZE;
10583 			pring->iotag_max = phba->cfg_hba_queue_depth;
10584 			pring->num_mask = 0;
10585 			break;
10586 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
10587 			/* numCiocb and numRiocb are used in config_port */
10588 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
10589 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
10590 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10591 							SLI3_IOCB_CMD_SIZE :
10592 							SLI2_IOCB_CMD_SIZE;
10593 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10594 							SLI3_IOCB_RSP_SIZE :
10595 							SLI2_IOCB_RSP_SIZE;
10596 			pring->fast_iotag = 0;
10597 			pring->iotag_ctr = 0;
10598 			pring->iotag_max = 4096;
10599 			pring->lpfc_sli_rcv_async_status =
10600 				lpfc_sli_async_event_handler;
10601 			pring->num_mask = LPFC_MAX_RING_MASK;
10602 			pring->prt[0].profile = 0;	/* Mask 0 */
10603 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10604 			pring->prt[0].type = FC_TYPE_ELS;
10605 			pring->prt[0].lpfc_sli_rcv_unsol_event =
10606 			    lpfc_els_unsol_event;
10607 			pring->prt[1].profile = 0;	/* Mask 1 */
10608 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
10609 			pring->prt[1].type = FC_TYPE_ELS;
10610 			pring->prt[1].lpfc_sli_rcv_unsol_event =
10611 			    lpfc_els_unsol_event;
10612 			pring->prt[2].profile = 0;	/* Mask 2 */
10613 			/* NameServer Inquiry */
10614 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10615 			/* NameServer */
10616 			pring->prt[2].type = FC_TYPE_CT;
10617 			pring->prt[2].lpfc_sli_rcv_unsol_event =
10618 			    lpfc_ct_unsol_event;
10619 			pring->prt[3].profile = 0;	/* Mask 3 */
10620 			/* NameServer response */
10621 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10622 			/* NameServer */
10623 			pring->prt[3].type = FC_TYPE_CT;
10624 			pring->prt[3].lpfc_sli_rcv_unsol_event =
10625 			    lpfc_ct_unsol_event;
10626 			break;
10627 		}
10628 		totiocbsize += (pring->sli.sli3.numCiocb *
10629 			pring->sli.sli3.sizeCiocb) +
10630 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
10631 	}
10632 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
10633 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
10634 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
10635 		       "SLI2 SLIM Data: x%x x%lx\n",
10636 		       phba->brd_no, totiocbsize,
10637 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
10638 	}
10639 	if (phba->cfg_multi_ring_support == 2)
10640 		lpfc_extra_ring_setup(phba);
10641 
10642 	return 0;
10643 }
10644 
10645 /**
10646  * lpfc_sli4_queue_init - Queue initialization function
10647  * @phba: Pointer to HBA context object.
10648  *
10649  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
10650  * ring. This function also initializes ring indices of each ring.
10651  * This function is called during the initialization of the SLI
10652  * interface of an HBA.
10653  * This function is called with no lock held and always returns
10654  * 1.
10655  **/
10656 void
10657 lpfc_sli4_queue_init(struct lpfc_hba *phba)
10658 {
10659 	struct lpfc_sli *psli;
10660 	struct lpfc_sli_ring *pring;
10661 	int i;
10662 
10663 	psli = &phba->sli;
10664 	spin_lock_irq(&phba->hbalock);
10665 	INIT_LIST_HEAD(&psli->mboxq);
10666 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
10667 	/* Initialize list headers for txq and txcmplq as double linked lists */
10668 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
10669 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
10670 		pring->flag = 0;
10671 		pring->ringno = LPFC_FCP_RING;
10672 		pring->txcmplq_cnt = 0;
10673 		INIT_LIST_HEAD(&pring->txq);
10674 		INIT_LIST_HEAD(&pring->txcmplq);
10675 		INIT_LIST_HEAD(&pring->iocb_continueq);
10676 		spin_lock_init(&pring->ring_lock);
10677 	}
10678 	pring = phba->sli4_hba.els_wq->pring;
10679 	pring->flag = 0;
10680 	pring->ringno = LPFC_ELS_RING;
10681 	pring->txcmplq_cnt = 0;
10682 	INIT_LIST_HEAD(&pring->txq);
10683 	INIT_LIST_HEAD(&pring->txcmplq);
10684 	INIT_LIST_HEAD(&pring->iocb_continueq);
10685 	spin_lock_init(&pring->ring_lock);
10686 
10687 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10688 		pring = phba->sli4_hba.nvmels_wq->pring;
10689 		pring->flag = 0;
10690 		pring->ringno = LPFC_ELS_RING;
10691 		pring->txcmplq_cnt = 0;
10692 		INIT_LIST_HEAD(&pring->txq);
10693 		INIT_LIST_HEAD(&pring->txcmplq);
10694 		INIT_LIST_HEAD(&pring->iocb_continueq);
10695 		spin_lock_init(&pring->ring_lock);
10696 	}
10697 
10698 	spin_unlock_irq(&phba->hbalock);
10699 }
10700 
10701 /**
10702  * lpfc_sli_queue_init - Queue initialization function
10703  * @phba: Pointer to HBA context object.
10704  *
10705  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
10706  * ring. This function also initializes ring indices of each ring.
10707  * This function is called during the initialization of the SLI
10708  * interface of an HBA.
10709  * This function is called with no lock held and always returns
10710  * 1.
10711  **/
10712 void
10713 lpfc_sli_queue_init(struct lpfc_hba *phba)
10714 {
10715 	struct lpfc_sli *psli;
10716 	struct lpfc_sli_ring *pring;
10717 	int i;
10718 
10719 	psli = &phba->sli;
10720 	spin_lock_irq(&phba->hbalock);
10721 	INIT_LIST_HEAD(&psli->mboxq);
10722 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
10723 	/* Initialize list headers for txq and txcmplq as double linked lists */
10724 	for (i = 0; i < psli->num_rings; i++) {
10725 		pring = &psli->sli3_ring[i];
10726 		pring->ringno = i;
10727 		pring->sli.sli3.next_cmdidx  = 0;
10728 		pring->sli.sli3.local_getidx = 0;
10729 		pring->sli.sli3.cmdidx = 0;
10730 		INIT_LIST_HEAD(&pring->iocb_continueq);
10731 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
10732 		INIT_LIST_HEAD(&pring->postbufq);
10733 		pring->flag = 0;
10734 		INIT_LIST_HEAD(&pring->txq);
10735 		INIT_LIST_HEAD(&pring->txcmplq);
10736 		spin_lock_init(&pring->ring_lock);
10737 	}
10738 	spin_unlock_irq(&phba->hbalock);
10739 }
10740 
10741 /**
10742  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
10743  * @phba: Pointer to HBA context object.
10744  *
10745  * This routine flushes the mailbox command subsystem. It will unconditionally
10746  * flush all the mailbox commands in the three possible stages in the mailbox
10747  * command sub-system: pending mailbox command queue; the outstanding mailbox
10748  * command; and completed mailbox command queue. It is caller's responsibility
10749  * to make sure that the driver is in the proper state to flush the mailbox
10750  * command sub-system. Namely, the posting of mailbox commands into the
10751  * pending mailbox command queue from the various clients must be stopped;
10752  * either the HBA is in a state that it will never works on the outstanding
10753  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
10754  * mailbox command has been completed.
10755  **/
10756 static void
10757 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
10758 {
10759 	LIST_HEAD(completions);
10760 	struct lpfc_sli *psli = &phba->sli;
10761 	LPFC_MBOXQ_t *pmb;
10762 	unsigned long iflag;
10763 
10764 	/* Disable softirqs, including timers from obtaining phba->hbalock */
10765 	local_bh_disable();
10766 
10767 	/* Flush all the mailbox commands in the mbox system */
10768 	spin_lock_irqsave(&phba->hbalock, iflag);
10769 
10770 	/* The pending mailbox command queue */
10771 	list_splice_init(&phba->sli.mboxq, &completions);
10772 	/* The outstanding active mailbox command */
10773 	if (psli->mbox_active) {
10774 		list_add_tail(&psli->mbox_active->list, &completions);
10775 		psli->mbox_active = NULL;
10776 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10777 	}
10778 	/* The completed mailbox command queue */
10779 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
10780 	spin_unlock_irqrestore(&phba->hbalock, iflag);
10781 
10782 	/* Enable softirqs again, done with phba->hbalock */
10783 	local_bh_enable();
10784 
10785 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
10786 	while (!list_empty(&completions)) {
10787 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
10788 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
10789 		if (pmb->mbox_cmpl)
10790 			pmb->mbox_cmpl(phba, pmb);
10791 	}
10792 }
10793 
10794 /**
10795  * lpfc_sli_host_down - Vport cleanup function
10796  * @vport: Pointer to virtual port object.
10797  *
10798  * lpfc_sli_host_down is called to clean up the resources
10799  * associated with a vport before destroying virtual
10800  * port data structures.
10801  * This function does following operations:
10802  * - Free discovery resources associated with this virtual
10803  *   port.
10804  * - Free iocbs associated with this virtual port in
10805  *   the txq.
10806  * - Send abort for all iocb commands associated with this
10807  *   vport in txcmplq.
10808  *
10809  * This function is called with no lock held and always returns 1.
10810  **/
10811 int
10812 lpfc_sli_host_down(struct lpfc_vport *vport)
10813 {
10814 	LIST_HEAD(completions);
10815 	struct lpfc_hba *phba = vport->phba;
10816 	struct lpfc_sli *psli = &phba->sli;
10817 	struct lpfc_queue *qp = NULL;
10818 	struct lpfc_sli_ring *pring;
10819 	struct lpfc_iocbq *iocb, *next_iocb;
10820 	int i;
10821 	unsigned long flags = 0;
10822 	uint16_t prev_pring_flag;
10823 
10824 	lpfc_cleanup_discovery_resources(vport);
10825 
10826 	spin_lock_irqsave(&phba->hbalock, flags);
10827 
10828 	/*
10829 	 * Error everything on the txq since these iocbs
10830 	 * have not been given to the FW yet.
10831 	 * Also issue ABTS for everything on the txcmplq
10832 	 */
10833 	if (phba->sli_rev != LPFC_SLI_REV4) {
10834 		for (i = 0; i < psli->num_rings; i++) {
10835 			pring = &psli->sli3_ring[i];
10836 			prev_pring_flag = pring->flag;
10837 			/* Only slow rings */
10838 			if (pring->ringno == LPFC_ELS_RING) {
10839 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10840 				/* Set the lpfc data pending flag */
10841 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10842 			}
10843 			list_for_each_entry_safe(iocb, next_iocb,
10844 						 &pring->txq, list) {
10845 				if (iocb->vport != vport)
10846 					continue;
10847 				list_move_tail(&iocb->list, &completions);
10848 			}
10849 			list_for_each_entry_safe(iocb, next_iocb,
10850 						 &pring->txcmplq, list) {
10851 				if (iocb->vport != vport)
10852 					continue;
10853 				lpfc_sli_issue_abort_iotag(phba, pring, iocb);
10854 			}
10855 			pring->flag = prev_pring_flag;
10856 		}
10857 	} else {
10858 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
10859 			pring = qp->pring;
10860 			if (!pring)
10861 				continue;
10862 			if (pring == phba->sli4_hba.els_wq->pring) {
10863 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10864 				/* Set the lpfc data pending flag */
10865 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10866 			}
10867 			prev_pring_flag = pring->flag;
10868 			spin_lock(&pring->ring_lock);
10869 			list_for_each_entry_safe(iocb, next_iocb,
10870 						 &pring->txq, list) {
10871 				if (iocb->vport != vport)
10872 					continue;
10873 				list_move_tail(&iocb->list, &completions);
10874 			}
10875 			spin_unlock(&pring->ring_lock);
10876 			list_for_each_entry_safe(iocb, next_iocb,
10877 						 &pring->txcmplq, list) {
10878 				if (iocb->vport != vport)
10879 					continue;
10880 				lpfc_sli_issue_abort_iotag(phba, pring, iocb);
10881 			}
10882 			pring->flag = prev_pring_flag;
10883 		}
10884 	}
10885 	spin_unlock_irqrestore(&phba->hbalock, flags);
10886 
10887 	/* Cancel all the IOCBs from the completions list */
10888 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
10889 			      IOERR_SLI_DOWN);
10890 	return 1;
10891 }
10892 
10893 /**
10894  * lpfc_sli_hba_down - Resource cleanup function for the HBA
10895  * @phba: Pointer to HBA context object.
10896  *
10897  * This function cleans up all iocb, buffers, mailbox commands
10898  * while shutting down the HBA. This function is called with no
10899  * lock held and always returns 1.
10900  * This function does the following to cleanup driver resources:
10901  * - Free discovery resources for each virtual port
10902  * - Cleanup any pending fabric iocbs
10903  * - Iterate through the iocb txq and free each entry
10904  *   in the list.
10905  * - Free up any buffer posted to the HBA
10906  * - Free mailbox commands in the mailbox queue.
10907  **/
10908 int
10909 lpfc_sli_hba_down(struct lpfc_hba *phba)
10910 {
10911 	LIST_HEAD(completions);
10912 	struct lpfc_sli *psli = &phba->sli;
10913 	struct lpfc_queue *qp = NULL;
10914 	struct lpfc_sli_ring *pring;
10915 	struct lpfc_dmabuf *buf_ptr;
10916 	unsigned long flags = 0;
10917 	int i;
10918 
10919 	/* Shutdown the mailbox command sub-system */
10920 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
10921 
10922 	lpfc_hba_down_prep(phba);
10923 
10924 	/* Disable softirqs, including timers from obtaining phba->hbalock */
10925 	local_bh_disable();
10926 
10927 	lpfc_fabric_abort_hba(phba);
10928 
10929 	spin_lock_irqsave(&phba->hbalock, flags);
10930 
10931 	/*
10932 	 * Error everything on the txq since these iocbs
10933 	 * have not been given to the FW yet.
10934 	 */
10935 	if (phba->sli_rev != LPFC_SLI_REV4) {
10936 		for (i = 0; i < psli->num_rings; i++) {
10937 			pring = &psli->sli3_ring[i];
10938 			/* Only slow rings */
10939 			if (pring->ringno == LPFC_ELS_RING) {
10940 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10941 				/* Set the lpfc data pending flag */
10942 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10943 			}
10944 			list_splice_init(&pring->txq, &completions);
10945 		}
10946 	} else {
10947 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
10948 			pring = qp->pring;
10949 			if (!pring)
10950 				continue;
10951 			spin_lock(&pring->ring_lock);
10952 			list_splice_init(&pring->txq, &completions);
10953 			spin_unlock(&pring->ring_lock);
10954 			if (pring == phba->sli4_hba.els_wq->pring) {
10955 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10956 				/* Set the lpfc data pending flag */
10957 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10958 			}
10959 		}
10960 	}
10961 	spin_unlock_irqrestore(&phba->hbalock, flags);
10962 
10963 	/* Cancel all the IOCBs from the completions list */
10964 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
10965 			      IOERR_SLI_DOWN);
10966 
10967 	spin_lock_irqsave(&phba->hbalock, flags);
10968 	list_splice_init(&phba->elsbuf, &completions);
10969 	phba->elsbuf_cnt = 0;
10970 	phba->elsbuf_prev_cnt = 0;
10971 	spin_unlock_irqrestore(&phba->hbalock, flags);
10972 
10973 	while (!list_empty(&completions)) {
10974 		list_remove_head(&completions, buf_ptr,
10975 			struct lpfc_dmabuf, list);
10976 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
10977 		kfree(buf_ptr);
10978 	}
10979 
10980 	/* Enable softirqs again, done with phba->hbalock */
10981 	local_bh_enable();
10982 
10983 	/* Return any active mbox cmds */
10984 	del_timer_sync(&psli->mbox_tmo);
10985 
10986 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
10987 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
10988 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
10989 
10990 	return 1;
10991 }
10992 
10993 /**
10994  * lpfc_sli_pcimem_bcopy - SLI memory copy function
10995  * @srcp: Source memory pointer.
10996  * @destp: Destination memory pointer.
10997  * @cnt: Number of words required to be copied.
10998  *
10999  * This function is used for copying data between driver memory
11000  * and the SLI memory. This function also changes the endianness
11001  * of each word if native endianness is different from SLI
11002  * endianness. This function can be called with or without
11003  * lock.
11004  **/
11005 void
11006 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
11007 {
11008 	uint32_t *src = srcp;
11009 	uint32_t *dest = destp;
11010 	uint32_t ldata;
11011 	int i;
11012 
11013 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
11014 		ldata = *src;
11015 		ldata = le32_to_cpu(ldata);
11016 		*dest = ldata;
11017 		src++;
11018 		dest++;
11019 	}
11020 }
11021 
11022 
11023 /**
11024  * lpfc_sli_bemem_bcopy - SLI memory copy function
11025  * @srcp: Source memory pointer.
11026  * @destp: Destination memory pointer.
11027  * @cnt: Number of words required to be copied.
11028  *
11029  * This function is used for copying data between a data structure
11030  * with big endian representation to local endianness.
11031  * This function can be called with or without lock.
11032  **/
11033 void
11034 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
11035 {
11036 	uint32_t *src = srcp;
11037 	uint32_t *dest = destp;
11038 	uint32_t ldata;
11039 	int i;
11040 
11041 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
11042 		ldata = *src;
11043 		ldata = be32_to_cpu(ldata);
11044 		*dest = ldata;
11045 		src++;
11046 		dest++;
11047 	}
11048 }
11049 
11050 /**
11051  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
11052  * @phba: Pointer to HBA context object.
11053  * @pring: Pointer to driver SLI ring object.
11054  * @mp: Pointer to driver buffer object.
11055  *
11056  * This function is called with no lock held.
11057  * It always return zero after adding the buffer to the postbufq
11058  * buffer list.
11059  **/
11060 int
11061 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11062 			 struct lpfc_dmabuf *mp)
11063 {
11064 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
11065 	   later */
11066 	spin_lock_irq(&phba->hbalock);
11067 	list_add_tail(&mp->list, &pring->postbufq);
11068 	pring->postbufq_cnt++;
11069 	spin_unlock_irq(&phba->hbalock);
11070 	return 0;
11071 }
11072 
11073 /**
11074  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
11075  * @phba: Pointer to HBA context object.
11076  *
11077  * When HBQ is enabled, buffers are searched based on tags. This function
11078  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
11079  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
11080  * does not conflict with tags of buffer posted for unsolicited events.
11081  * The function returns the allocated tag. The function is called with
11082  * no locks held.
11083  **/
11084 uint32_t
11085 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
11086 {
11087 	spin_lock_irq(&phba->hbalock);
11088 	phba->buffer_tag_count++;
11089 	/*
11090 	 * Always set the QUE_BUFTAG_BIT to distiguish between
11091 	 * a tag assigned by HBQ.
11092 	 */
11093 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
11094 	spin_unlock_irq(&phba->hbalock);
11095 	return phba->buffer_tag_count;
11096 }
11097 
11098 /**
11099  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
11100  * @phba: Pointer to HBA context object.
11101  * @pring: Pointer to driver SLI ring object.
11102  * @tag: Buffer tag.
11103  *
11104  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
11105  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
11106  * iocb is posted to the response ring with the tag of the buffer.
11107  * This function searches the pring->postbufq list using the tag
11108  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
11109  * iocb. If the buffer is found then lpfc_dmabuf object of the
11110  * buffer is returned to the caller else NULL is returned.
11111  * This function is called with no lock held.
11112  **/
11113 struct lpfc_dmabuf *
11114 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11115 			uint32_t tag)
11116 {
11117 	struct lpfc_dmabuf *mp, *next_mp;
11118 	struct list_head *slp = &pring->postbufq;
11119 
11120 	/* Search postbufq, from the beginning, looking for a match on tag */
11121 	spin_lock_irq(&phba->hbalock);
11122 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11123 		if (mp->buffer_tag == tag) {
11124 			list_del_init(&mp->list);
11125 			pring->postbufq_cnt--;
11126 			spin_unlock_irq(&phba->hbalock);
11127 			return mp;
11128 		}
11129 	}
11130 
11131 	spin_unlock_irq(&phba->hbalock);
11132 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11133 			"0402 Cannot find virtual addr for buffer tag on "
11134 			"ring %d Data x%lx x%px x%px x%x\n",
11135 			pring->ringno, (unsigned long) tag,
11136 			slp->next, slp->prev, pring->postbufq_cnt);
11137 
11138 	return NULL;
11139 }
11140 
11141 /**
11142  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
11143  * @phba: Pointer to HBA context object.
11144  * @pring: Pointer to driver SLI ring object.
11145  * @phys: DMA address of the buffer.
11146  *
11147  * This function searches the buffer list using the dma_address
11148  * of unsolicited event to find the driver's lpfc_dmabuf object
11149  * corresponding to the dma_address. The function returns the
11150  * lpfc_dmabuf object if a buffer is found else it returns NULL.
11151  * This function is called by the ct and els unsolicited event
11152  * handlers to get the buffer associated with the unsolicited
11153  * event.
11154  *
11155  * This function is called with no lock held.
11156  **/
11157 struct lpfc_dmabuf *
11158 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11159 			 dma_addr_t phys)
11160 {
11161 	struct lpfc_dmabuf *mp, *next_mp;
11162 	struct list_head *slp = &pring->postbufq;
11163 
11164 	/* Search postbufq, from the beginning, looking for a match on phys */
11165 	spin_lock_irq(&phba->hbalock);
11166 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11167 		if (mp->phys == phys) {
11168 			list_del_init(&mp->list);
11169 			pring->postbufq_cnt--;
11170 			spin_unlock_irq(&phba->hbalock);
11171 			return mp;
11172 		}
11173 	}
11174 
11175 	spin_unlock_irq(&phba->hbalock);
11176 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11177 			"0410 Cannot find virtual addr for mapped buf on "
11178 			"ring %d Data x%llx x%px x%px x%x\n",
11179 			pring->ringno, (unsigned long long)phys,
11180 			slp->next, slp->prev, pring->postbufq_cnt);
11181 	return NULL;
11182 }
11183 
11184 /**
11185  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
11186  * @phba: Pointer to HBA context object.
11187  * @cmdiocb: Pointer to driver command iocb object.
11188  * @rspiocb: Pointer to driver response iocb object.
11189  *
11190  * This function is the completion handler for the abort iocbs for
11191  * ELS commands. This function is called from the ELS ring event
11192  * handler with no lock held. This function frees memory resources
11193  * associated with the abort iocb.
11194  **/
11195 static void
11196 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11197 			struct lpfc_iocbq *rspiocb)
11198 {
11199 	IOCB_t *irsp = &rspiocb->iocb;
11200 	uint16_t abort_iotag, abort_context;
11201 	struct lpfc_iocbq *abort_iocb = NULL;
11202 
11203 	if (irsp->ulpStatus) {
11204 
11205 		/*
11206 		 * Assume that the port already completed and returned, or
11207 		 * will return the iocb. Just Log the message.
11208 		 */
11209 		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
11210 		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
11211 
11212 		spin_lock_irq(&phba->hbalock);
11213 		if (phba->sli_rev < LPFC_SLI_REV4) {
11214 			if (irsp->ulpCommand == CMD_ABORT_XRI_CX &&
11215 			    irsp->ulpStatus == IOSTAT_LOCAL_REJECT &&
11216 			    irsp->un.ulpWord[4] == IOERR_ABORT_REQUESTED) {
11217 				spin_unlock_irq(&phba->hbalock);
11218 				goto release_iocb;
11219 			}
11220 			if (abort_iotag != 0 &&
11221 				abort_iotag <= phba->sli.last_iotag)
11222 				abort_iocb =
11223 					phba->sli.iocbq_lookup[abort_iotag];
11224 		} else
11225 			/* For sli4 the abort_tag is the XRI,
11226 			 * so the abort routine puts the iotag  of the iocb
11227 			 * being aborted in the context field of the abort
11228 			 * IOCB.
11229 			 */
11230 			abort_iocb = phba->sli.iocbq_lookup[abort_context];
11231 
11232 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
11233 				"0327 Cannot abort els iocb x%px "
11234 				"with tag %x context %x, abort status %x, "
11235 				"abort code %x\n",
11236 				abort_iocb, abort_iotag, abort_context,
11237 				irsp->ulpStatus, irsp->un.ulpWord[4]);
11238 
11239 		spin_unlock_irq(&phba->hbalock);
11240 	}
11241 release_iocb:
11242 	lpfc_sli_release_iocbq(phba, cmdiocb);
11243 	return;
11244 }
11245 
11246 /**
11247  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
11248  * @phba: Pointer to HBA context object.
11249  * @cmdiocb: Pointer to driver command iocb object.
11250  * @rspiocb: Pointer to driver response iocb object.
11251  *
11252  * The function is called from SLI ring event handler with no
11253  * lock held. This function is the completion handler for ELS commands
11254  * which are aborted. The function frees memory resources used for
11255  * the aborted ELS commands.
11256  **/
11257 static void
11258 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11259 		     struct lpfc_iocbq *rspiocb)
11260 {
11261 	IOCB_t *irsp = &rspiocb->iocb;
11262 
11263 	/* ELS cmd tag <ulpIoTag> completes */
11264 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
11265 			"0139 Ignoring ELS cmd tag x%x completion Data: "
11266 			"x%x x%x x%x\n",
11267 			irsp->ulpIoTag, irsp->ulpStatus,
11268 			irsp->un.ulpWord[4], irsp->ulpTimeout);
11269 	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
11270 		lpfc_ct_free_iocb(phba, cmdiocb);
11271 	else
11272 		lpfc_els_free_iocb(phba, cmdiocb);
11273 	return;
11274 }
11275 
11276 /**
11277  * lpfc_sli_abort_iotag_issue - Issue abort for a command iocb
11278  * @phba: Pointer to HBA context object.
11279  * @pring: Pointer to driver SLI ring object.
11280  * @cmdiocb: Pointer to driver command iocb object.
11281  *
11282  * This function issues an abort iocb for the provided command iocb down to
11283  * the port. Other than the case the outstanding command iocb is an abort
11284  * request, this function issues abort out unconditionally. This function is
11285  * called with hbalock held. The function returns 0 when it fails due to
11286  * memory allocation failure or when the command iocb is an abort request.
11287  **/
11288 static int
11289 lpfc_sli_abort_iotag_issue(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11290 			   struct lpfc_iocbq *cmdiocb)
11291 {
11292 	struct lpfc_vport *vport = cmdiocb->vport;
11293 	struct lpfc_iocbq *abtsiocbp;
11294 	IOCB_t *icmd = NULL;
11295 	IOCB_t *iabt = NULL;
11296 	int retval;
11297 	unsigned long iflags;
11298 	struct lpfc_nodelist *ndlp;
11299 
11300 	lockdep_assert_held(&phba->hbalock);
11301 
11302 	/*
11303 	 * There are certain command types we don't want to abort.  And we
11304 	 * don't want to abort commands that are already in the process of
11305 	 * being aborted.
11306 	 */
11307 	icmd = &cmdiocb->iocb;
11308 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11309 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
11310 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
11311 		return 0;
11312 
11313 	/* issue ABTS for this IOCB based on iotag */
11314 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
11315 	if (abtsiocbp == NULL)
11316 		return 0;
11317 
11318 	/* This signals the response to set the correct status
11319 	 * before calling the completion handler
11320 	 */
11321 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
11322 
11323 	iabt = &abtsiocbp->iocb;
11324 	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
11325 	iabt->un.acxri.abortContextTag = icmd->ulpContext;
11326 	if (phba->sli_rev == LPFC_SLI_REV4) {
11327 		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
11328 		iabt->un.acxri.abortContextTag = cmdiocb->iotag;
11329 	} else {
11330 		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
11331 		if (pring->ringno == LPFC_ELS_RING) {
11332 			ndlp = (struct lpfc_nodelist *)(cmdiocb->context1);
11333 			iabt->un.acxri.abortContextTag = ndlp->nlp_rpi;
11334 		}
11335 	}
11336 	iabt->ulpLe = 1;
11337 	iabt->ulpClass = icmd->ulpClass;
11338 
11339 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11340 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
11341 	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
11342 		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
11343 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
11344 		abtsiocbp->iocb_flag |= LPFC_IO_FOF;
11345 
11346 	if (phba->link_state >= LPFC_LINK_UP)
11347 		iabt->ulpCommand = CMD_ABORT_XRI_CN;
11348 	else
11349 		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
11350 
11351 	abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
11352 	abtsiocbp->vport = vport;
11353 
11354 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
11355 			 "0339 Abort xri x%x, original iotag x%x, "
11356 			 "abort cmd iotag x%x\n",
11357 			 iabt->un.acxri.abortIoTag,
11358 			 iabt->un.acxri.abortContextTag,
11359 			 abtsiocbp->iotag);
11360 
11361 	if (phba->sli_rev == LPFC_SLI_REV4) {
11362 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
11363 		if (unlikely(pring == NULL))
11364 			return 0;
11365 		/* Note: both hbalock and ring_lock need to be set here */
11366 		spin_lock_irqsave(&pring->ring_lock, iflags);
11367 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11368 			abtsiocbp, 0);
11369 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11370 	} else {
11371 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11372 			abtsiocbp, 0);
11373 	}
11374 
11375 	if (retval)
11376 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
11377 
11378 	/*
11379 	 * Caller to this routine should check for IOCB_ERROR
11380 	 * and handle it properly.  This routine no longer removes
11381 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
11382 	 */
11383 	return retval;
11384 }
11385 
11386 /**
11387  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
11388  * @phba: Pointer to HBA context object.
11389  * @pring: Pointer to driver SLI ring object.
11390  * @cmdiocb: Pointer to driver command iocb object.
11391  *
11392  * This function issues an abort iocb for the provided command iocb. In case
11393  * of unloading, the abort iocb will not be issued to commands on the ELS
11394  * ring. Instead, the callback function shall be changed to those commands
11395  * so that nothing happens when them finishes. This function is called with
11396  * hbalock held. The function returns 0 when the command iocb is an abort
11397  * request.
11398  **/
11399 int
11400 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11401 			   struct lpfc_iocbq *cmdiocb)
11402 {
11403 	struct lpfc_vport *vport = cmdiocb->vport;
11404 	int retval = IOCB_ERROR;
11405 	IOCB_t *icmd = NULL;
11406 
11407 	lockdep_assert_held(&phba->hbalock);
11408 
11409 	/*
11410 	 * There are certain command types we don't want to abort.  And we
11411 	 * don't want to abort commands that are already in the process of
11412 	 * being aborted.
11413 	 */
11414 	icmd = &cmdiocb->iocb;
11415 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11416 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
11417 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
11418 		return 0;
11419 
11420 	if (!pring) {
11421 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11422 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11423 		else
11424 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11425 		goto abort_iotag_exit;
11426 	}
11427 
11428 	/*
11429 	 * If we're unloading, don't abort iocb on the ELS ring, but change
11430 	 * the callback so that nothing happens when it finishes.
11431 	 */
11432 	if ((vport->load_flag & FC_UNLOADING) &&
11433 	    (pring->ringno == LPFC_ELS_RING)) {
11434 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11435 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11436 		else
11437 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11438 		goto abort_iotag_exit;
11439 	}
11440 
11441 	/* Now, we try to issue the abort to the cmdiocb out */
11442 	retval = lpfc_sli_abort_iotag_issue(phba, pring, cmdiocb);
11443 
11444 abort_iotag_exit:
11445 	/*
11446 	 * Caller to this routine should check for IOCB_ERROR
11447 	 * and handle it properly.  This routine no longer removes
11448 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
11449 	 */
11450 	return retval;
11451 }
11452 
11453 /**
11454  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
11455  * @phba: pointer to lpfc HBA data structure.
11456  *
11457  * This routine will abort all pending and outstanding iocbs to an HBA.
11458  **/
11459 void
11460 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
11461 {
11462 	struct lpfc_sli *psli = &phba->sli;
11463 	struct lpfc_sli_ring *pring;
11464 	struct lpfc_queue *qp = NULL;
11465 	int i;
11466 
11467 	if (phba->sli_rev != LPFC_SLI_REV4) {
11468 		for (i = 0; i < psli->num_rings; i++) {
11469 			pring = &psli->sli3_ring[i];
11470 			lpfc_sli_abort_iocb_ring(phba, pring);
11471 		}
11472 		return;
11473 	}
11474 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11475 		pring = qp->pring;
11476 		if (!pring)
11477 			continue;
11478 		lpfc_sli_abort_iocb_ring(phba, pring);
11479 	}
11480 }
11481 
11482 /**
11483  * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
11484  * @iocbq: Pointer to driver iocb object.
11485  * @vport: Pointer to driver virtual port object.
11486  * @tgt_id: SCSI ID of the target.
11487  * @lun_id: LUN ID of the scsi device.
11488  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
11489  *
11490  * This function acts as an iocb filter for functions which abort or count
11491  * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
11492  * 0 if the filtering criteria is met for the given iocb and will return
11493  * 1 if the filtering criteria is not met.
11494  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
11495  * given iocb is for the SCSI device specified by vport, tgt_id and
11496  * lun_id parameter.
11497  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
11498  * given iocb is for the SCSI target specified by vport and tgt_id
11499  * parameters.
11500  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
11501  * given iocb is for the SCSI host associated with the given vport.
11502  * This function is called with no locks held.
11503  **/
11504 static int
11505 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
11506 			   uint16_t tgt_id, uint64_t lun_id,
11507 			   lpfc_ctx_cmd ctx_cmd)
11508 {
11509 	struct lpfc_io_buf *lpfc_cmd;
11510 	int rc = 1;
11511 
11512 	if (iocbq->vport != vport)
11513 		return rc;
11514 
11515 	if (!(iocbq->iocb_flag &  LPFC_IO_FCP) ||
11516 	    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ))
11517 		return rc;
11518 
11519 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
11520 
11521 	if (lpfc_cmd->pCmd == NULL)
11522 		return rc;
11523 
11524 	switch (ctx_cmd) {
11525 	case LPFC_CTX_LUN:
11526 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11527 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
11528 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
11529 			rc = 0;
11530 		break;
11531 	case LPFC_CTX_TGT:
11532 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11533 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
11534 			rc = 0;
11535 		break;
11536 	case LPFC_CTX_HOST:
11537 		rc = 0;
11538 		break;
11539 	default:
11540 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
11541 			__func__, ctx_cmd);
11542 		break;
11543 	}
11544 
11545 	return rc;
11546 }
11547 
11548 /**
11549  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
11550  * @vport: Pointer to virtual port.
11551  * @tgt_id: SCSI ID of the target.
11552  * @lun_id: LUN ID of the scsi device.
11553  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11554  *
11555  * This function returns number of FCP commands pending for the vport.
11556  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
11557  * commands pending on the vport associated with SCSI device specified
11558  * by tgt_id and lun_id parameters.
11559  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
11560  * commands pending on the vport associated with SCSI target specified
11561  * by tgt_id parameter.
11562  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
11563  * commands pending on the vport.
11564  * This function returns the number of iocbs which satisfy the filter.
11565  * This function is called without any lock held.
11566  **/
11567 int
11568 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
11569 		  lpfc_ctx_cmd ctx_cmd)
11570 {
11571 	struct lpfc_hba *phba = vport->phba;
11572 	struct lpfc_iocbq *iocbq;
11573 	int sum, i;
11574 
11575 	spin_lock_irq(&phba->hbalock);
11576 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
11577 		iocbq = phba->sli.iocbq_lookup[i];
11578 
11579 		if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
11580 						ctx_cmd) == 0)
11581 			sum++;
11582 	}
11583 	spin_unlock_irq(&phba->hbalock);
11584 
11585 	return sum;
11586 }
11587 
11588 /**
11589  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
11590  * @phba: Pointer to HBA context object
11591  * @cmdiocb: Pointer to command iocb object.
11592  * @rspiocb: Pointer to response iocb object.
11593  *
11594  * This function is called when an aborted FCP iocb completes. This
11595  * function is called by the ring event handler with no lock held.
11596  * This function frees the iocb.
11597  **/
11598 void
11599 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11600 			struct lpfc_iocbq *rspiocb)
11601 {
11602 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11603 			"3096 ABORT_XRI_CN completing on rpi x%x "
11604 			"original iotag x%x, abort cmd iotag x%x "
11605 			"status 0x%x, reason 0x%x\n",
11606 			cmdiocb->iocb.un.acxri.abortContextTag,
11607 			cmdiocb->iocb.un.acxri.abortIoTag,
11608 			cmdiocb->iotag, rspiocb->iocb.ulpStatus,
11609 			rspiocb->iocb.un.ulpWord[4]);
11610 	lpfc_sli_release_iocbq(phba, cmdiocb);
11611 	return;
11612 }
11613 
11614 /**
11615  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
11616  * @vport: Pointer to virtual port.
11617  * @pring: Pointer to driver SLI ring object.
11618  * @tgt_id: SCSI ID of the target.
11619  * @lun_id: LUN ID of the scsi device.
11620  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11621  *
11622  * This function sends an abort command for every SCSI command
11623  * associated with the given virtual port pending on the ring
11624  * filtered by lpfc_sli_validate_fcp_iocb function.
11625  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
11626  * FCP iocbs associated with lun specified by tgt_id and lun_id
11627  * parameters
11628  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
11629  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
11630  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
11631  * FCP iocbs associated with virtual port.
11632  * This function returns number of iocbs it failed to abort.
11633  * This function is called with no locks held.
11634  **/
11635 int
11636 lpfc_sli_abort_iocb(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
11637 		    uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd abort_cmd)
11638 {
11639 	struct lpfc_hba *phba = vport->phba;
11640 	struct lpfc_iocbq *iocbq;
11641 	struct lpfc_iocbq *abtsiocb;
11642 	struct lpfc_sli_ring *pring_s4;
11643 	IOCB_t *cmd = NULL;
11644 	int errcnt = 0, ret_val = 0;
11645 	int i;
11646 
11647 	/* all I/Os are in process of being flushed */
11648 	if (phba->hba_flag & HBA_IOQ_FLUSH)
11649 		return errcnt;
11650 
11651 	for (i = 1; i <= phba->sli.last_iotag; i++) {
11652 		iocbq = phba->sli.iocbq_lookup[i];
11653 
11654 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
11655 					       abort_cmd) != 0)
11656 			continue;
11657 
11658 		/*
11659 		 * If the iocbq is already being aborted, don't take a second
11660 		 * action, but do count it.
11661 		 */
11662 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
11663 			continue;
11664 
11665 		/* issue ABTS for this IOCB based on iotag */
11666 		abtsiocb = lpfc_sli_get_iocbq(phba);
11667 		if (abtsiocb == NULL) {
11668 			errcnt++;
11669 			continue;
11670 		}
11671 
11672 		/* indicate the IO is being aborted by the driver. */
11673 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
11674 
11675 		cmd = &iocbq->iocb;
11676 		abtsiocb->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
11677 		abtsiocb->iocb.un.acxri.abortContextTag = cmd->ulpContext;
11678 		if (phba->sli_rev == LPFC_SLI_REV4)
11679 			abtsiocb->iocb.un.acxri.abortIoTag = iocbq->sli4_xritag;
11680 		else
11681 			abtsiocb->iocb.un.acxri.abortIoTag = cmd->ulpIoTag;
11682 		abtsiocb->iocb.ulpLe = 1;
11683 		abtsiocb->iocb.ulpClass = cmd->ulpClass;
11684 		abtsiocb->vport = vport;
11685 
11686 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11687 		abtsiocb->hba_wqidx = iocbq->hba_wqidx;
11688 		if (iocbq->iocb_flag & LPFC_IO_FCP)
11689 			abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
11690 		if (iocbq->iocb_flag & LPFC_IO_FOF)
11691 			abtsiocb->iocb_flag |= LPFC_IO_FOF;
11692 
11693 		if (lpfc_is_link_up(phba))
11694 			abtsiocb->iocb.ulpCommand = CMD_ABORT_XRI_CN;
11695 		else
11696 			abtsiocb->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
11697 
11698 		/* Setup callback routine and issue the command. */
11699 		abtsiocb->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
11700 		if (phba->sli_rev == LPFC_SLI_REV4) {
11701 			pring_s4 = lpfc_sli4_calc_ring(phba, iocbq);
11702 			if (!pring_s4)
11703 				continue;
11704 			ret_val = lpfc_sli_issue_iocb(phba, pring_s4->ringno,
11705 						      abtsiocb, 0);
11706 		} else
11707 			ret_val = lpfc_sli_issue_iocb(phba, pring->ringno,
11708 						      abtsiocb, 0);
11709 		if (ret_val == IOCB_ERROR) {
11710 			lpfc_sli_release_iocbq(phba, abtsiocb);
11711 			errcnt++;
11712 			continue;
11713 		}
11714 	}
11715 
11716 	return errcnt;
11717 }
11718 
11719 /**
11720  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
11721  * @vport: Pointer to virtual port.
11722  * @pring: Pointer to driver SLI ring object.
11723  * @tgt_id: SCSI ID of the target.
11724  * @lun_id: LUN ID of the scsi device.
11725  * @taskmgmt_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11726  *
11727  * This function sends an abort command for every SCSI command
11728  * associated with the given virtual port pending on the ring
11729  * filtered by lpfc_sli_validate_fcp_iocb function.
11730  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
11731  * FCP iocbs associated with lun specified by tgt_id and lun_id
11732  * parameters
11733  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
11734  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
11735  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
11736  * FCP iocbs associated with virtual port.
11737  * This function returns number of iocbs it aborted .
11738  * This function is called with no locks held right after a taskmgmt
11739  * command is sent.
11740  **/
11741 int
11742 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
11743 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
11744 {
11745 	struct lpfc_hba *phba = vport->phba;
11746 	struct lpfc_io_buf *lpfc_cmd;
11747 	struct lpfc_iocbq *abtsiocbq;
11748 	struct lpfc_nodelist *ndlp;
11749 	struct lpfc_iocbq *iocbq;
11750 	IOCB_t *icmd;
11751 	int sum, i, ret_val;
11752 	unsigned long iflags;
11753 	struct lpfc_sli_ring *pring_s4 = NULL;
11754 
11755 	spin_lock_irqsave(&phba->hbalock, iflags);
11756 
11757 	/* all I/Os are in process of being flushed */
11758 	if (phba->hba_flag & HBA_IOQ_FLUSH) {
11759 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11760 		return 0;
11761 	}
11762 	sum = 0;
11763 
11764 	for (i = 1; i <= phba->sli.last_iotag; i++) {
11765 		iocbq = phba->sli.iocbq_lookup[i];
11766 
11767 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
11768 					       cmd) != 0)
11769 			continue;
11770 
11771 		/* Guard against IO completion being called at same time */
11772 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
11773 		spin_lock(&lpfc_cmd->buf_lock);
11774 
11775 		if (!lpfc_cmd->pCmd) {
11776 			spin_unlock(&lpfc_cmd->buf_lock);
11777 			continue;
11778 		}
11779 
11780 		if (phba->sli_rev == LPFC_SLI_REV4) {
11781 			pring_s4 =
11782 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
11783 			if (!pring_s4) {
11784 				spin_unlock(&lpfc_cmd->buf_lock);
11785 				continue;
11786 			}
11787 			/* Note: both hbalock and ring_lock must be set here */
11788 			spin_lock(&pring_s4->ring_lock);
11789 		}
11790 
11791 		/*
11792 		 * If the iocbq is already being aborted, don't take a second
11793 		 * action, but do count it.
11794 		 */
11795 		if ((iocbq->iocb_flag & LPFC_DRIVER_ABORTED) ||
11796 		    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ)) {
11797 			if (phba->sli_rev == LPFC_SLI_REV4)
11798 				spin_unlock(&pring_s4->ring_lock);
11799 			spin_unlock(&lpfc_cmd->buf_lock);
11800 			continue;
11801 		}
11802 
11803 		/* issue ABTS for this IOCB based on iotag */
11804 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
11805 		if (!abtsiocbq) {
11806 			if (phba->sli_rev == LPFC_SLI_REV4)
11807 				spin_unlock(&pring_s4->ring_lock);
11808 			spin_unlock(&lpfc_cmd->buf_lock);
11809 			continue;
11810 		}
11811 
11812 		icmd = &iocbq->iocb;
11813 		abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
11814 		abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
11815 		if (phba->sli_rev == LPFC_SLI_REV4)
11816 			abtsiocbq->iocb.un.acxri.abortIoTag =
11817 							 iocbq->sli4_xritag;
11818 		else
11819 			abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
11820 		abtsiocbq->iocb.ulpLe = 1;
11821 		abtsiocbq->iocb.ulpClass = icmd->ulpClass;
11822 		abtsiocbq->vport = vport;
11823 
11824 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11825 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
11826 		if (iocbq->iocb_flag & LPFC_IO_FCP)
11827 			abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
11828 		if (iocbq->iocb_flag & LPFC_IO_FOF)
11829 			abtsiocbq->iocb_flag |= LPFC_IO_FOF;
11830 
11831 		ndlp = lpfc_cmd->rdata->pnode;
11832 
11833 		if (lpfc_is_link_up(phba) &&
11834 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
11835 			abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
11836 		else
11837 			abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
11838 
11839 		/* Setup callback routine and issue the command. */
11840 		abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
11841 
11842 		/*
11843 		 * Indicate the IO is being aborted by the driver and set
11844 		 * the caller's flag into the aborted IO.
11845 		 */
11846 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
11847 
11848 		if (phba->sli_rev == LPFC_SLI_REV4) {
11849 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
11850 							abtsiocbq, 0);
11851 			spin_unlock(&pring_s4->ring_lock);
11852 		} else {
11853 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
11854 							abtsiocbq, 0);
11855 		}
11856 
11857 		spin_unlock(&lpfc_cmd->buf_lock);
11858 
11859 		if (ret_val == IOCB_ERROR)
11860 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
11861 		else
11862 			sum++;
11863 	}
11864 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11865 	return sum;
11866 }
11867 
11868 /**
11869  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
11870  * @phba: Pointer to HBA context object.
11871  * @cmdiocbq: Pointer to command iocb.
11872  * @rspiocbq: Pointer to response iocb.
11873  *
11874  * This function is the completion handler for iocbs issued using
11875  * lpfc_sli_issue_iocb_wait function. This function is called by the
11876  * ring event handler function without any lock held. This function
11877  * can be called from both worker thread context and interrupt
11878  * context. This function also can be called from other thread which
11879  * cleans up the SLI layer objects.
11880  * This function copy the contents of the response iocb to the
11881  * response iocb memory object provided by the caller of
11882  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
11883  * sleeps for the iocb completion.
11884  **/
11885 static void
11886 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
11887 			struct lpfc_iocbq *cmdiocbq,
11888 			struct lpfc_iocbq *rspiocbq)
11889 {
11890 	wait_queue_head_t *pdone_q;
11891 	unsigned long iflags;
11892 	struct lpfc_io_buf *lpfc_cmd;
11893 
11894 	spin_lock_irqsave(&phba->hbalock, iflags);
11895 	if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
11896 
11897 		/*
11898 		 * A time out has occurred for the iocb.  If a time out
11899 		 * completion handler has been supplied, call it.  Otherwise,
11900 		 * just free the iocbq.
11901 		 */
11902 
11903 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11904 		cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
11905 		cmdiocbq->wait_iocb_cmpl = NULL;
11906 		if (cmdiocbq->iocb_cmpl)
11907 			(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
11908 		else
11909 			lpfc_sli_release_iocbq(phba, cmdiocbq);
11910 		return;
11911 	}
11912 
11913 	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
11914 	if (cmdiocbq->context2 && rspiocbq)
11915 		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
11916 		       &rspiocbq->iocb, sizeof(IOCB_t));
11917 
11918 	/* Set the exchange busy flag for task management commands */
11919 	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
11920 		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
11921 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
11922 			cur_iocbq);
11923 		if (rspiocbq && (rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY))
11924 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
11925 		else
11926 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
11927 	}
11928 
11929 	pdone_q = cmdiocbq->context_un.wait_queue;
11930 	if (pdone_q)
11931 		wake_up(pdone_q);
11932 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11933 	return;
11934 }
11935 
11936 /**
11937  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
11938  * @phba: Pointer to HBA context object..
11939  * @piocbq: Pointer to command iocb.
11940  * @flag: Flag to test.
11941  *
11942  * This routine grabs the hbalock and then test the iocb_flag to
11943  * see if the passed in flag is set.
11944  * Returns:
11945  * 1 if flag is set.
11946  * 0 if flag is not set.
11947  **/
11948 static int
11949 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
11950 		 struct lpfc_iocbq *piocbq, uint32_t flag)
11951 {
11952 	unsigned long iflags;
11953 	int ret;
11954 
11955 	spin_lock_irqsave(&phba->hbalock, iflags);
11956 	ret = piocbq->iocb_flag & flag;
11957 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11958 	return ret;
11959 
11960 }
11961 
11962 /**
11963  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
11964  * @phba: Pointer to HBA context object..
11965  * @pring: Pointer to sli ring.
11966  * @piocb: Pointer to command iocb.
11967  * @prspiocbq: Pointer to response iocb.
11968  * @timeout: Timeout in number of seconds.
11969  *
11970  * This function issues the iocb to firmware and waits for the
11971  * iocb to complete. The iocb_cmpl field of the shall be used
11972  * to handle iocbs which time out. If the field is NULL, the
11973  * function shall free the iocbq structure.  If more clean up is
11974  * needed, the caller is expected to provide a completion function
11975  * that will provide the needed clean up.  If the iocb command is
11976  * not completed within timeout seconds, the function will either
11977  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
11978  * completion function set in the iocb_cmpl field and then return
11979  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
11980  * resources if this function returns IOCB_TIMEDOUT.
11981  * The function waits for the iocb completion using an
11982  * non-interruptible wait.
11983  * This function will sleep while waiting for iocb completion.
11984  * So, this function should not be called from any context which
11985  * does not allow sleeping. Due to the same reason, this function
11986  * cannot be called with interrupt disabled.
11987  * This function assumes that the iocb completions occur while
11988  * this function sleep. So, this function cannot be called from
11989  * the thread which process iocb completion for this ring.
11990  * This function clears the iocb_flag of the iocb object before
11991  * issuing the iocb and the iocb completion handler sets this
11992  * flag and wakes this thread when the iocb completes.
11993  * The contents of the response iocb will be copied to prspiocbq
11994  * by the completion handler when the command completes.
11995  * This function returns IOCB_SUCCESS when success.
11996  * This function is called with no lock held.
11997  **/
11998 int
11999 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
12000 			 uint32_t ring_number,
12001 			 struct lpfc_iocbq *piocb,
12002 			 struct lpfc_iocbq *prspiocbq,
12003 			 uint32_t timeout)
12004 {
12005 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
12006 	long timeleft, timeout_req = 0;
12007 	int retval = IOCB_SUCCESS;
12008 	uint32_t creg_val;
12009 	struct lpfc_iocbq *iocb;
12010 	int txq_cnt = 0;
12011 	int txcmplq_cnt = 0;
12012 	struct lpfc_sli_ring *pring;
12013 	unsigned long iflags;
12014 	bool iocb_completed = true;
12015 
12016 	if (phba->sli_rev >= LPFC_SLI_REV4)
12017 		pring = lpfc_sli4_calc_ring(phba, piocb);
12018 	else
12019 		pring = &phba->sli.sli3_ring[ring_number];
12020 	/*
12021 	 * If the caller has provided a response iocbq buffer, then context2
12022 	 * is NULL or its an error.
12023 	 */
12024 	if (prspiocbq) {
12025 		if (piocb->context2)
12026 			return IOCB_ERROR;
12027 		piocb->context2 = prspiocbq;
12028 	}
12029 
12030 	piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
12031 	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
12032 	piocb->context_un.wait_queue = &done_q;
12033 	piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
12034 
12035 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12036 		if (lpfc_readl(phba->HCregaddr, &creg_val))
12037 			return IOCB_ERROR;
12038 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
12039 		writel(creg_val, phba->HCregaddr);
12040 		readl(phba->HCregaddr); /* flush */
12041 	}
12042 
12043 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
12044 				     SLI_IOCB_RET_IOCB);
12045 	if (retval == IOCB_SUCCESS) {
12046 		timeout_req = msecs_to_jiffies(timeout * 1000);
12047 		timeleft = wait_event_timeout(done_q,
12048 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
12049 				timeout_req);
12050 		spin_lock_irqsave(&phba->hbalock, iflags);
12051 		if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
12052 
12053 			/*
12054 			 * IOCB timed out.  Inform the wake iocb wait
12055 			 * completion function and set local status
12056 			 */
12057 
12058 			iocb_completed = false;
12059 			piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
12060 		}
12061 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12062 		if (iocb_completed) {
12063 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12064 					"0331 IOCB wake signaled\n");
12065 			/* Note: we are not indicating if the IOCB has a success
12066 			 * status or not - that's for the caller to check.
12067 			 * IOCB_SUCCESS means just that the command was sent and
12068 			 * completed. Not that it completed successfully.
12069 			 * */
12070 		} else if (timeleft == 0) {
12071 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12072 					"0338 IOCB wait timeout error - no "
12073 					"wake response Data x%x\n", timeout);
12074 			retval = IOCB_TIMEDOUT;
12075 		} else {
12076 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12077 					"0330 IOCB wake NOT set, "
12078 					"Data x%x x%lx\n",
12079 					timeout, (timeleft / jiffies));
12080 			retval = IOCB_TIMEDOUT;
12081 		}
12082 	} else if (retval == IOCB_BUSY) {
12083 		if (phba->cfg_log_verbose & LOG_SLI) {
12084 			list_for_each_entry(iocb, &pring->txq, list) {
12085 				txq_cnt++;
12086 			}
12087 			list_for_each_entry(iocb, &pring->txcmplq, list) {
12088 				txcmplq_cnt++;
12089 			}
12090 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12091 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
12092 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
12093 		}
12094 		return retval;
12095 	} else {
12096 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12097 				"0332 IOCB wait issue failed, Data x%x\n",
12098 				retval);
12099 		retval = IOCB_ERROR;
12100 	}
12101 
12102 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12103 		if (lpfc_readl(phba->HCregaddr, &creg_val))
12104 			return IOCB_ERROR;
12105 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
12106 		writel(creg_val, phba->HCregaddr);
12107 		readl(phba->HCregaddr); /* flush */
12108 	}
12109 
12110 	if (prspiocbq)
12111 		piocb->context2 = NULL;
12112 
12113 	piocb->context_un.wait_queue = NULL;
12114 	piocb->iocb_cmpl = NULL;
12115 	return retval;
12116 }
12117 
12118 /**
12119  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
12120  * @phba: Pointer to HBA context object.
12121  * @pmboxq: Pointer to driver mailbox object.
12122  * @timeout: Timeout in number of seconds.
12123  *
12124  * This function issues the mailbox to firmware and waits for the
12125  * mailbox command to complete. If the mailbox command is not
12126  * completed within timeout seconds, it returns MBX_TIMEOUT.
12127  * The function waits for the mailbox completion using an
12128  * interruptible wait. If the thread is woken up due to a
12129  * signal, MBX_TIMEOUT error is returned to the caller. Caller
12130  * should not free the mailbox resources, if this function returns
12131  * MBX_TIMEOUT.
12132  * This function will sleep while waiting for mailbox completion.
12133  * So, this function should not be called from any context which
12134  * does not allow sleeping. Due to the same reason, this function
12135  * cannot be called with interrupt disabled.
12136  * This function assumes that the mailbox completion occurs while
12137  * this function sleep. So, this function cannot be called from
12138  * the worker thread which processes mailbox completion.
12139  * This function is called in the context of HBA management
12140  * applications.
12141  * This function returns MBX_SUCCESS when successful.
12142  * This function is called with no lock held.
12143  **/
12144 int
12145 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
12146 			 uint32_t timeout)
12147 {
12148 	struct completion mbox_done;
12149 	int retval;
12150 	unsigned long flag;
12151 
12152 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
12153 	/* setup wake call as IOCB callback */
12154 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
12155 
12156 	/* setup context3 field to pass wait_queue pointer to wake function  */
12157 	init_completion(&mbox_done);
12158 	pmboxq->context3 = &mbox_done;
12159 	/* now issue the command */
12160 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
12161 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
12162 		wait_for_completion_timeout(&mbox_done,
12163 					    msecs_to_jiffies(timeout * 1000));
12164 
12165 		spin_lock_irqsave(&phba->hbalock, flag);
12166 		pmboxq->context3 = NULL;
12167 		/*
12168 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
12169 		 * else do not free the resources.
12170 		 */
12171 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
12172 			retval = MBX_SUCCESS;
12173 		} else {
12174 			retval = MBX_TIMEOUT;
12175 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
12176 		}
12177 		spin_unlock_irqrestore(&phba->hbalock, flag);
12178 	}
12179 	return retval;
12180 }
12181 
12182 /**
12183  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
12184  * @phba: Pointer to HBA context.
12185  *
12186  * This function is called to shutdown the driver's mailbox sub-system.
12187  * It first marks the mailbox sub-system is in a block state to prevent
12188  * the asynchronous mailbox command from issued off the pending mailbox
12189  * command queue. If the mailbox command sub-system shutdown is due to
12190  * HBA error conditions such as EEH or ERATT, this routine shall invoke
12191  * the mailbox sub-system flush routine to forcefully bring down the
12192  * mailbox sub-system. Otherwise, if it is due to normal condition (such
12193  * as with offline or HBA function reset), this routine will wait for the
12194  * outstanding mailbox command to complete before invoking the mailbox
12195  * sub-system flush routine to gracefully bring down mailbox sub-system.
12196  **/
12197 void
12198 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
12199 {
12200 	struct lpfc_sli *psli = &phba->sli;
12201 	unsigned long timeout;
12202 
12203 	if (mbx_action == LPFC_MBX_NO_WAIT) {
12204 		/* delay 100ms for port state */
12205 		msleep(100);
12206 		lpfc_sli_mbox_sys_flush(phba);
12207 		return;
12208 	}
12209 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
12210 
12211 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12212 	local_bh_disable();
12213 
12214 	spin_lock_irq(&phba->hbalock);
12215 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
12216 
12217 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
12218 		/* Determine how long we might wait for the active mailbox
12219 		 * command to be gracefully completed by firmware.
12220 		 */
12221 		if (phba->sli.mbox_active)
12222 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
12223 						phba->sli.mbox_active) *
12224 						1000) + jiffies;
12225 		spin_unlock_irq(&phba->hbalock);
12226 
12227 		/* Enable softirqs again, done with phba->hbalock */
12228 		local_bh_enable();
12229 
12230 		while (phba->sli.mbox_active) {
12231 			/* Check active mailbox complete status every 2ms */
12232 			msleep(2);
12233 			if (time_after(jiffies, timeout))
12234 				/* Timeout, let the mailbox flush routine to
12235 				 * forcefully release active mailbox command
12236 				 */
12237 				break;
12238 		}
12239 	} else {
12240 		spin_unlock_irq(&phba->hbalock);
12241 
12242 		/* Enable softirqs again, done with phba->hbalock */
12243 		local_bh_enable();
12244 	}
12245 
12246 	lpfc_sli_mbox_sys_flush(phba);
12247 }
12248 
12249 /**
12250  * lpfc_sli_eratt_read - read sli-3 error attention events
12251  * @phba: Pointer to HBA context.
12252  *
12253  * This function is called to read the SLI3 device error attention registers
12254  * for possible error attention events. The caller must hold the hostlock
12255  * with spin_lock_irq().
12256  *
12257  * This function returns 1 when there is Error Attention in the Host Attention
12258  * Register and returns 0 otherwise.
12259  **/
12260 static int
12261 lpfc_sli_eratt_read(struct lpfc_hba *phba)
12262 {
12263 	uint32_t ha_copy;
12264 
12265 	/* Read chip Host Attention (HA) register */
12266 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
12267 		goto unplug_err;
12268 
12269 	if (ha_copy & HA_ERATT) {
12270 		/* Read host status register to retrieve error event */
12271 		if (lpfc_sli_read_hs(phba))
12272 			goto unplug_err;
12273 
12274 		/* Check if there is a deferred error condition is active */
12275 		if ((HS_FFER1 & phba->work_hs) &&
12276 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12277 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
12278 			phba->hba_flag |= DEFER_ERATT;
12279 			/* Clear all interrupt enable conditions */
12280 			writel(0, phba->HCregaddr);
12281 			readl(phba->HCregaddr);
12282 		}
12283 
12284 		/* Set the driver HA work bitmap */
12285 		phba->work_ha |= HA_ERATT;
12286 		/* Indicate polling handles this ERATT */
12287 		phba->hba_flag |= HBA_ERATT_HANDLED;
12288 		return 1;
12289 	}
12290 	return 0;
12291 
12292 unplug_err:
12293 	/* Set the driver HS work bitmap */
12294 	phba->work_hs |= UNPLUG_ERR;
12295 	/* Set the driver HA work bitmap */
12296 	phba->work_ha |= HA_ERATT;
12297 	/* Indicate polling handles this ERATT */
12298 	phba->hba_flag |= HBA_ERATT_HANDLED;
12299 	return 1;
12300 }
12301 
12302 /**
12303  * lpfc_sli4_eratt_read - read sli-4 error attention events
12304  * @phba: Pointer to HBA context.
12305  *
12306  * This function is called to read the SLI4 device error attention registers
12307  * for possible error attention events. The caller must hold the hostlock
12308  * with spin_lock_irq().
12309  *
12310  * This function returns 1 when there is Error Attention in the Host Attention
12311  * Register and returns 0 otherwise.
12312  **/
12313 static int
12314 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
12315 {
12316 	uint32_t uerr_sta_hi, uerr_sta_lo;
12317 	uint32_t if_type, portsmphr;
12318 	struct lpfc_register portstat_reg;
12319 
12320 	/*
12321 	 * For now, use the SLI4 device internal unrecoverable error
12322 	 * registers for error attention. This can be changed later.
12323 	 */
12324 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12325 	switch (if_type) {
12326 	case LPFC_SLI_INTF_IF_TYPE_0:
12327 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
12328 			&uerr_sta_lo) ||
12329 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
12330 			&uerr_sta_hi)) {
12331 			phba->work_hs |= UNPLUG_ERR;
12332 			phba->work_ha |= HA_ERATT;
12333 			phba->hba_flag |= HBA_ERATT_HANDLED;
12334 			return 1;
12335 		}
12336 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
12337 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
12338 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12339 					"1423 HBA Unrecoverable error: "
12340 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
12341 					"ue_mask_lo_reg=0x%x, "
12342 					"ue_mask_hi_reg=0x%x\n",
12343 					uerr_sta_lo, uerr_sta_hi,
12344 					phba->sli4_hba.ue_mask_lo,
12345 					phba->sli4_hba.ue_mask_hi);
12346 			phba->work_status[0] = uerr_sta_lo;
12347 			phba->work_status[1] = uerr_sta_hi;
12348 			phba->work_ha |= HA_ERATT;
12349 			phba->hba_flag |= HBA_ERATT_HANDLED;
12350 			return 1;
12351 		}
12352 		break;
12353 	case LPFC_SLI_INTF_IF_TYPE_2:
12354 	case LPFC_SLI_INTF_IF_TYPE_6:
12355 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
12356 			&portstat_reg.word0) ||
12357 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
12358 			&portsmphr)){
12359 			phba->work_hs |= UNPLUG_ERR;
12360 			phba->work_ha |= HA_ERATT;
12361 			phba->hba_flag |= HBA_ERATT_HANDLED;
12362 			return 1;
12363 		}
12364 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
12365 			phba->work_status[0] =
12366 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
12367 			phba->work_status[1] =
12368 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
12369 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12370 					"2885 Port Status Event: "
12371 					"port status reg 0x%x, "
12372 					"port smphr reg 0x%x, "
12373 					"error 1=0x%x, error 2=0x%x\n",
12374 					portstat_reg.word0,
12375 					portsmphr,
12376 					phba->work_status[0],
12377 					phba->work_status[1]);
12378 			phba->work_ha |= HA_ERATT;
12379 			phba->hba_flag |= HBA_ERATT_HANDLED;
12380 			return 1;
12381 		}
12382 		break;
12383 	case LPFC_SLI_INTF_IF_TYPE_1:
12384 	default:
12385 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12386 				"2886 HBA Error Attention on unsupported "
12387 				"if type %d.", if_type);
12388 		return 1;
12389 	}
12390 
12391 	return 0;
12392 }
12393 
12394 /**
12395  * lpfc_sli_check_eratt - check error attention events
12396  * @phba: Pointer to HBA context.
12397  *
12398  * This function is called from timer soft interrupt context to check HBA's
12399  * error attention register bit for error attention events.
12400  *
12401  * This function returns 1 when there is Error Attention in the Host Attention
12402  * Register and returns 0 otherwise.
12403  **/
12404 int
12405 lpfc_sli_check_eratt(struct lpfc_hba *phba)
12406 {
12407 	uint32_t ha_copy;
12408 
12409 	/* If somebody is waiting to handle an eratt, don't process it
12410 	 * here. The brdkill function will do this.
12411 	 */
12412 	if (phba->link_flag & LS_IGNORE_ERATT)
12413 		return 0;
12414 
12415 	/* Check if interrupt handler handles this ERATT */
12416 	spin_lock_irq(&phba->hbalock);
12417 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
12418 		/* Interrupt handler has handled ERATT */
12419 		spin_unlock_irq(&phba->hbalock);
12420 		return 0;
12421 	}
12422 
12423 	/*
12424 	 * If there is deferred error attention, do not check for error
12425 	 * attention
12426 	 */
12427 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12428 		spin_unlock_irq(&phba->hbalock);
12429 		return 0;
12430 	}
12431 
12432 	/* If PCI channel is offline, don't process it */
12433 	if (unlikely(pci_channel_offline(phba->pcidev))) {
12434 		spin_unlock_irq(&phba->hbalock);
12435 		return 0;
12436 	}
12437 
12438 	switch (phba->sli_rev) {
12439 	case LPFC_SLI_REV2:
12440 	case LPFC_SLI_REV3:
12441 		/* Read chip Host Attention (HA) register */
12442 		ha_copy = lpfc_sli_eratt_read(phba);
12443 		break;
12444 	case LPFC_SLI_REV4:
12445 		/* Read device Uncoverable Error (UERR) registers */
12446 		ha_copy = lpfc_sli4_eratt_read(phba);
12447 		break;
12448 	default:
12449 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12450 				"0299 Invalid SLI revision (%d)\n",
12451 				phba->sli_rev);
12452 		ha_copy = 0;
12453 		break;
12454 	}
12455 	spin_unlock_irq(&phba->hbalock);
12456 
12457 	return ha_copy;
12458 }
12459 
12460 /**
12461  * lpfc_intr_state_check - Check device state for interrupt handling
12462  * @phba: Pointer to HBA context.
12463  *
12464  * This inline routine checks whether a device or its PCI slot is in a state
12465  * that the interrupt should be handled.
12466  *
12467  * This function returns 0 if the device or the PCI slot is in a state that
12468  * interrupt should be handled, otherwise -EIO.
12469  */
12470 static inline int
12471 lpfc_intr_state_check(struct lpfc_hba *phba)
12472 {
12473 	/* If the pci channel is offline, ignore all the interrupts */
12474 	if (unlikely(pci_channel_offline(phba->pcidev)))
12475 		return -EIO;
12476 
12477 	/* Update device level interrupt statistics */
12478 	phba->sli.slistat.sli_intr++;
12479 
12480 	/* Ignore all interrupts during initialization. */
12481 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
12482 		return -EIO;
12483 
12484 	return 0;
12485 }
12486 
12487 /**
12488  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
12489  * @irq: Interrupt number.
12490  * @dev_id: The device context pointer.
12491  *
12492  * This function is directly called from the PCI layer as an interrupt
12493  * service routine when device with SLI-3 interface spec is enabled with
12494  * MSI-X multi-message interrupt mode and there are slow-path events in
12495  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
12496  * interrupt mode, this function is called as part of the device-level
12497  * interrupt handler. When the PCI slot is in error recovery or the HBA
12498  * is undergoing initialization, the interrupt handler will not process
12499  * the interrupt. The link attention and ELS ring attention events are
12500  * handled by the worker thread. The interrupt handler signals the worker
12501  * thread and returns for these events. This function is called without
12502  * any lock held. It gets the hbalock to access and update SLI data
12503  * structures.
12504  *
12505  * This function returns IRQ_HANDLED when interrupt is handled else it
12506  * returns IRQ_NONE.
12507  **/
12508 irqreturn_t
12509 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
12510 {
12511 	struct lpfc_hba  *phba;
12512 	uint32_t ha_copy, hc_copy;
12513 	uint32_t work_ha_copy;
12514 	unsigned long status;
12515 	unsigned long iflag;
12516 	uint32_t control;
12517 
12518 	MAILBOX_t *mbox, *pmbox;
12519 	struct lpfc_vport *vport;
12520 	struct lpfc_nodelist *ndlp;
12521 	struct lpfc_dmabuf *mp;
12522 	LPFC_MBOXQ_t *pmb;
12523 	int rc;
12524 
12525 	/*
12526 	 * Get the driver's phba structure from the dev_id and
12527 	 * assume the HBA is not interrupting.
12528 	 */
12529 	phba = (struct lpfc_hba *)dev_id;
12530 
12531 	if (unlikely(!phba))
12532 		return IRQ_NONE;
12533 
12534 	/*
12535 	 * Stuff needs to be attented to when this function is invoked as an
12536 	 * individual interrupt handler in MSI-X multi-message interrupt mode
12537 	 */
12538 	if (phba->intr_type == MSIX) {
12539 		/* Check device state for handling interrupt */
12540 		if (lpfc_intr_state_check(phba))
12541 			return IRQ_NONE;
12542 		/* Need to read HA REG for slow-path events */
12543 		spin_lock_irqsave(&phba->hbalock, iflag);
12544 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
12545 			goto unplug_error;
12546 		/* If somebody is waiting to handle an eratt don't process it
12547 		 * here. The brdkill function will do this.
12548 		 */
12549 		if (phba->link_flag & LS_IGNORE_ERATT)
12550 			ha_copy &= ~HA_ERATT;
12551 		/* Check the need for handling ERATT in interrupt handler */
12552 		if (ha_copy & HA_ERATT) {
12553 			if (phba->hba_flag & HBA_ERATT_HANDLED)
12554 				/* ERATT polling has handled ERATT */
12555 				ha_copy &= ~HA_ERATT;
12556 			else
12557 				/* Indicate interrupt handler handles ERATT */
12558 				phba->hba_flag |= HBA_ERATT_HANDLED;
12559 		}
12560 
12561 		/*
12562 		 * If there is deferred error attention, do not check for any
12563 		 * interrupt.
12564 		 */
12565 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12566 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12567 			return IRQ_NONE;
12568 		}
12569 
12570 		/* Clear up only attention source related to slow-path */
12571 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
12572 			goto unplug_error;
12573 
12574 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
12575 			HC_LAINT_ENA | HC_ERINT_ENA),
12576 			phba->HCregaddr);
12577 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
12578 			phba->HAregaddr);
12579 		writel(hc_copy, phba->HCregaddr);
12580 		readl(phba->HAregaddr); /* flush */
12581 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12582 	} else
12583 		ha_copy = phba->ha_copy;
12584 
12585 	work_ha_copy = ha_copy & phba->work_ha_mask;
12586 
12587 	if (work_ha_copy) {
12588 		if (work_ha_copy & HA_LATT) {
12589 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
12590 				/*
12591 				 * Turn off Link Attention interrupts
12592 				 * until CLEAR_LA done
12593 				 */
12594 				spin_lock_irqsave(&phba->hbalock, iflag);
12595 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
12596 				if (lpfc_readl(phba->HCregaddr, &control))
12597 					goto unplug_error;
12598 				control &= ~HC_LAINT_ENA;
12599 				writel(control, phba->HCregaddr);
12600 				readl(phba->HCregaddr); /* flush */
12601 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12602 			}
12603 			else
12604 				work_ha_copy &= ~HA_LATT;
12605 		}
12606 
12607 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
12608 			/*
12609 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
12610 			 * the only slow ring.
12611 			 */
12612 			status = (work_ha_copy &
12613 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
12614 			status >>= (4*LPFC_ELS_RING);
12615 			if (status & HA_RXMASK) {
12616 				spin_lock_irqsave(&phba->hbalock, iflag);
12617 				if (lpfc_readl(phba->HCregaddr, &control))
12618 					goto unplug_error;
12619 
12620 				lpfc_debugfs_slow_ring_trc(phba,
12621 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
12622 				control, status,
12623 				(uint32_t)phba->sli.slistat.sli_intr);
12624 
12625 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
12626 					lpfc_debugfs_slow_ring_trc(phba,
12627 						"ISR Disable ring:"
12628 						"pwork:x%x hawork:x%x wait:x%x",
12629 						phba->work_ha, work_ha_copy,
12630 						(uint32_t)((unsigned long)
12631 						&phba->work_waitq));
12632 
12633 					control &=
12634 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
12635 					writel(control, phba->HCregaddr);
12636 					readl(phba->HCregaddr); /* flush */
12637 				}
12638 				else {
12639 					lpfc_debugfs_slow_ring_trc(phba,
12640 						"ISR slow ring:   pwork:"
12641 						"x%x hawork:x%x wait:x%x",
12642 						phba->work_ha, work_ha_copy,
12643 						(uint32_t)((unsigned long)
12644 						&phba->work_waitq));
12645 				}
12646 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12647 			}
12648 		}
12649 		spin_lock_irqsave(&phba->hbalock, iflag);
12650 		if (work_ha_copy & HA_ERATT) {
12651 			if (lpfc_sli_read_hs(phba))
12652 				goto unplug_error;
12653 			/*
12654 			 * Check if there is a deferred error condition
12655 			 * is active
12656 			 */
12657 			if ((HS_FFER1 & phba->work_hs) &&
12658 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12659 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
12660 				  phba->work_hs)) {
12661 				phba->hba_flag |= DEFER_ERATT;
12662 				/* Clear all interrupt enable conditions */
12663 				writel(0, phba->HCregaddr);
12664 				readl(phba->HCregaddr);
12665 			}
12666 		}
12667 
12668 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
12669 			pmb = phba->sli.mbox_active;
12670 			pmbox = &pmb->u.mb;
12671 			mbox = phba->mbox;
12672 			vport = pmb->vport;
12673 
12674 			/* First check out the status word */
12675 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
12676 			if (pmbox->mbxOwner != OWN_HOST) {
12677 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12678 				/*
12679 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
12680 				 * mbxStatus <status>
12681 				 */
12682 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
12683 						LOG_SLI,
12684 						"(%d):0304 Stray Mailbox "
12685 						"Interrupt mbxCommand x%x "
12686 						"mbxStatus x%x\n",
12687 						(vport ? vport->vpi : 0),
12688 						pmbox->mbxCommand,
12689 						pmbox->mbxStatus);
12690 				/* clear mailbox attention bit */
12691 				work_ha_copy &= ~HA_MBATT;
12692 			} else {
12693 				phba->sli.mbox_active = NULL;
12694 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12695 				phba->last_completion_time = jiffies;
12696 				del_timer(&phba->sli.mbox_tmo);
12697 				if (pmb->mbox_cmpl) {
12698 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
12699 							MAILBOX_CMD_SIZE);
12700 					if (pmb->out_ext_byte_len &&
12701 						pmb->ctx_buf)
12702 						lpfc_sli_pcimem_bcopy(
12703 						phba->mbox_ext,
12704 						pmb->ctx_buf,
12705 						pmb->out_ext_byte_len);
12706 				}
12707 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
12708 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
12709 
12710 					lpfc_debugfs_disc_trc(vport,
12711 						LPFC_DISC_TRC_MBOX_VPORT,
12712 						"MBOX dflt rpi: : "
12713 						"status:x%x rpi:x%x",
12714 						(uint32_t)pmbox->mbxStatus,
12715 						pmbox->un.varWords[0], 0);
12716 
12717 					if (!pmbox->mbxStatus) {
12718 						mp = (struct lpfc_dmabuf *)
12719 							(pmb->ctx_buf);
12720 						ndlp = (struct lpfc_nodelist *)
12721 							pmb->ctx_ndlp;
12722 
12723 						/* Reg_LOGIN of dflt RPI was
12724 						 * successful. new lets get
12725 						 * rid of the RPI using the
12726 						 * same mbox buffer.
12727 						 */
12728 						lpfc_unreg_login(phba,
12729 							vport->vpi,
12730 							pmbox->un.varWords[0],
12731 							pmb);
12732 						pmb->mbox_cmpl =
12733 							lpfc_mbx_cmpl_dflt_rpi;
12734 						pmb->ctx_buf = mp;
12735 						pmb->ctx_ndlp = ndlp;
12736 						pmb->vport = vport;
12737 						rc = lpfc_sli_issue_mbox(phba,
12738 								pmb,
12739 								MBX_NOWAIT);
12740 						if (rc != MBX_BUSY)
12741 							lpfc_printf_log(phba,
12742 							KERN_ERR,
12743 							LOG_MBOX | LOG_SLI,
12744 							"0350 rc should have"
12745 							"been MBX_BUSY\n");
12746 						if (rc != MBX_NOT_FINISHED)
12747 							goto send_current_mbox;
12748 					}
12749 				}
12750 				spin_lock_irqsave(
12751 						&phba->pport->work_port_lock,
12752 						iflag);
12753 				phba->pport->work_port_events &=
12754 					~WORKER_MBOX_TMO;
12755 				spin_unlock_irqrestore(
12756 						&phba->pport->work_port_lock,
12757 						iflag);
12758 				lpfc_mbox_cmpl_put(phba, pmb);
12759 			}
12760 		} else
12761 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12762 
12763 		if ((work_ha_copy & HA_MBATT) &&
12764 		    (phba->sli.mbox_active == NULL)) {
12765 send_current_mbox:
12766 			/* Process next mailbox command if there is one */
12767 			do {
12768 				rc = lpfc_sli_issue_mbox(phba, NULL,
12769 							 MBX_NOWAIT);
12770 			} while (rc == MBX_NOT_FINISHED);
12771 			if (rc != MBX_SUCCESS)
12772 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
12773 						LOG_SLI, "0349 rc should be "
12774 						"MBX_SUCCESS\n");
12775 		}
12776 
12777 		spin_lock_irqsave(&phba->hbalock, iflag);
12778 		phba->work_ha |= work_ha_copy;
12779 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12780 		lpfc_worker_wake_up(phba);
12781 	}
12782 	return IRQ_HANDLED;
12783 unplug_error:
12784 	spin_unlock_irqrestore(&phba->hbalock, iflag);
12785 	return IRQ_HANDLED;
12786 
12787 } /* lpfc_sli_sp_intr_handler */
12788 
12789 /**
12790  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
12791  * @irq: Interrupt number.
12792  * @dev_id: The device context pointer.
12793  *
12794  * This function is directly called from the PCI layer as an interrupt
12795  * service routine when device with SLI-3 interface spec is enabled with
12796  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
12797  * ring event in the HBA. However, when the device is enabled with either
12798  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
12799  * device-level interrupt handler. When the PCI slot is in error recovery
12800  * or the HBA is undergoing initialization, the interrupt handler will not
12801  * process the interrupt. The SCSI FCP fast-path ring event are handled in
12802  * the intrrupt context. This function is called without any lock held.
12803  * It gets the hbalock to access and update SLI data structures.
12804  *
12805  * This function returns IRQ_HANDLED when interrupt is handled else it
12806  * returns IRQ_NONE.
12807  **/
12808 irqreturn_t
12809 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
12810 {
12811 	struct lpfc_hba  *phba;
12812 	uint32_t ha_copy;
12813 	unsigned long status;
12814 	unsigned long iflag;
12815 	struct lpfc_sli_ring *pring;
12816 
12817 	/* Get the driver's phba structure from the dev_id and
12818 	 * assume the HBA is not interrupting.
12819 	 */
12820 	phba = (struct lpfc_hba *) dev_id;
12821 
12822 	if (unlikely(!phba))
12823 		return IRQ_NONE;
12824 
12825 	/*
12826 	 * Stuff needs to be attented to when this function is invoked as an
12827 	 * individual interrupt handler in MSI-X multi-message interrupt mode
12828 	 */
12829 	if (phba->intr_type == MSIX) {
12830 		/* Check device state for handling interrupt */
12831 		if (lpfc_intr_state_check(phba))
12832 			return IRQ_NONE;
12833 		/* Need to read HA REG for FCP ring and other ring events */
12834 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
12835 			return IRQ_HANDLED;
12836 		/* Clear up only attention source related to fast-path */
12837 		spin_lock_irqsave(&phba->hbalock, iflag);
12838 		/*
12839 		 * If there is deferred error attention, do not check for
12840 		 * any interrupt.
12841 		 */
12842 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12843 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12844 			return IRQ_NONE;
12845 		}
12846 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
12847 			phba->HAregaddr);
12848 		readl(phba->HAregaddr); /* flush */
12849 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12850 	} else
12851 		ha_copy = phba->ha_copy;
12852 
12853 	/*
12854 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
12855 	 */
12856 	ha_copy &= ~(phba->work_ha_mask);
12857 
12858 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
12859 	status >>= (4*LPFC_FCP_RING);
12860 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12861 	if (status & HA_RXMASK)
12862 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
12863 
12864 	if (phba->cfg_multi_ring_support == 2) {
12865 		/*
12866 		 * Process all events on extra ring. Take the optimized path
12867 		 * for extra ring IO.
12868 		 */
12869 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
12870 		status >>= (4*LPFC_EXTRA_RING);
12871 		if (status & HA_RXMASK) {
12872 			lpfc_sli_handle_fast_ring_event(phba,
12873 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
12874 					status);
12875 		}
12876 	}
12877 	return IRQ_HANDLED;
12878 }  /* lpfc_sli_fp_intr_handler */
12879 
12880 /**
12881  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
12882  * @irq: Interrupt number.
12883  * @dev_id: The device context pointer.
12884  *
12885  * This function is the HBA device-level interrupt handler to device with
12886  * SLI-3 interface spec, called from the PCI layer when either MSI or
12887  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
12888  * requires driver attention. This function invokes the slow-path interrupt
12889  * attention handling function and fast-path interrupt attention handling
12890  * function in turn to process the relevant HBA attention events. This
12891  * function is called without any lock held. It gets the hbalock to access
12892  * and update SLI data structures.
12893  *
12894  * This function returns IRQ_HANDLED when interrupt is handled, else it
12895  * returns IRQ_NONE.
12896  **/
12897 irqreturn_t
12898 lpfc_sli_intr_handler(int irq, void *dev_id)
12899 {
12900 	struct lpfc_hba  *phba;
12901 	irqreturn_t sp_irq_rc, fp_irq_rc;
12902 	unsigned long status1, status2;
12903 	uint32_t hc_copy;
12904 
12905 	/*
12906 	 * Get the driver's phba structure from the dev_id and
12907 	 * assume the HBA is not interrupting.
12908 	 */
12909 	phba = (struct lpfc_hba *) dev_id;
12910 
12911 	if (unlikely(!phba))
12912 		return IRQ_NONE;
12913 
12914 	/* Check device state for handling interrupt */
12915 	if (lpfc_intr_state_check(phba))
12916 		return IRQ_NONE;
12917 
12918 	spin_lock(&phba->hbalock);
12919 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
12920 		spin_unlock(&phba->hbalock);
12921 		return IRQ_HANDLED;
12922 	}
12923 
12924 	if (unlikely(!phba->ha_copy)) {
12925 		spin_unlock(&phba->hbalock);
12926 		return IRQ_NONE;
12927 	} else if (phba->ha_copy & HA_ERATT) {
12928 		if (phba->hba_flag & HBA_ERATT_HANDLED)
12929 			/* ERATT polling has handled ERATT */
12930 			phba->ha_copy &= ~HA_ERATT;
12931 		else
12932 			/* Indicate interrupt handler handles ERATT */
12933 			phba->hba_flag |= HBA_ERATT_HANDLED;
12934 	}
12935 
12936 	/*
12937 	 * If there is deferred error attention, do not check for any interrupt.
12938 	 */
12939 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12940 		spin_unlock(&phba->hbalock);
12941 		return IRQ_NONE;
12942 	}
12943 
12944 	/* Clear attention sources except link and error attentions */
12945 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
12946 		spin_unlock(&phba->hbalock);
12947 		return IRQ_HANDLED;
12948 	}
12949 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
12950 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
12951 		phba->HCregaddr);
12952 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
12953 	writel(hc_copy, phba->HCregaddr);
12954 	readl(phba->HAregaddr); /* flush */
12955 	spin_unlock(&phba->hbalock);
12956 
12957 	/*
12958 	 * Invokes slow-path host attention interrupt handling as appropriate.
12959 	 */
12960 
12961 	/* status of events with mailbox and link attention */
12962 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
12963 
12964 	/* status of events with ELS ring */
12965 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
12966 	status2 >>= (4*LPFC_ELS_RING);
12967 
12968 	if (status1 || (status2 & HA_RXMASK))
12969 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
12970 	else
12971 		sp_irq_rc = IRQ_NONE;
12972 
12973 	/*
12974 	 * Invoke fast-path host attention interrupt handling as appropriate.
12975 	 */
12976 
12977 	/* status of events with FCP ring */
12978 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
12979 	status1 >>= (4*LPFC_FCP_RING);
12980 
12981 	/* status of events with extra ring */
12982 	if (phba->cfg_multi_ring_support == 2) {
12983 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
12984 		status2 >>= (4*LPFC_EXTRA_RING);
12985 	} else
12986 		status2 = 0;
12987 
12988 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
12989 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
12990 	else
12991 		fp_irq_rc = IRQ_NONE;
12992 
12993 	/* Return device-level interrupt handling status */
12994 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
12995 }  /* lpfc_sli_intr_handler */
12996 
12997 /**
12998  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
12999  * @phba: pointer to lpfc hba data structure.
13000  *
13001  * This routine is invoked by the worker thread to process all the pending
13002  * SLI4 els abort xri events.
13003  **/
13004 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
13005 {
13006 	struct lpfc_cq_event *cq_event;
13007 
13008 	/* First, declare the els xri abort event has been handled */
13009 	spin_lock_irq(&phba->hbalock);
13010 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
13011 	spin_unlock_irq(&phba->hbalock);
13012 	/* Now, handle all the els xri abort events */
13013 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
13014 		/* Get the first event from the head of the event queue */
13015 		spin_lock_irq(&phba->hbalock);
13016 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
13017 				 cq_event, struct lpfc_cq_event, list);
13018 		spin_unlock_irq(&phba->hbalock);
13019 		/* Notify aborted XRI for ELS work queue */
13020 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
13021 		/* Free the event processed back to the free pool */
13022 		lpfc_sli4_cq_event_release(phba, cq_event);
13023 	}
13024 }
13025 
13026 /**
13027  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
13028  * @phba: pointer to lpfc hba data structure
13029  * @pIocbIn: pointer to the rspiocbq
13030  * @pIocbOut: pointer to the cmdiocbq
13031  * @wcqe: pointer to the complete wcqe
13032  *
13033  * This routine transfers the fields of a command iocbq to a response iocbq
13034  * by copying all the IOCB fields from command iocbq and transferring the
13035  * completion status information from the complete wcqe.
13036  **/
13037 static void
13038 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
13039 			      struct lpfc_iocbq *pIocbIn,
13040 			      struct lpfc_iocbq *pIocbOut,
13041 			      struct lpfc_wcqe_complete *wcqe)
13042 {
13043 	int numBdes, i;
13044 	unsigned long iflags;
13045 	uint32_t status, max_response;
13046 	struct lpfc_dmabuf *dmabuf;
13047 	struct ulp_bde64 *bpl, bde;
13048 	size_t offset = offsetof(struct lpfc_iocbq, iocb);
13049 
13050 	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
13051 	       sizeof(struct lpfc_iocbq) - offset);
13052 	/* Map WCQE parameters into irspiocb parameters */
13053 	status = bf_get(lpfc_wcqe_c_status, wcqe);
13054 	pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
13055 	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
13056 		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
13057 			pIocbIn->iocb.un.fcpi.fcpi_parm =
13058 					pIocbOut->iocb.un.fcpi.fcpi_parm -
13059 					wcqe->total_data_placed;
13060 		else
13061 			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
13062 	else {
13063 		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
13064 		switch (pIocbOut->iocb.ulpCommand) {
13065 		case CMD_ELS_REQUEST64_CR:
13066 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
13067 			bpl  = (struct ulp_bde64 *)dmabuf->virt;
13068 			bde.tus.w = le32_to_cpu(bpl[1].tus.w);
13069 			max_response = bde.tus.f.bdeSize;
13070 			break;
13071 		case CMD_GEN_REQUEST64_CR:
13072 			max_response = 0;
13073 			if (!pIocbOut->context3)
13074 				break;
13075 			numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
13076 					sizeof(struct ulp_bde64);
13077 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
13078 			bpl = (struct ulp_bde64 *)dmabuf->virt;
13079 			for (i = 0; i < numBdes; i++) {
13080 				bde.tus.w = le32_to_cpu(bpl[i].tus.w);
13081 				if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
13082 					max_response += bde.tus.f.bdeSize;
13083 			}
13084 			break;
13085 		default:
13086 			max_response = wcqe->total_data_placed;
13087 			break;
13088 		}
13089 		if (max_response < wcqe->total_data_placed)
13090 			pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
13091 		else
13092 			pIocbIn->iocb.un.genreq64.bdl.bdeSize =
13093 				wcqe->total_data_placed;
13094 	}
13095 
13096 	/* Convert BG errors for completion status */
13097 	if (status == CQE_STATUS_DI_ERROR) {
13098 		pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
13099 
13100 		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
13101 			pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
13102 		else
13103 			pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
13104 
13105 		pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
13106 		if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
13107 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13108 				BGS_GUARD_ERR_MASK;
13109 		if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
13110 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13111 				BGS_APPTAG_ERR_MASK;
13112 		if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
13113 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13114 				BGS_REFTAG_ERR_MASK;
13115 
13116 		/* Check to see if there was any good data before the error */
13117 		if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
13118 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13119 				BGS_HI_WATER_MARK_PRESENT_MASK;
13120 			pIocbIn->iocb.unsli3.sli3_bg.bghm =
13121 				wcqe->total_data_placed;
13122 		}
13123 
13124 		/*
13125 		* Set ALL the error bits to indicate we don't know what
13126 		* type of error it is.
13127 		*/
13128 		if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
13129 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13130 				(BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
13131 				BGS_GUARD_ERR_MASK);
13132 	}
13133 
13134 	/* Pick up HBA exchange busy condition */
13135 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
13136 		spin_lock_irqsave(&phba->hbalock, iflags);
13137 		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
13138 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13139 	}
13140 }
13141 
13142 /**
13143  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
13144  * @phba: Pointer to HBA context object.
13145  * @wcqe: Pointer to work-queue completion queue entry.
13146  *
13147  * This routine handles an ELS work-queue completion event and construct
13148  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
13149  * discovery engine to handle.
13150  *
13151  * Return: Pointer to the receive IOCBQ, NULL otherwise.
13152  **/
13153 static struct lpfc_iocbq *
13154 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
13155 			       struct lpfc_iocbq *irspiocbq)
13156 {
13157 	struct lpfc_sli_ring *pring;
13158 	struct lpfc_iocbq *cmdiocbq;
13159 	struct lpfc_wcqe_complete *wcqe;
13160 	unsigned long iflags;
13161 
13162 	pring = lpfc_phba_elsring(phba);
13163 	if (unlikely(!pring))
13164 		return NULL;
13165 
13166 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
13167 	pring->stats.iocb_event++;
13168 	/* Look up the ELS command IOCB and create pseudo response IOCB */
13169 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
13170 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13171 	if (unlikely(!cmdiocbq)) {
13172 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13173 				"0386 ELS complete with no corresponding "
13174 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
13175 				wcqe->word0, wcqe->total_data_placed,
13176 				wcqe->parameter, wcqe->word3);
13177 		lpfc_sli_release_iocbq(phba, irspiocbq);
13178 		return NULL;
13179 	}
13180 
13181 	spin_lock_irqsave(&pring->ring_lock, iflags);
13182 	/* Put the iocb back on the txcmplq */
13183 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
13184 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
13185 
13186 	/* Fake the irspiocbq and copy necessary response information */
13187 	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
13188 
13189 	return irspiocbq;
13190 }
13191 
13192 inline struct lpfc_cq_event *
13193 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
13194 {
13195 	struct lpfc_cq_event *cq_event;
13196 
13197 	/* Allocate a new internal CQ_EVENT entry */
13198 	cq_event = lpfc_sli4_cq_event_alloc(phba);
13199 	if (!cq_event) {
13200 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13201 				"0602 Failed to alloc CQ_EVENT entry\n");
13202 		return NULL;
13203 	}
13204 
13205 	/* Move the CQE into the event */
13206 	memcpy(&cq_event->cqe, entry, size);
13207 	return cq_event;
13208 }
13209 
13210 /**
13211  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
13212  * @phba: Pointer to HBA context object.
13213  * @cqe: Pointer to mailbox completion queue entry.
13214  *
13215  * This routine process a mailbox completion queue entry with asynchronous
13216  * event.
13217  *
13218  * Return: true if work posted to worker thread, otherwise false.
13219  **/
13220 static bool
13221 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13222 {
13223 	struct lpfc_cq_event *cq_event;
13224 	unsigned long iflags;
13225 
13226 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13227 			"0392 Async Event: word0:x%x, word1:x%x, "
13228 			"word2:x%x, word3:x%x\n", mcqe->word0,
13229 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
13230 
13231 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
13232 	if (!cq_event)
13233 		return false;
13234 	spin_lock_irqsave(&phba->hbalock, iflags);
13235 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
13236 	/* Set the async event flag */
13237 	phba->hba_flag |= ASYNC_EVENT;
13238 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13239 
13240 	return true;
13241 }
13242 
13243 /**
13244  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
13245  * @phba: Pointer to HBA context object.
13246  * @cqe: Pointer to mailbox completion queue entry.
13247  *
13248  * This routine process a mailbox completion queue entry with mailbox
13249  * completion event.
13250  *
13251  * Return: true if work posted to worker thread, otherwise false.
13252  **/
13253 static bool
13254 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13255 {
13256 	uint32_t mcqe_status;
13257 	MAILBOX_t *mbox, *pmbox;
13258 	struct lpfc_mqe *mqe;
13259 	struct lpfc_vport *vport;
13260 	struct lpfc_nodelist *ndlp;
13261 	struct lpfc_dmabuf *mp;
13262 	unsigned long iflags;
13263 	LPFC_MBOXQ_t *pmb;
13264 	bool workposted = false;
13265 	int rc;
13266 
13267 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
13268 	if (!bf_get(lpfc_trailer_completed, mcqe))
13269 		goto out_no_mqe_complete;
13270 
13271 	/* Get the reference to the active mbox command */
13272 	spin_lock_irqsave(&phba->hbalock, iflags);
13273 	pmb = phba->sli.mbox_active;
13274 	if (unlikely(!pmb)) {
13275 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
13276 				"1832 No pending MBOX command to handle\n");
13277 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13278 		goto out_no_mqe_complete;
13279 	}
13280 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13281 	mqe = &pmb->u.mqe;
13282 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
13283 	mbox = phba->mbox;
13284 	vport = pmb->vport;
13285 
13286 	/* Reset heartbeat timer */
13287 	phba->last_completion_time = jiffies;
13288 	del_timer(&phba->sli.mbox_tmo);
13289 
13290 	/* Move mbox data to caller's mailbox region, do endian swapping */
13291 	if (pmb->mbox_cmpl && mbox)
13292 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
13293 
13294 	/*
13295 	 * For mcqe errors, conditionally move a modified error code to
13296 	 * the mbox so that the error will not be missed.
13297 	 */
13298 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
13299 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
13300 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
13301 			bf_set(lpfc_mqe_status, mqe,
13302 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
13303 	}
13304 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13305 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13306 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
13307 				      "MBOX dflt rpi: status:x%x rpi:x%x",
13308 				      mcqe_status,
13309 				      pmbox->un.varWords[0], 0);
13310 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
13311 			mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
13312 			ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
13313 			/* Reg_LOGIN of dflt RPI was successful. Now lets get
13314 			 * RID of the PPI using the same mbox buffer.
13315 			 */
13316 			lpfc_unreg_login(phba, vport->vpi,
13317 					 pmbox->un.varWords[0], pmb);
13318 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
13319 			pmb->ctx_buf = mp;
13320 			pmb->ctx_ndlp = ndlp;
13321 			pmb->vport = vport;
13322 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
13323 			if (rc != MBX_BUSY)
13324 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
13325 						LOG_SLI, "0385 rc should "
13326 						"have been MBX_BUSY\n");
13327 			if (rc != MBX_NOT_FINISHED)
13328 				goto send_current_mbox;
13329 		}
13330 	}
13331 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
13332 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
13333 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
13334 
13335 	/* There is mailbox completion work to do */
13336 	spin_lock_irqsave(&phba->hbalock, iflags);
13337 	__lpfc_mbox_cmpl_put(phba, pmb);
13338 	phba->work_ha |= HA_MBATT;
13339 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13340 	workposted = true;
13341 
13342 send_current_mbox:
13343 	spin_lock_irqsave(&phba->hbalock, iflags);
13344 	/* Release the mailbox command posting token */
13345 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13346 	/* Setting active mailbox pointer need to be in sync to flag clear */
13347 	phba->sli.mbox_active = NULL;
13348 	if (bf_get(lpfc_trailer_consumed, mcqe))
13349 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13350 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13351 	/* Wake up worker thread to post the next pending mailbox command */
13352 	lpfc_worker_wake_up(phba);
13353 	return workposted;
13354 
13355 out_no_mqe_complete:
13356 	spin_lock_irqsave(&phba->hbalock, iflags);
13357 	if (bf_get(lpfc_trailer_consumed, mcqe))
13358 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13359 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13360 	return false;
13361 }
13362 
13363 /**
13364  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
13365  * @phba: Pointer to HBA context object.
13366  * @cqe: Pointer to mailbox completion queue entry.
13367  *
13368  * This routine process a mailbox completion queue entry, it invokes the
13369  * proper mailbox complete handling or asynchronous event handling routine
13370  * according to the MCQE's async bit.
13371  *
13372  * Return: true if work posted to worker thread, otherwise false.
13373  **/
13374 static bool
13375 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13376 			 struct lpfc_cqe *cqe)
13377 {
13378 	struct lpfc_mcqe mcqe;
13379 	bool workposted;
13380 
13381 	cq->CQ_mbox++;
13382 
13383 	/* Copy the mailbox MCQE and convert endian order as needed */
13384 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
13385 
13386 	/* Invoke the proper event handling routine */
13387 	if (!bf_get(lpfc_trailer_async, &mcqe))
13388 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
13389 	else
13390 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
13391 	return workposted;
13392 }
13393 
13394 /**
13395  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
13396  * @phba: Pointer to HBA context object.
13397  * @cq: Pointer to associated CQ
13398  * @wcqe: Pointer to work-queue completion queue entry.
13399  *
13400  * This routine handles an ELS work-queue completion event.
13401  *
13402  * Return: true if work posted to worker thread, otherwise false.
13403  **/
13404 static bool
13405 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13406 			     struct lpfc_wcqe_complete *wcqe)
13407 {
13408 	struct lpfc_iocbq *irspiocbq;
13409 	unsigned long iflags;
13410 	struct lpfc_sli_ring *pring = cq->pring;
13411 	int txq_cnt = 0;
13412 	int txcmplq_cnt = 0;
13413 
13414 	/* Check for response status */
13415 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
13416 		/* Log the error status */
13417 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13418 				"0357 ELS CQE error: status=x%x: "
13419 				"CQE: %08x %08x %08x %08x\n",
13420 				bf_get(lpfc_wcqe_c_status, wcqe),
13421 				wcqe->word0, wcqe->total_data_placed,
13422 				wcqe->parameter, wcqe->word3);
13423 	}
13424 
13425 	/* Get an irspiocbq for later ELS response processing use */
13426 	irspiocbq = lpfc_sli_get_iocbq(phba);
13427 	if (!irspiocbq) {
13428 		if (!list_empty(&pring->txq))
13429 			txq_cnt++;
13430 		if (!list_empty(&pring->txcmplq))
13431 			txcmplq_cnt++;
13432 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13433 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
13434 			"els_txcmplq_cnt=%d\n",
13435 			txq_cnt, phba->iocb_cnt,
13436 			txcmplq_cnt);
13437 		return false;
13438 	}
13439 
13440 	/* Save off the slow-path queue event for work thread to process */
13441 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
13442 	spin_lock_irqsave(&phba->hbalock, iflags);
13443 	list_add_tail(&irspiocbq->cq_event.list,
13444 		      &phba->sli4_hba.sp_queue_event);
13445 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
13446 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13447 
13448 	return true;
13449 }
13450 
13451 /**
13452  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
13453  * @phba: Pointer to HBA context object.
13454  * @wcqe: Pointer to work-queue completion queue entry.
13455  *
13456  * This routine handles slow-path WQ entry consumed event by invoking the
13457  * proper WQ release routine to the slow-path WQ.
13458  **/
13459 static void
13460 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
13461 			     struct lpfc_wcqe_release *wcqe)
13462 {
13463 	/* sanity check on queue memory */
13464 	if (unlikely(!phba->sli4_hba.els_wq))
13465 		return;
13466 	/* Check for the slow-path ELS work queue */
13467 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
13468 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
13469 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
13470 	else
13471 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13472 				"2579 Slow-path wqe consume event carries "
13473 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
13474 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
13475 				phba->sli4_hba.els_wq->queue_id);
13476 }
13477 
13478 /**
13479  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
13480  * @phba: Pointer to HBA context object.
13481  * @cq: Pointer to a WQ completion queue.
13482  * @wcqe: Pointer to work-queue completion queue entry.
13483  *
13484  * This routine handles an XRI abort event.
13485  *
13486  * Return: true if work posted to worker thread, otherwise false.
13487  **/
13488 static bool
13489 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
13490 				   struct lpfc_queue *cq,
13491 				   struct sli4_wcqe_xri_aborted *wcqe)
13492 {
13493 	bool workposted = false;
13494 	struct lpfc_cq_event *cq_event;
13495 	unsigned long iflags;
13496 
13497 	switch (cq->subtype) {
13498 	case LPFC_IO:
13499 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
13500 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13501 			/* Notify aborted XRI for NVME work queue */
13502 			if (phba->nvmet_support)
13503 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
13504 		}
13505 		workposted = false;
13506 		break;
13507 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
13508 	case LPFC_ELS:
13509 		cq_event = lpfc_cq_event_setup(
13510 			phba, wcqe, sizeof(struct sli4_wcqe_xri_aborted));
13511 		if (!cq_event)
13512 			return false;
13513 		cq_event->hdwq = cq->hdwq;
13514 		spin_lock_irqsave(&phba->hbalock, iflags);
13515 		list_add_tail(&cq_event->list,
13516 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
13517 		/* Set the els xri abort event flag */
13518 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
13519 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13520 		workposted = true;
13521 		break;
13522 	default:
13523 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13524 				"0603 Invalid CQ subtype %d: "
13525 				"%08x %08x %08x %08x\n",
13526 				cq->subtype, wcqe->word0, wcqe->parameter,
13527 				wcqe->word2, wcqe->word3);
13528 		workposted = false;
13529 		break;
13530 	}
13531 	return workposted;
13532 }
13533 
13534 #define FC_RCTL_MDS_DIAGS	0xF4
13535 
13536 /**
13537  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
13538  * @phba: Pointer to HBA context object.
13539  * @rcqe: Pointer to receive-queue completion queue entry.
13540  *
13541  * This routine process a receive-queue completion queue entry.
13542  *
13543  * Return: true if work posted to worker thread, otherwise false.
13544  **/
13545 static bool
13546 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
13547 {
13548 	bool workposted = false;
13549 	struct fc_frame_header *fc_hdr;
13550 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
13551 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
13552 	struct lpfc_nvmet_tgtport *tgtp;
13553 	struct hbq_dmabuf *dma_buf;
13554 	uint32_t status, rq_id;
13555 	unsigned long iflags;
13556 
13557 	/* sanity check on queue memory */
13558 	if (unlikely(!hrq) || unlikely(!drq))
13559 		return workposted;
13560 
13561 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
13562 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
13563 	else
13564 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
13565 	if (rq_id != hrq->queue_id)
13566 		goto out;
13567 
13568 	status = bf_get(lpfc_rcqe_status, rcqe);
13569 	switch (status) {
13570 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
13571 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13572 				"2537 Receive Frame Truncated!!\n");
13573 		/* fall through */
13574 	case FC_STATUS_RQ_SUCCESS:
13575 		spin_lock_irqsave(&phba->hbalock, iflags);
13576 		lpfc_sli4_rq_release(hrq, drq);
13577 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
13578 		if (!dma_buf) {
13579 			hrq->RQ_no_buf_found++;
13580 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13581 			goto out;
13582 		}
13583 		hrq->RQ_rcv_buf++;
13584 		hrq->RQ_buf_posted--;
13585 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
13586 
13587 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
13588 
13589 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
13590 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
13591 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13592 			/* Handle MDS Loopback frames */
13593 			lpfc_sli4_handle_mds_loopback(phba->pport, dma_buf);
13594 			break;
13595 		}
13596 
13597 		/* save off the frame for the work thread to process */
13598 		list_add_tail(&dma_buf->cq_event.list,
13599 			      &phba->sli4_hba.sp_queue_event);
13600 		/* Frame received */
13601 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
13602 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13603 		workposted = true;
13604 		break;
13605 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
13606 		if (phba->nvmet_support) {
13607 			tgtp = phba->targetport->private;
13608 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_NVME,
13609 					"6402 RQE Error x%x, posted %d err_cnt "
13610 					"%d: %x %x %x\n",
13611 					status, hrq->RQ_buf_posted,
13612 					hrq->RQ_no_posted_buf,
13613 					atomic_read(&tgtp->rcv_fcp_cmd_in),
13614 					atomic_read(&tgtp->rcv_fcp_cmd_out),
13615 					atomic_read(&tgtp->xmt_fcp_release));
13616 		}
13617 		/* fallthrough */
13618 
13619 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
13620 		hrq->RQ_no_posted_buf++;
13621 		/* Post more buffers if possible */
13622 		spin_lock_irqsave(&phba->hbalock, iflags);
13623 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
13624 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13625 		workposted = true;
13626 		break;
13627 	}
13628 out:
13629 	return workposted;
13630 }
13631 
13632 /**
13633  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
13634  * @phba: Pointer to HBA context object.
13635  * @cq: Pointer to the completion queue.
13636  * @cqe: Pointer to a completion queue entry.
13637  *
13638  * This routine process a slow-path work-queue or receive queue completion queue
13639  * entry.
13640  *
13641  * Return: true if work posted to worker thread, otherwise false.
13642  **/
13643 static bool
13644 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13645 			 struct lpfc_cqe *cqe)
13646 {
13647 	struct lpfc_cqe cqevt;
13648 	bool workposted = false;
13649 
13650 	/* Copy the work queue CQE and convert endian order if needed */
13651 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
13652 
13653 	/* Check and process for different type of WCQE and dispatch */
13654 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
13655 	case CQE_CODE_COMPL_WQE:
13656 		/* Process the WQ/RQ complete event */
13657 		phba->last_completion_time = jiffies;
13658 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
13659 				(struct lpfc_wcqe_complete *)&cqevt);
13660 		break;
13661 	case CQE_CODE_RELEASE_WQE:
13662 		/* Process the WQ release event */
13663 		lpfc_sli4_sp_handle_rel_wcqe(phba,
13664 				(struct lpfc_wcqe_release *)&cqevt);
13665 		break;
13666 	case CQE_CODE_XRI_ABORTED:
13667 		/* Process the WQ XRI abort event */
13668 		phba->last_completion_time = jiffies;
13669 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
13670 				(struct sli4_wcqe_xri_aborted *)&cqevt);
13671 		break;
13672 	case CQE_CODE_RECEIVE:
13673 	case CQE_CODE_RECEIVE_V1:
13674 		/* Process the RQ event */
13675 		phba->last_completion_time = jiffies;
13676 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
13677 				(struct lpfc_rcqe *)&cqevt);
13678 		break;
13679 	default:
13680 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13681 				"0388 Not a valid WCQE code: x%x\n",
13682 				bf_get(lpfc_cqe_code, &cqevt));
13683 		break;
13684 	}
13685 	return workposted;
13686 }
13687 
13688 /**
13689  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
13690  * @phba: Pointer to HBA context object.
13691  * @eqe: Pointer to fast-path event queue entry.
13692  *
13693  * This routine process a event queue entry from the slow-path event queue.
13694  * It will check the MajorCode and MinorCode to determine this is for a
13695  * completion event on a completion queue, if not, an error shall be logged
13696  * and just return. Otherwise, it will get to the corresponding completion
13697  * queue and process all the entries on that completion queue, rearm the
13698  * completion queue, and then return.
13699  *
13700  **/
13701 static void
13702 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
13703 	struct lpfc_queue *speq)
13704 {
13705 	struct lpfc_queue *cq = NULL, *childq;
13706 	uint16_t cqid;
13707 
13708 	/* Get the reference to the corresponding CQ */
13709 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
13710 
13711 	list_for_each_entry(childq, &speq->child_list, list) {
13712 		if (childq->queue_id == cqid) {
13713 			cq = childq;
13714 			break;
13715 		}
13716 	}
13717 	if (unlikely(!cq)) {
13718 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
13719 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13720 					"0365 Slow-path CQ identifier "
13721 					"(%d) does not exist\n", cqid);
13722 		return;
13723 	}
13724 
13725 	/* Save EQ associated with this CQ */
13726 	cq->assoc_qp = speq;
13727 
13728 	if (!queue_work_on(cq->chann, phba->wq, &cq->spwork))
13729 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13730 				"0390 Cannot schedule soft IRQ "
13731 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
13732 				cqid, cq->queue_id, raw_smp_processor_id());
13733 }
13734 
13735 /**
13736  * __lpfc_sli4_process_cq - Process elements of a CQ
13737  * @phba: Pointer to HBA context object.
13738  * @cq: Pointer to CQ to be processed
13739  * @handler: Routine to process each cqe
13740  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
13741  *
13742  * This routine processes completion queue entries in a CQ. While a valid
13743  * queue element is found, the handler is called. During processing checks
13744  * are made for periodic doorbell writes to let the hardware know of
13745  * element consumption.
13746  *
13747  * If the max limit on cqes to process is hit, or there are no more valid
13748  * entries, the loop stops. If we processed a sufficient number of elements,
13749  * meaning there is sufficient load, rather than rearming and generating
13750  * another interrupt, a cq rescheduling delay will be set. A delay of 0
13751  * indicates no rescheduling.
13752  *
13753  * Returns True if work scheduled, False otherwise.
13754  **/
13755 static bool
13756 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
13757 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
13758 			struct lpfc_cqe *), unsigned long *delay)
13759 {
13760 	struct lpfc_cqe *cqe;
13761 	bool workposted = false;
13762 	int count = 0, consumed = 0;
13763 	bool arm = true;
13764 
13765 	/* default - no reschedule */
13766 	*delay = 0;
13767 
13768 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
13769 		goto rearm_and_exit;
13770 
13771 	/* Process all the entries to the CQ */
13772 	cq->q_flag = 0;
13773 	cqe = lpfc_sli4_cq_get(cq);
13774 	while (cqe) {
13775 		workposted |= handler(phba, cq, cqe);
13776 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
13777 
13778 		consumed++;
13779 		if (!(++count % cq->max_proc_limit))
13780 			break;
13781 
13782 		if (!(count % cq->notify_interval)) {
13783 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
13784 						LPFC_QUEUE_NOARM);
13785 			consumed = 0;
13786 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
13787 		}
13788 
13789 		if (count == LPFC_NVMET_CQ_NOTIFY)
13790 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
13791 
13792 		cqe = lpfc_sli4_cq_get(cq);
13793 	}
13794 	if (count >= phba->cfg_cq_poll_threshold) {
13795 		*delay = 1;
13796 		arm = false;
13797 	}
13798 
13799 	/* Track the max number of CQEs processed in 1 EQ */
13800 	if (count > cq->CQ_max_cqe)
13801 		cq->CQ_max_cqe = count;
13802 
13803 	cq->assoc_qp->EQ_cqe_cnt += count;
13804 
13805 	/* Catch the no cq entry condition */
13806 	if (unlikely(count == 0))
13807 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13808 				"0369 No entry from completion queue "
13809 				"qid=%d\n", cq->queue_id);
13810 
13811 	cq->queue_claimed = 0;
13812 
13813 rearm_and_exit:
13814 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
13815 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
13816 
13817 	return workposted;
13818 }
13819 
13820 /**
13821  * lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
13822  * @cq: pointer to CQ to process
13823  *
13824  * This routine calls the cq processing routine with a handler specific
13825  * to the type of queue bound to it.
13826  *
13827  * The CQ routine returns two values: the first is the calling status,
13828  * which indicates whether work was queued to the  background discovery
13829  * thread. If true, the routine should wakeup the discovery thread;
13830  * the second is the delay parameter. If non-zero, rather than rearming
13831  * the CQ and yet another interrupt, the CQ handler should be queued so
13832  * that it is processed in a subsequent polling action. The value of
13833  * the delay indicates when to reschedule it.
13834  **/
13835 static void
13836 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
13837 {
13838 	struct lpfc_hba *phba = cq->phba;
13839 	unsigned long delay;
13840 	bool workposted = false;
13841 
13842 	/* Process and rearm the CQ */
13843 	switch (cq->type) {
13844 	case LPFC_MCQ:
13845 		workposted |= __lpfc_sli4_process_cq(phba, cq,
13846 						lpfc_sli4_sp_handle_mcqe,
13847 						&delay);
13848 		break;
13849 	case LPFC_WCQ:
13850 		if (cq->subtype == LPFC_IO)
13851 			workposted |= __lpfc_sli4_process_cq(phba, cq,
13852 						lpfc_sli4_fp_handle_cqe,
13853 						&delay);
13854 		else
13855 			workposted |= __lpfc_sli4_process_cq(phba, cq,
13856 						lpfc_sli4_sp_handle_cqe,
13857 						&delay);
13858 		break;
13859 	default:
13860 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13861 				"0370 Invalid completion queue type (%d)\n",
13862 				cq->type);
13863 		return;
13864 	}
13865 
13866 	if (delay) {
13867 		if (!queue_delayed_work_on(cq->chann, phba->wq,
13868 					   &cq->sched_spwork, delay))
13869 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13870 				"0394 Cannot schedule soft IRQ "
13871 				"for cqid=%d on CPU %d\n",
13872 				cq->queue_id, cq->chann);
13873 	}
13874 
13875 	/* wake up worker thread if there are works to be done */
13876 	if (workposted)
13877 		lpfc_worker_wake_up(phba);
13878 }
13879 
13880 /**
13881  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
13882  *   interrupt
13883  * @work: pointer to work element
13884  *
13885  * translates from the work handler and calls the slow-path handler.
13886  **/
13887 static void
13888 lpfc_sli4_sp_process_cq(struct work_struct *work)
13889 {
13890 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
13891 
13892 	__lpfc_sli4_sp_process_cq(cq);
13893 }
13894 
13895 /**
13896  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
13897  * @work: pointer to work element
13898  *
13899  * translates from the work handler and calls the slow-path handler.
13900  **/
13901 static void
13902 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
13903 {
13904 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
13905 					struct lpfc_queue, sched_spwork);
13906 
13907 	__lpfc_sli4_sp_process_cq(cq);
13908 }
13909 
13910 /**
13911  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
13912  * @phba: Pointer to HBA context object.
13913  * @cq: Pointer to associated CQ
13914  * @wcqe: Pointer to work-queue completion queue entry.
13915  *
13916  * This routine process a fast-path work queue completion entry from fast-path
13917  * event queue for FCP command response completion.
13918  **/
13919 static void
13920 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13921 			     struct lpfc_wcqe_complete *wcqe)
13922 {
13923 	struct lpfc_sli_ring *pring = cq->pring;
13924 	struct lpfc_iocbq *cmdiocbq;
13925 	struct lpfc_iocbq irspiocbq;
13926 	unsigned long iflags;
13927 
13928 	/* Check for response status */
13929 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
13930 		/* If resource errors reported from HBA, reduce queue
13931 		 * depth of the SCSI device.
13932 		 */
13933 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
13934 		     IOSTAT_LOCAL_REJECT)) &&
13935 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
13936 		     IOERR_NO_RESOURCES))
13937 			phba->lpfc_rampdown_queue_depth(phba);
13938 
13939 		/* Log the error status */
13940 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13941 				"0373 FCP CQE error: status=x%x: "
13942 				"CQE: %08x %08x %08x %08x\n",
13943 				bf_get(lpfc_wcqe_c_status, wcqe),
13944 				wcqe->word0, wcqe->total_data_placed,
13945 				wcqe->parameter, wcqe->word3);
13946 	}
13947 
13948 	/* Look up the FCP command IOCB and create pseudo response IOCB */
13949 	spin_lock_irqsave(&pring->ring_lock, iflags);
13950 	pring->stats.iocb_event++;
13951 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
13952 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
13953 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13954 	if (unlikely(!cmdiocbq)) {
13955 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13956 				"0374 FCP complete with no corresponding "
13957 				"cmdiocb: iotag (%d)\n",
13958 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13959 		return;
13960 	}
13961 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
13962 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
13963 #endif
13964 	if (cmdiocbq->iocb_cmpl == NULL) {
13965 		if (cmdiocbq->wqe_cmpl) {
13966 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
13967 				spin_lock_irqsave(&phba->hbalock, iflags);
13968 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
13969 				spin_unlock_irqrestore(&phba->hbalock, iflags);
13970 			}
13971 
13972 			/* Pass the cmd_iocb and the wcqe to the upper layer */
13973 			(cmdiocbq->wqe_cmpl)(phba, cmdiocbq, wcqe);
13974 			return;
13975 		}
13976 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13977 				"0375 FCP cmdiocb not callback function "
13978 				"iotag: (%d)\n",
13979 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13980 		return;
13981 	}
13982 
13983 	/* Fake the irspiocb and copy necessary response information */
13984 	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
13985 
13986 	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
13987 		spin_lock_irqsave(&phba->hbalock, iflags);
13988 		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
13989 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13990 	}
13991 
13992 	/* Pass the cmd_iocb and the rsp state to the upper layer */
13993 	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
13994 }
13995 
13996 /**
13997  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
13998  * @phba: Pointer to HBA context object.
13999  * @cq: Pointer to completion queue.
14000  * @wcqe: Pointer to work-queue completion queue entry.
14001  *
14002  * This routine handles an fast-path WQ entry consumed event by invoking the
14003  * proper WQ release routine to the slow-path WQ.
14004  **/
14005 static void
14006 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14007 			     struct lpfc_wcqe_release *wcqe)
14008 {
14009 	struct lpfc_queue *childwq;
14010 	bool wqid_matched = false;
14011 	uint16_t hba_wqid;
14012 
14013 	/* Check for fast-path FCP work queue release */
14014 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
14015 	list_for_each_entry(childwq, &cq->child_list, list) {
14016 		if (childwq->queue_id == hba_wqid) {
14017 			lpfc_sli4_wq_release(childwq,
14018 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14019 			if (childwq->q_flag & HBA_NVMET_WQFULL)
14020 				lpfc_nvmet_wqfull_process(phba, childwq);
14021 			wqid_matched = true;
14022 			break;
14023 		}
14024 	}
14025 	/* Report warning log message if no match found */
14026 	if (wqid_matched != true)
14027 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14028 				"2580 Fast-path wqe consume event carries "
14029 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
14030 }
14031 
14032 /**
14033  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
14034  * @phba: Pointer to HBA context object.
14035  * @rcqe: Pointer to receive-queue completion queue entry.
14036  *
14037  * This routine process a receive-queue completion queue entry.
14038  *
14039  * Return: true if work posted to worker thread, otherwise false.
14040  **/
14041 static bool
14042 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14043 			    struct lpfc_rcqe *rcqe)
14044 {
14045 	bool workposted = false;
14046 	struct lpfc_queue *hrq;
14047 	struct lpfc_queue *drq;
14048 	struct rqb_dmabuf *dma_buf;
14049 	struct fc_frame_header *fc_hdr;
14050 	struct lpfc_nvmet_tgtport *tgtp;
14051 	uint32_t status, rq_id;
14052 	unsigned long iflags;
14053 	uint32_t fctl, idx;
14054 
14055 	if ((phba->nvmet_support == 0) ||
14056 	    (phba->sli4_hba.nvmet_cqset == NULL))
14057 		return workposted;
14058 
14059 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
14060 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
14061 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
14062 
14063 	/* sanity check on queue memory */
14064 	if (unlikely(!hrq) || unlikely(!drq))
14065 		return workposted;
14066 
14067 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14068 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14069 	else
14070 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14071 
14072 	if ((phba->nvmet_support == 0) ||
14073 	    (rq_id != hrq->queue_id))
14074 		return workposted;
14075 
14076 	status = bf_get(lpfc_rcqe_status, rcqe);
14077 	switch (status) {
14078 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14079 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14080 				"6126 Receive Frame Truncated!!\n");
14081 		/* fall through */
14082 	case FC_STATUS_RQ_SUCCESS:
14083 		spin_lock_irqsave(&phba->hbalock, iflags);
14084 		lpfc_sli4_rq_release(hrq, drq);
14085 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
14086 		if (!dma_buf) {
14087 			hrq->RQ_no_buf_found++;
14088 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14089 			goto out;
14090 		}
14091 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14092 		hrq->RQ_rcv_buf++;
14093 		hrq->RQ_buf_posted--;
14094 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14095 
14096 		/* Just some basic sanity checks on FCP Command frame */
14097 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
14098 			fc_hdr->fh_f_ctl[1] << 8 |
14099 			fc_hdr->fh_f_ctl[2]);
14100 		if (((fctl &
14101 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
14102 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
14103 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
14104 			goto drop;
14105 
14106 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
14107 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
14108 			lpfc_nvmet_unsol_fcp_event(
14109 				phba, idx, dma_buf, cq->isr_timestamp,
14110 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
14111 			return false;
14112 		}
14113 drop:
14114 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
14115 		break;
14116 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14117 		if (phba->nvmet_support) {
14118 			tgtp = phba->targetport->private;
14119 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_NVME,
14120 					"6401 RQE Error x%x, posted %d err_cnt "
14121 					"%d: %x %x %x\n",
14122 					status, hrq->RQ_buf_posted,
14123 					hrq->RQ_no_posted_buf,
14124 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14125 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14126 					atomic_read(&tgtp->xmt_fcp_release));
14127 		}
14128 		/* fallthrough */
14129 
14130 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14131 		hrq->RQ_no_posted_buf++;
14132 		/* Post more buffers if possible */
14133 		break;
14134 	}
14135 out:
14136 	return workposted;
14137 }
14138 
14139 /**
14140  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
14141  * @phba: adapter with cq
14142  * @cq: Pointer to the completion queue.
14143  * @eqe: Pointer to fast-path completion queue entry.
14144  *
14145  * This routine process a fast-path work queue completion entry from fast-path
14146  * event queue for FCP command response completion.
14147  *
14148  * Return: true if work posted to worker thread, otherwise false.
14149  **/
14150 static bool
14151 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14152 			 struct lpfc_cqe *cqe)
14153 {
14154 	struct lpfc_wcqe_release wcqe;
14155 	bool workposted = false;
14156 
14157 	/* Copy the work queue CQE and convert endian order if needed */
14158 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
14159 
14160 	/* Check and process for different type of WCQE and dispatch */
14161 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
14162 	case CQE_CODE_COMPL_WQE:
14163 	case CQE_CODE_NVME_ERSP:
14164 		cq->CQ_wq++;
14165 		/* Process the WQ complete event */
14166 		phba->last_completion_time = jiffies;
14167 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
14168 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
14169 				(struct lpfc_wcqe_complete *)&wcqe);
14170 		break;
14171 	case CQE_CODE_RELEASE_WQE:
14172 		cq->CQ_release_wqe++;
14173 		/* Process the WQ release event */
14174 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
14175 				(struct lpfc_wcqe_release *)&wcqe);
14176 		break;
14177 	case CQE_CODE_XRI_ABORTED:
14178 		cq->CQ_xri_aborted++;
14179 		/* Process the WQ XRI abort event */
14180 		phba->last_completion_time = jiffies;
14181 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14182 				(struct sli4_wcqe_xri_aborted *)&wcqe);
14183 		break;
14184 	case CQE_CODE_RECEIVE_V1:
14185 	case CQE_CODE_RECEIVE:
14186 		phba->last_completion_time = jiffies;
14187 		if (cq->subtype == LPFC_NVMET) {
14188 			workposted = lpfc_sli4_nvmet_handle_rcqe(
14189 				phba, cq, (struct lpfc_rcqe *)&wcqe);
14190 		}
14191 		break;
14192 	default:
14193 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14194 				"0144 Not a valid CQE code: x%x\n",
14195 				bf_get(lpfc_wcqe_c_code, &wcqe));
14196 		break;
14197 	}
14198 	return workposted;
14199 }
14200 
14201 /**
14202  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
14203  * @phba: Pointer to HBA context object.
14204  * @eqe: Pointer to fast-path event queue entry.
14205  *
14206  * This routine process a event queue entry from the fast-path event queue.
14207  * It will check the MajorCode and MinorCode to determine this is for a
14208  * completion event on a completion queue, if not, an error shall be logged
14209  * and just return. Otherwise, it will get to the corresponding completion
14210  * queue and process all the entries on the completion queue, rearm the
14211  * completion queue, and then return.
14212  **/
14213 static void
14214 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
14215 			 struct lpfc_eqe *eqe)
14216 {
14217 	struct lpfc_queue *cq = NULL;
14218 	uint32_t qidx = eq->hdwq;
14219 	uint16_t cqid, id;
14220 
14221 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
14222 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14223 				"0366 Not a valid completion "
14224 				"event: majorcode=x%x, minorcode=x%x\n",
14225 				bf_get_le32(lpfc_eqe_major_code, eqe),
14226 				bf_get_le32(lpfc_eqe_minor_code, eqe));
14227 		return;
14228 	}
14229 
14230 	/* Get the reference to the corresponding CQ */
14231 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14232 
14233 	/* Use the fast lookup method first */
14234 	if (cqid <= phba->sli4_hba.cq_max) {
14235 		cq = phba->sli4_hba.cq_lookup[cqid];
14236 		if (cq)
14237 			goto  work_cq;
14238 	}
14239 
14240 	/* Next check for NVMET completion */
14241 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
14242 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
14243 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
14244 			/* Process NVMET unsol rcv */
14245 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
14246 			goto  process_cq;
14247 		}
14248 	}
14249 
14250 	if (phba->sli4_hba.nvmels_cq &&
14251 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
14252 		/* Process NVME unsol rcv */
14253 		cq = phba->sli4_hba.nvmels_cq;
14254 	}
14255 
14256 	/* Otherwise this is a Slow path event */
14257 	if (cq == NULL) {
14258 		lpfc_sli4_sp_handle_eqe(phba, eqe,
14259 					phba->sli4_hba.hdwq[qidx].hba_eq);
14260 		return;
14261 	}
14262 
14263 process_cq:
14264 	if (unlikely(cqid != cq->queue_id)) {
14265 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14266 				"0368 Miss-matched fast-path completion "
14267 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
14268 				cqid, cq->queue_id);
14269 		return;
14270 	}
14271 
14272 work_cq:
14273 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
14274 	if (phba->ktime_on)
14275 		cq->isr_timestamp = ktime_get_ns();
14276 	else
14277 		cq->isr_timestamp = 0;
14278 #endif
14279 	if (!queue_work_on(cq->chann, phba->wq, &cq->irqwork))
14280 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14281 				"0363 Cannot schedule soft IRQ "
14282 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14283 				cqid, cq->queue_id, raw_smp_processor_id());
14284 }
14285 
14286 /**
14287  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
14288  * @cq: Pointer to CQ to be processed
14289  *
14290  * This routine calls the cq processing routine with the handler for
14291  * fast path CQEs.
14292  *
14293  * The CQ routine returns two values: the first is the calling status,
14294  * which indicates whether work was queued to the  background discovery
14295  * thread. If true, the routine should wakeup the discovery thread;
14296  * the second is the delay parameter. If non-zero, rather than rearming
14297  * the CQ and yet another interrupt, the CQ handler should be queued so
14298  * that it is processed in a subsequent polling action. The value of
14299  * the delay indicates when to reschedule it.
14300  **/
14301 static void
14302 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq)
14303 {
14304 	struct lpfc_hba *phba = cq->phba;
14305 	unsigned long delay;
14306 	bool workposted = false;
14307 
14308 	/* process and rearm the CQ */
14309 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
14310 					     &delay);
14311 
14312 	if (delay) {
14313 		if (!queue_delayed_work_on(cq->chann, phba->wq,
14314 					   &cq->sched_irqwork, delay))
14315 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14316 				"0367 Cannot schedule soft IRQ "
14317 				"for cqid=%d on CPU %d\n",
14318 				cq->queue_id, cq->chann);
14319 	}
14320 
14321 	/* wake up worker thread if there are works to be done */
14322 	if (workposted)
14323 		lpfc_worker_wake_up(phba);
14324 }
14325 
14326 /**
14327  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
14328  *   interrupt
14329  * @work: pointer to work element
14330  *
14331  * translates from the work handler and calls the fast-path handler.
14332  **/
14333 static void
14334 lpfc_sli4_hba_process_cq(struct work_struct *work)
14335 {
14336 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
14337 
14338 	__lpfc_sli4_hba_process_cq(cq);
14339 }
14340 
14341 /**
14342  * lpfc_sli4_hba_process_cq - fast-path work handler when started by timer
14343  * @work: pointer to work element
14344  *
14345  * translates from the work handler and calls the fast-path handler.
14346  **/
14347 static void
14348 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
14349 {
14350 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
14351 					struct lpfc_queue, sched_irqwork);
14352 
14353 	__lpfc_sli4_hba_process_cq(cq);
14354 }
14355 
14356 /**
14357  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
14358  * @irq: Interrupt number.
14359  * @dev_id: The device context pointer.
14360  *
14361  * This function is directly called from the PCI layer as an interrupt
14362  * service routine when device with SLI-4 interface spec is enabled with
14363  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
14364  * ring event in the HBA. However, when the device is enabled with either
14365  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
14366  * device-level interrupt handler. When the PCI slot is in error recovery
14367  * or the HBA is undergoing initialization, the interrupt handler will not
14368  * process the interrupt. The SCSI FCP fast-path ring event are handled in
14369  * the intrrupt context. This function is called without any lock held.
14370  * It gets the hbalock to access and update SLI data structures. Note that,
14371  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
14372  * equal to that of FCP CQ index.
14373  *
14374  * The link attention and ELS ring attention events are handled
14375  * by the worker thread. The interrupt handler signals the worker thread
14376  * and returns for these events. This function is called without any lock
14377  * held. It gets the hbalock to access and update SLI data structures.
14378  *
14379  * This function returns IRQ_HANDLED when interrupt is handled else it
14380  * returns IRQ_NONE.
14381  **/
14382 irqreturn_t
14383 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
14384 {
14385 	struct lpfc_hba *phba;
14386 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
14387 	struct lpfc_queue *fpeq;
14388 	unsigned long iflag;
14389 	int ecount = 0;
14390 	int hba_eqidx;
14391 	struct lpfc_eq_intr_info *eqi;
14392 	uint32_t icnt;
14393 
14394 	/* Get the driver's phba structure from the dev_id */
14395 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
14396 	phba = hba_eq_hdl->phba;
14397 	hba_eqidx = hba_eq_hdl->idx;
14398 
14399 	if (unlikely(!phba))
14400 		return IRQ_NONE;
14401 	if (unlikely(!phba->sli4_hba.hdwq))
14402 		return IRQ_NONE;
14403 
14404 	/* Get to the EQ struct associated with this vector */
14405 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
14406 	if (unlikely(!fpeq))
14407 		return IRQ_NONE;
14408 
14409 	/* Check device state for handling interrupt */
14410 	if (unlikely(lpfc_intr_state_check(phba))) {
14411 		/* Check again for link_state with lock held */
14412 		spin_lock_irqsave(&phba->hbalock, iflag);
14413 		if (phba->link_state < LPFC_LINK_DOWN)
14414 			/* Flush, clear interrupt, and rearm the EQ */
14415 			lpfc_sli4_eqcq_flush(phba, fpeq);
14416 		spin_unlock_irqrestore(&phba->hbalock, iflag);
14417 		return IRQ_NONE;
14418 	}
14419 
14420 	eqi = phba->sli4_hba.eq_info;
14421 	icnt = this_cpu_inc_return(eqi->icnt);
14422 	fpeq->last_cpu = raw_smp_processor_id();
14423 
14424 	if (icnt > LPFC_EQD_ISR_TRIGGER &&
14425 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
14426 	    phba->cfg_auto_imax &&
14427 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
14428 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
14429 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
14430 
14431 	/* process and rearm the EQ */
14432 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
14433 
14434 	if (unlikely(ecount == 0)) {
14435 		fpeq->EQ_no_entry++;
14436 		if (phba->intr_type == MSIX)
14437 			/* MSI-X treated interrupt served as no EQ share INT */
14438 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14439 					"0358 MSI-X interrupt with no EQE\n");
14440 		else
14441 			/* Non MSI-X treated on interrupt as EQ share INT */
14442 			return IRQ_NONE;
14443 	}
14444 
14445 	return IRQ_HANDLED;
14446 } /* lpfc_sli4_fp_intr_handler */
14447 
14448 /**
14449  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
14450  * @irq: Interrupt number.
14451  * @dev_id: The device context pointer.
14452  *
14453  * This function is the device-level interrupt handler to device with SLI-4
14454  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
14455  * interrupt mode is enabled and there is an event in the HBA which requires
14456  * driver attention. This function invokes the slow-path interrupt attention
14457  * handling function and fast-path interrupt attention handling function in
14458  * turn to process the relevant HBA attention events. This function is called
14459  * without any lock held. It gets the hbalock to access and update SLI data
14460  * structures.
14461  *
14462  * This function returns IRQ_HANDLED when interrupt is handled, else it
14463  * returns IRQ_NONE.
14464  **/
14465 irqreturn_t
14466 lpfc_sli4_intr_handler(int irq, void *dev_id)
14467 {
14468 	struct lpfc_hba  *phba;
14469 	irqreturn_t hba_irq_rc;
14470 	bool hba_handled = false;
14471 	int qidx;
14472 
14473 	/* Get the driver's phba structure from the dev_id */
14474 	phba = (struct lpfc_hba *)dev_id;
14475 
14476 	if (unlikely(!phba))
14477 		return IRQ_NONE;
14478 
14479 	/*
14480 	 * Invoke fast-path host attention interrupt handling as appropriate.
14481 	 */
14482 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
14483 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
14484 					&phba->sli4_hba.hba_eq_hdl[qidx]);
14485 		if (hba_irq_rc == IRQ_HANDLED)
14486 			hba_handled |= true;
14487 	}
14488 
14489 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
14490 } /* lpfc_sli4_intr_handler */
14491 
14492 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
14493 {
14494 	struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
14495 	struct lpfc_queue *eq;
14496 	int i = 0;
14497 
14498 	rcu_read_lock();
14499 
14500 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
14501 		i += lpfc_sli4_poll_eq(eq, LPFC_POLL_SLOWPATH);
14502 	if (!list_empty(&phba->poll_list))
14503 		mod_timer(&phba->cpuhp_poll_timer,
14504 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
14505 
14506 	rcu_read_unlock();
14507 }
14508 
14509 inline int lpfc_sli4_poll_eq(struct lpfc_queue *eq, uint8_t path)
14510 {
14511 	struct lpfc_hba *phba = eq->phba;
14512 	int i = 0;
14513 
14514 	/*
14515 	 * Unlocking an irq is one of the entry point to check
14516 	 * for re-schedule, but we are good for io submission
14517 	 * path as midlayer does a get_cpu to glue us in. Flush
14518 	 * out the invalidate queue so we can see the updated
14519 	 * value for flag.
14520 	 */
14521 	smp_rmb();
14522 
14523 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
14524 		/* We will not likely get the completion for the caller
14525 		 * during this iteration but i guess that's fine.
14526 		 * Future io's coming on this eq should be able to
14527 		 * pick it up.  As for the case of single io's, they
14528 		 * will be handled through a sched from polling timer
14529 		 * function which is currently triggered every 1msec.
14530 		 */
14531 		i = lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM);
14532 
14533 	return i;
14534 }
14535 
14536 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
14537 {
14538 	struct lpfc_hba *phba = eq->phba;
14539 
14540 	/* kickstart slowpath processing if needed */
14541 	if (list_empty(&phba->poll_list))
14542 		mod_timer(&phba->cpuhp_poll_timer,
14543 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
14544 
14545 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
14546 	synchronize_rcu();
14547 }
14548 
14549 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
14550 {
14551 	struct lpfc_hba *phba = eq->phba;
14552 
14553 	/* Disable slowpath processing for this eq.  Kick start the eq
14554 	 * by RE-ARMING the eq's ASAP
14555 	 */
14556 	list_del_rcu(&eq->_poll_list);
14557 	synchronize_rcu();
14558 
14559 	if (list_empty(&phba->poll_list))
14560 		del_timer_sync(&phba->cpuhp_poll_timer);
14561 }
14562 
14563 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
14564 {
14565 	struct lpfc_queue *eq, *next;
14566 
14567 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
14568 		list_del(&eq->_poll_list);
14569 
14570 	INIT_LIST_HEAD(&phba->poll_list);
14571 	synchronize_rcu();
14572 }
14573 
14574 static inline void
14575 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
14576 {
14577 	if (mode == eq->mode)
14578 		return;
14579 	/*
14580 	 * currently this function is only called during a hotplug
14581 	 * event and the cpu on which this function is executing
14582 	 * is going offline.  By now the hotplug has instructed
14583 	 * the scheduler to remove this cpu from cpu active mask.
14584 	 * So we don't need to work about being put aside by the
14585 	 * scheduler for a high priority process.  Yes, the inte-
14586 	 * rrupts could come but they are known to retire ASAP.
14587 	 */
14588 
14589 	/* Disable polling in the fastpath */
14590 	WRITE_ONCE(eq->mode, mode);
14591 	/* flush out the store buffer */
14592 	smp_wmb();
14593 
14594 	/*
14595 	 * Add this eq to the polling list and start polling. For
14596 	 * a grace period both interrupt handler and poller will
14597 	 * try to process the eq _but_ that's fine.  We have a
14598 	 * synchronization mechanism in place (queue_claimed) to
14599 	 * deal with it.  This is just a draining phase for int-
14600 	 * errupt handler (not eq's) as we have guranteed through
14601 	 * barrier that all the CPUs have seen the new CQ_POLLED
14602 	 * state. which will effectively disable the REARMING of
14603 	 * the EQ.  The whole idea is eq's die off eventually as
14604 	 * we are not rearming EQ's anymore.
14605 	 */
14606 	mode ? lpfc_sli4_add_to_poll_list(eq) :
14607 	       lpfc_sli4_remove_from_poll_list(eq);
14608 }
14609 
14610 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
14611 {
14612 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
14613 }
14614 
14615 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
14616 {
14617 	struct lpfc_hba *phba = eq->phba;
14618 
14619 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
14620 
14621 	/* Kick start for the pending io's in h/w.
14622 	 * Once we switch back to interrupt processing on a eq
14623 	 * the io path completion will only arm eq's when it
14624 	 * receives a completion.  But since eq's are in disa-
14625 	 * rmed state it doesn't receive a completion.  This
14626 	 * creates a deadlock scenaro.
14627 	 */
14628 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
14629 }
14630 
14631 /**
14632  * lpfc_sli4_queue_free - free a queue structure and associated memory
14633  * @queue: The queue structure to free.
14634  *
14635  * This function frees a queue structure and the DMAable memory used for
14636  * the host resident queue. This function must be called after destroying the
14637  * queue on the HBA.
14638  **/
14639 void
14640 lpfc_sli4_queue_free(struct lpfc_queue *queue)
14641 {
14642 	struct lpfc_dmabuf *dmabuf;
14643 
14644 	if (!queue)
14645 		return;
14646 
14647 	if (!list_empty(&queue->wq_list))
14648 		list_del(&queue->wq_list);
14649 
14650 	while (!list_empty(&queue->page_list)) {
14651 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
14652 				 list);
14653 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
14654 				  dmabuf->virt, dmabuf->phys);
14655 		kfree(dmabuf);
14656 	}
14657 	if (queue->rqbp) {
14658 		lpfc_free_rq_buffer(queue->phba, queue);
14659 		kfree(queue->rqbp);
14660 	}
14661 
14662 	if (!list_empty(&queue->cpu_list))
14663 		list_del(&queue->cpu_list);
14664 
14665 	kfree(queue);
14666 	return;
14667 }
14668 
14669 /**
14670  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
14671  * @phba: The HBA that this queue is being created on.
14672  * @page_size: The size of a queue page
14673  * @entry_size: The size of each queue entry for this queue.
14674  * @entry count: The number of entries that this queue will handle.
14675  * @cpu: The cpu that will primarily utilize this queue.
14676  *
14677  * This function allocates a queue structure and the DMAable memory used for
14678  * the host resident queue. This function must be called before creating the
14679  * queue on the HBA.
14680  **/
14681 struct lpfc_queue *
14682 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
14683 		      uint32_t entry_size, uint32_t entry_count, int cpu)
14684 {
14685 	struct lpfc_queue *queue;
14686 	struct lpfc_dmabuf *dmabuf;
14687 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14688 	uint16_t x, pgcnt;
14689 
14690 	if (!phba->sli4_hba.pc_sli4_params.supported)
14691 		hw_page_size = page_size;
14692 
14693 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
14694 
14695 	/* If needed, Adjust page count to match the max the adapter supports */
14696 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
14697 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
14698 
14699 	queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
14700 			     GFP_KERNEL, cpu_to_node(cpu));
14701 	if (!queue)
14702 		return NULL;
14703 
14704 	INIT_LIST_HEAD(&queue->list);
14705 	INIT_LIST_HEAD(&queue->_poll_list);
14706 	INIT_LIST_HEAD(&queue->wq_list);
14707 	INIT_LIST_HEAD(&queue->wqfull_list);
14708 	INIT_LIST_HEAD(&queue->page_list);
14709 	INIT_LIST_HEAD(&queue->child_list);
14710 	INIT_LIST_HEAD(&queue->cpu_list);
14711 
14712 	/* Set queue parameters now.  If the system cannot provide memory
14713 	 * resources, the free routine needs to know what was allocated.
14714 	 */
14715 	queue->page_count = pgcnt;
14716 	queue->q_pgs = (void **)&queue[1];
14717 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
14718 	queue->entry_size = entry_size;
14719 	queue->entry_count = entry_count;
14720 	queue->page_size = hw_page_size;
14721 	queue->phba = phba;
14722 
14723 	for (x = 0; x < queue->page_count; x++) {
14724 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
14725 				      dev_to_node(&phba->pcidev->dev));
14726 		if (!dmabuf)
14727 			goto out_fail;
14728 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14729 						  hw_page_size, &dmabuf->phys,
14730 						  GFP_KERNEL);
14731 		if (!dmabuf->virt) {
14732 			kfree(dmabuf);
14733 			goto out_fail;
14734 		}
14735 		dmabuf->buffer_tag = x;
14736 		list_add_tail(&dmabuf->list, &queue->page_list);
14737 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
14738 		queue->q_pgs[x] = dmabuf->virt;
14739 	}
14740 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
14741 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
14742 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
14743 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
14744 
14745 	/* notify_interval will be set during q creation */
14746 
14747 	return queue;
14748 out_fail:
14749 	lpfc_sli4_queue_free(queue);
14750 	return NULL;
14751 }
14752 
14753 /**
14754  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
14755  * @phba: HBA structure that indicates port to create a queue on.
14756  * @pci_barset: PCI BAR set flag.
14757  *
14758  * This function shall perform iomap of the specified PCI BAR address to host
14759  * memory address if not already done so and return it. The returned host
14760  * memory address can be NULL.
14761  */
14762 static void __iomem *
14763 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
14764 {
14765 	if (!phba->pcidev)
14766 		return NULL;
14767 
14768 	switch (pci_barset) {
14769 	case WQ_PCI_BAR_0_AND_1:
14770 		return phba->pci_bar0_memmap_p;
14771 	case WQ_PCI_BAR_2_AND_3:
14772 		return phba->pci_bar2_memmap_p;
14773 	case WQ_PCI_BAR_4_AND_5:
14774 		return phba->pci_bar4_memmap_p;
14775 	default:
14776 		break;
14777 	}
14778 	return NULL;
14779 }
14780 
14781 /**
14782  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
14783  * @phba: HBA structure that EQs are on.
14784  * @startq: The starting EQ index to modify
14785  * @numq: The number of EQs (consecutive indexes) to modify
14786  * @usdelay: amount of delay
14787  *
14788  * This function revises the EQ delay on 1 or more EQs. The EQ delay
14789  * is set either by writing to a register (if supported by the SLI Port)
14790  * or by mailbox command. The mailbox command allows several EQs to be
14791  * updated at once.
14792  *
14793  * The @phba struct is used to send a mailbox command to HBA. The @startq
14794  * is used to get the starting EQ index to change. The @numq value is
14795  * used to specify how many consecutive EQ indexes, starting at EQ index,
14796  * are to be changed. This function is asynchronous and will wait for any
14797  * mailbox commands to finish before returning.
14798  *
14799  * On success this function will return a zero. If unable to allocate
14800  * enough memory this function will return -ENOMEM. If a mailbox command
14801  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
14802  * have had their delay multipler changed.
14803  **/
14804 void
14805 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
14806 			 uint32_t numq, uint32_t usdelay)
14807 {
14808 	struct lpfc_mbx_modify_eq_delay *eq_delay;
14809 	LPFC_MBOXQ_t *mbox;
14810 	struct lpfc_queue *eq;
14811 	int cnt = 0, rc, length;
14812 	uint32_t shdr_status, shdr_add_status;
14813 	uint32_t dmult;
14814 	int qidx;
14815 	union lpfc_sli4_cfg_shdr *shdr;
14816 
14817 	if (startq >= phba->cfg_irq_chann)
14818 		return;
14819 
14820 	if (usdelay > 0xFFFF) {
14821 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
14822 				"6429 usdelay %d too large. Scaled down to "
14823 				"0xFFFF.\n", usdelay);
14824 		usdelay = 0xFFFF;
14825 	}
14826 
14827 	/* set values by EQ_DELAY register if supported */
14828 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
14829 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
14830 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
14831 			if (!eq)
14832 				continue;
14833 
14834 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
14835 
14836 			if (++cnt >= numq)
14837 				break;
14838 		}
14839 		return;
14840 	}
14841 
14842 	/* Otherwise, set values by mailbox cmd */
14843 
14844 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14845 	if (!mbox) {
14846 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_FCP | LOG_NVME,
14847 				"6428 Failed allocating mailbox cmd buffer."
14848 				" EQ delay was not set.\n");
14849 		return;
14850 	}
14851 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
14852 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14853 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14854 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
14855 			 length, LPFC_SLI4_MBX_EMBED);
14856 	eq_delay = &mbox->u.mqe.un.eq_delay;
14857 
14858 	/* Calculate delay multiper from maximum interrupt per second */
14859 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
14860 	if (dmult)
14861 		dmult--;
14862 	if (dmult > LPFC_DMULT_MAX)
14863 		dmult = LPFC_DMULT_MAX;
14864 
14865 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
14866 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
14867 		if (!eq)
14868 			continue;
14869 		eq->q_mode = usdelay;
14870 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
14871 		eq_delay->u.request.eq[cnt].phase = 0;
14872 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
14873 
14874 		if (++cnt >= numq)
14875 			break;
14876 	}
14877 	eq_delay->u.request.num_eq = cnt;
14878 
14879 	mbox->vport = phba->pport;
14880 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14881 	mbox->ctx_buf = NULL;
14882 	mbox->ctx_ndlp = NULL;
14883 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14884 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
14885 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14886 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14887 	if (shdr_status || shdr_add_status || rc) {
14888 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14889 				"2512 MODIFY_EQ_DELAY mailbox failed with "
14890 				"status x%x add_status x%x, mbx status x%x\n",
14891 				shdr_status, shdr_add_status, rc);
14892 	}
14893 	mempool_free(mbox, phba->mbox_mem_pool);
14894 	return;
14895 }
14896 
14897 /**
14898  * lpfc_eq_create - Create an Event Queue on the HBA
14899  * @phba: HBA structure that indicates port to create a queue on.
14900  * @eq: The queue structure to use to create the event queue.
14901  * @imax: The maximum interrupt per second limit.
14902  *
14903  * This function creates an event queue, as detailed in @eq, on a port,
14904  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
14905  *
14906  * The @phba struct is used to send mailbox command to HBA. The @eq struct
14907  * is used to get the entry count and entry size that are necessary to
14908  * determine the number of pages to allocate and use for this queue. This
14909  * function will send the EQ_CREATE mailbox command to the HBA to setup the
14910  * event queue. This function is asynchronous and will wait for the mailbox
14911  * command to finish before continuing.
14912  *
14913  * On success this function will return a zero. If unable to allocate enough
14914  * memory this function will return -ENOMEM. If the queue create mailbox command
14915  * fails this function will return -ENXIO.
14916  **/
14917 int
14918 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
14919 {
14920 	struct lpfc_mbx_eq_create *eq_create;
14921 	LPFC_MBOXQ_t *mbox;
14922 	int rc, length, status = 0;
14923 	struct lpfc_dmabuf *dmabuf;
14924 	uint32_t shdr_status, shdr_add_status;
14925 	union lpfc_sli4_cfg_shdr *shdr;
14926 	uint16_t dmult;
14927 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14928 
14929 	/* sanity check on queue memory */
14930 	if (!eq)
14931 		return -ENODEV;
14932 	if (!phba->sli4_hba.pc_sli4_params.supported)
14933 		hw_page_size = SLI4_PAGE_SIZE;
14934 
14935 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14936 	if (!mbox)
14937 		return -ENOMEM;
14938 	length = (sizeof(struct lpfc_mbx_eq_create) -
14939 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14940 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14941 			 LPFC_MBOX_OPCODE_EQ_CREATE,
14942 			 length, LPFC_SLI4_MBX_EMBED);
14943 	eq_create = &mbox->u.mqe.un.eq_create;
14944 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
14945 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
14946 	       eq->page_count);
14947 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
14948 	       LPFC_EQE_SIZE);
14949 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
14950 
14951 	/* Use version 2 of CREATE_EQ if eqav is set */
14952 	if (phba->sli4_hba.pc_sli4_params.eqav) {
14953 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
14954 		       LPFC_Q_CREATE_VERSION_2);
14955 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
14956 		       phba->sli4_hba.pc_sli4_params.eqav);
14957 	}
14958 
14959 	/* don't setup delay multiplier using EQ_CREATE */
14960 	dmult = 0;
14961 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
14962 	       dmult);
14963 	switch (eq->entry_count) {
14964 	default:
14965 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14966 				"0360 Unsupported EQ count. (%d)\n",
14967 				eq->entry_count);
14968 		if (eq->entry_count < 256) {
14969 			status = -EINVAL;
14970 			goto out;
14971 		}
14972 		/* fall through - otherwise default to smallest count */
14973 	case 256:
14974 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14975 		       LPFC_EQ_CNT_256);
14976 		break;
14977 	case 512:
14978 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14979 		       LPFC_EQ_CNT_512);
14980 		break;
14981 	case 1024:
14982 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14983 		       LPFC_EQ_CNT_1024);
14984 		break;
14985 	case 2048:
14986 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14987 		       LPFC_EQ_CNT_2048);
14988 		break;
14989 	case 4096:
14990 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14991 		       LPFC_EQ_CNT_4096);
14992 		break;
14993 	}
14994 	list_for_each_entry(dmabuf, &eq->page_list, list) {
14995 		memset(dmabuf->virt, 0, hw_page_size);
14996 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
14997 					putPaddrLow(dmabuf->phys);
14998 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
14999 					putPaddrHigh(dmabuf->phys);
15000 	}
15001 	mbox->vport = phba->pport;
15002 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15003 	mbox->ctx_buf = NULL;
15004 	mbox->ctx_ndlp = NULL;
15005 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15006 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15007 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15008 	if (shdr_status || shdr_add_status || rc) {
15009 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15010 				"2500 EQ_CREATE mailbox failed with "
15011 				"status x%x add_status x%x, mbx status x%x\n",
15012 				shdr_status, shdr_add_status, rc);
15013 		status = -ENXIO;
15014 	}
15015 	eq->type = LPFC_EQ;
15016 	eq->subtype = LPFC_NONE;
15017 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
15018 	if (eq->queue_id == 0xFFFF)
15019 		status = -ENXIO;
15020 	eq->host_index = 0;
15021 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
15022 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
15023 out:
15024 	mempool_free(mbox, phba->mbox_mem_pool);
15025 	return status;
15026 }
15027 
15028 /**
15029  * lpfc_cq_create - Create a Completion Queue on the HBA
15030  * @phba: HBA structure that indicates port to create a queue on.
15031  * @cq: The queue structure to use to create the completion queue.
15032  * @eq: The event queue to bind this completion queue to.
15033  *
15034  * This function creates a completion queue, as detailed in @wq, on a port,
15035  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
15036  *
15037  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15038  * is used to get the entry count and entry size that are necessary to
15039  * determine the number of pages to allocate and use for this queue. The @eq
15040  * is used to indicate which event queue to bind this completion queue to. This
15041  * function will send the CQ_CREATE mailbox command to the HBA to setup the
15042  * completion queue. This function is asynchronous and will wait for the mailbox
15043  * command to finish before continuing.
15044  *
15045  * On success this function will return a zero. If unable to allocate enough
15046  * memory this function will return -ENOMEM. If the queue create mailbox command
15047  * fails this function will return -ENXIO.
15048  **/
15049 int
15050 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
15051 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
15052 {
15053 	struct lpfc_mbx_cq_create *cq_create;
15054 	struct lpfc_dmabuf *dmabuf;
15055 	LPFC_MBOXQ_t *mbox;
15056 	int rc, length, status = 0;
15057 	uint32_t shdr_status, shdr_add_status;
15058 	union lpfc_sli4_cfg_shdr *shdr;
15059 
15060 	/* sanity check on queue memory */
15061 	if (!cq || !eq)
15062 		return -ENODEV;
15063 
15064 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15065 	if (!mbox)
15066 		return -ENOMEM;
15067 	length = (sizeof(struct lpfc_mbx_cq_create) -
15068 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15069 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15070 			 LPFC_MBOX_OPCODE_CQ_CREATE,
15071 			 length, LPFC_SLI4_MBX_EMBED);
15072 	cq_create = &mbox->u.mqe.un.cq_create;
15073 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
15074 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
15075 		    cq->page_count);
15076 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
15077 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
15078 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15079 	       phba->sli4_hba.pc_sli4_params.cqv);
15080 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
15081 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
15082 		       (cq->page_size / SLI4_PAGE_SIZE));
15083 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
15084 		       eq->queue_id);
15085 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
15086 		       phba->sli4_hba.pc_sli4_params.cqav);
15087 	} else {
15088 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
15089 		       eq->queue_id);
15090 	}
15091 	switch (cq->entry_count) {
15092 	case 2048:
15093 	case 4096:
15094 		if (phba->sli4_hba.pc_sli4_params.cqv ==
15095 		    LPFC_Q_CREATE_VERSION_2) {
15096 			cq_create->u.request.context.lpfc_cq_context_count =
15097 				cq->entry_count;
15098 			bf_set(lpfc_cq_context_count,
15099 			       &cq_create->u.request.context,
15100 			       LPFC_CQ_CNT_WORD7);
15101 			break;
15102 		}
15103 		/* fall through */
15104 	default:
15105 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15106 				"0361 Unsupported CQ count: "
15107 				"entry cnt %d sz %d pg cnt %d\n",
15108 				cq->entry_count, cq->entry_size,
15109 				cq->page_count);
15110 		if (cq->entry_count < 256) {
15111 			status = -EINVAL;
15112 			goto out;
15113 		}
15114 		/* fall through - otherwise default to smallest count */
15115 	case 256:
15116 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15117 		       LPFC_CQ_CNT_256);
15118 		break;
15119 	case 512:
15120 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15121 		       LPFC_CQ_CNT_512);
15122 		break;
15123 	case 1024:
15124 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15125 		       LPFC_CQ_CNT_1024);
15126 		break;
15127 	}
15128 	list_for_each_entry(dmabuf, &cq->page_list, list) {
15129 		memset(dmabuf->virt, 0, cq->page_size);
15130 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15131 					putPaddrLow(dmabuf->phys);
15132 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15133 					putPaddrHigh(dmabuf->phys);
15134 	}
15135 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15136 
15137 	/* The IOCTL status is embedded in the mailbox subheader. */
15138 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15139 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15140 	if (shdr_status || shdr_add_status || rc) {
15141 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15142 				"2501 CQ_CREATE mailbox failed with "
15143 				"status x%x add_status x%x, mbx status x%x\n",
15144 				shdr_status, shdr_add_status, rc);
15145 		status = -ENXIO;
15146 		goto out;
15147 	}
15148 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15149 	if (cq->queue_id == 0xFFFF) {
15150 		status = -ENXIO;
15151 		goto out;
15152 	}
15153 	/* link the cq onto the parent eq child list */
15154 	list_add_tail(&cq->list, &eq->child_list);
15155 	/* Set up completion queue's type and subtype */
15156 	cq->type = type;
15157 	cq->subtype = subtype;
15158 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15159 	cq->assoc_qid = eq->queue_id;
15160 	cq->assoc_qp = eq;
15161 	cq->host_index = 0;
15162 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15163 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
15164 
15165 	if (cq->queue_id > phba->sli4_hba.cq_max)
15166 		phba->sli4_hba.cq_max = cq->queue_id;
15167 out:
15168 	mempool_free(mbox, phba->mbox_mem_pool);
15169 	return status;
15170 }
15171 
15172 /**
15173  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
15174  * @phba: HBA structure that indicates port to create a queue on.
15175  * @cqp: The queue structure array to use to create the completion queues.
15176  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
15177  *
15178  * This function creates a set of  completion queue, s to support MRQ
15179  * as detailed in @cqp, on a port,
15180  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
15181  *
15182  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15183  * is used to get the entry count and entry size that are necessary to
15184  * determine the number of pages to allocate and use for this queue. The @eq
15185  * is used to indicate which event queue to bind this completion queue to. This
15186  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
15187  * completion queue. This function is asynchronous and will wait for the mailbox
15188  * command to finish before continuing.
15189  *
15190  * On success this function will return a zero. If unable to allocate enough
15191  * memory this function will return -ENOMEM. If the queue create mailbox command
15192  * fails this function will return -ENXIO.
15193  **/
15194 int
15195 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
15196 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
15197 		   uint32_t subtype)
15198 {
15199 	struct lpfc_queue *cq;
15200 	struct lpfc_queue *eq;
15201 	struct lpfc_mbx_cq_create_set *cq_set;
15202 	struct lpfc_dmabuf *dmabuf;
15203 	LPFC_MBOXQ_t *mbox;
15204 	int rc, length, alloclen, status = 0;
15205 	int cnt, idx, numcq, page_idx = 0;
15206 	uint32_t shdr_status, shdr_add_status;
15207 	union lpfc_sli4_cfg_shdr *shdr;
15208 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15209 
15210 	/* sanity check on queue memory */
15211 	numcq = phba->cfg_nvmet_mrq;
15212 	if (!cqp || !hdwq || !numcq)
15213 		return -ENODEV;
15214 
15215 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15216 	if (!mbox)
15217 		return -ENOMEM;
15218 
15219 	length = sizeof(struct lpfc_mbx_cq_create_set);
15220 	length += ((numcq * cqp[0]->page_count) *
15221 		   sizeof(struct dma_address));
15222 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15223 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
15224 			LPFC_SLI4_MBX_NEMBED);
15225 	if (alloclen < length) {
15226 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15227 				"3098 Allocated DMA memory size (%d) is "
15228 				"less than the requested DMA memory size "
15229 				"(%d)\n", alloclen, length);
15230 		status = -ENOMEM;
15231 		goto out;
15232 	}
15233 	cq_set = mbox->sge_array->addr[0];
15234 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
15235 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
15236 
15237 	for (idx = 0; idx < numcq; idx++) {
15238 		cq = cqp[idx];
15239 		eq = hdwq[idx].hba_eq;
15240 		if (!cq || !eq) {
15241 			status = -ENOMEM;
15242 			goto out;
15243 		}
15244 		if (!phba->sli4_hba.pc_sli4_params.supported)
15245 			hw_page_size = cq->page_size;
15246 
15247 		switch (idx) {
15248 		case 0:
15249 			bf_set(lpfc_mbx_cq_create_set_page_size,
15250 			       &cq_set->u.request,
15251 			       (hw_page_size / SLI4_PAGE_SIZE));
15252 			bf_set(lpfc_mbx_cq_create_set_num_pages,
15253 			       &cq_set->u.request, cq->page_count);
15254 			bf_set(lpfc_mbx_cq_create_set_evt,
15255 			       &cq_set->u.request, 1);
15256 			bf_set(lpfc_mbx_cq_create_set_valid,
15257 			       &cq_set->u.request, 1);
15258 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
15259 			       &cq_set->u.request, 0);
15260 			bf_set(lpfc_mbx_cq_create_set_num_cq,
15261 			       &cq_set->u.request, numcq);
15262 			bf_set(lpfc_mbx_cq_create_set_autovalid,
15263 			       &cq_set->u.request,
15264 			       phba->sli4_hba.pc_sli4_params.cqav);
15265 			switch (cq->entry_count) {
15266 			case 2048:
15267 			case 4096:
15268 				if (phba->sli4_hba.pc_sli4_params.cqv ==
15269 				    LPFC_Q_CREATE_VERSION_2) {
15270 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15271 					       &cq_set->u.request,
15272 						cq->entry_count);
15273 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15274 					       &cq_set->u.request,
15275 					       LPFC_CQ_CNT_WORD7);
15276 					break;
15277 				}
15278 				/* fall through */
15279 			default:
15280 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15281 						"3118 Bad CQ count. (%d)\n",
15282 						cq->entry_count);
15283 				if (cq->entry_count < 256) {
15284 					status = -EINVAL;
15285 					goto out;
15286 				}
15287 				/* fall through - otherwise default to smallest */
15288 			case 256:
15289 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15290 				       &cq_set->u.request, LPFC_CQ_CNT_256);
15291 				break;
15292 			case 512:
15293 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15294 				       &cq_set->u.request, LPFC_CQ_CNT_512);
15295 				break;
15296 			case 1024:
15297 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15298 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
15299 				break;
15300 			}
15301 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
15302 			       &cq_set->u.request, eq->queue_id);
15303 			break;
15304 		case 1:
15305 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
15306 			       &cq_set->u.request, eq->queue_id);
15307 			break;
15308 		case 2:
15309 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
15310 			       &cq_set->u.request, eq->queue_id);
15311 			break;
15312 		case 3:
15313 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
15314 			       &cq_set->u.request, eq->queue_id);
15315 			break;
15316 		case 4:
15317 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
15318 			       &cq_set->u.request, eq->queue_id);
15319 			break;
15320 		case 5:
15321 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
15322 			       &cq_set->u.request, eq->queue_id);
15323 			break;
15324 		case 6:
15325 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
15326 			       &cq_set->u.request, eq->queue_id);
15327 			break;
15328 		case 7:
15329 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
15330 			       &cq_set->u.request, eq->queue_id);
15331 			break;
15332 		case 8:
15333 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
15334 			       &cq_set->u.request, eq->queue_id);
15335 			break;
15336 		case 9:
15337 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
15338 			       &cq_set->u.request, eq->queue_id);
15339 			break;
15340 		case 10:
15341 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
15342 			       &cq_set->u.request, eq->queue_id);
15343 			break;
15344 		case 11:
15345 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
15346 			       &cq_set->u.request, eq->queue_id);
15347 			break;
15348 		case 12:
15349 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
15350 			       &cq_set->u.request, eq->queue_id);
15351 			break;
15352 		case 13:
15353 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
15354 			       &cq_set->u.request, eq->queue_id);
15355 			break;
15356 		case 14:
15357 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
15358 			       &cq_set->u.request, eq->queue_id);
15359 			break;
15360 		case 15:
15361 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
15362 			       &cq_set->u.request, eq->queue_id);
15363 			break;
15364 		}
15365 
15366 		/* link the cq onto the parent eq child list */
15367 		list_add_tail(&cq->list, &eq->child_list);
15368 		/* Set up completion queue's type and subtype */
15369 		cq->type = type;
15370 		cq->subtype = subtype;
15371 		cq->assoc_qid = eq->queue_id;
15372 		cq->assoc_qp = eq;
15373 		cq->host_index = 0;
15374 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15375 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
15376 					 cq->entry_count);
15377 		cq->chann = idx;
15378 
15379 		rc = 0;
15380 		list_for_each_entry(dmabuf, &cq->page_list, list) {
15381 			memset(dmabuf->virt, 0, hw_page_size);
15382 			cnt = page_idx + dmabuf->buffer_tag;
15383 			cq_set->u.request.page[cnt].addr_lo =
15384 					putPaddrLow(dmabuf->phys);
15385 			cq_set->u.request.page[cnt].addr_hi =
15386 					putPaddrHigh(dmabuf->phys);
15387 			rc++;
15388 		}
15389 		page_idx += rc;
15390 	}
15391 
15392 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15393 
15394 	/* The IOCTL status is embedded in the mailbox subheader. */
15395 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15396 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15397 	if (shdr_status || shdr_add_status || rc) {
15398 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15399 				"3119 CQ_CREATE_SET mailbox failed with "
15400 				"status x%x add_status x%x, mbx status x%x\n",
15401 				shdr_status, shdr_add_status, rc);
15402 		status = -ENXIO;
15403 		goto out;
15404 	}
15405 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
15406 	if (rc == 0xFFFF) {
15407 		status = -ENXIO;
15408 		goto out;
15409 	}
15410 
15411 	for (idx = 0; idx < numcq; idx++) {
15412 		cq = cqp[idx];
15413 		cq->queue_id = rc + idx;
15414 		if (cq->queue_id > phba->sli4_hba.cq_max)
15415 			phba->sli4_hba.cq_max = cq->queue_id;
15416 	}
15417 
15418 out:
15419 	lpfc_sli4_mbox_cmd_free(phba, mbox);
15420 	return status;
15421 }
15422 
15423 /**
15424  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
15425  * @phba: HBA structure that indicates port to create a queue on.
15426  * @mq: The queue structure to use to create the mailbox queue.
15427  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
15428  * @cq: The completion queue to associate with this cq.
15429  *
15430  * This function provides failback (fb) functionality when the
15431  * mq_create_ext fails on older FW generations.  It's purpose is identical
15432  * to mq_create_ext otherwise.
15433  *
15434  * This routine cannot fail as all attributes were previously accessed and
15435  * initialized in mq_create_ext.
15436  **/
15437 static void
15438 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
15439 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
15440 {
15441 	struct lpfc_mbx_mq_create *mq_create;
15442 	struct lpfc_dmabuf *dmabuf;
15443 	int length;
15444 
15445 	length = (sizeof(struct lpfc_mbx_mq_create) -
15446 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15447 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15448 			 LPFC_MBOX_OPCODE_MQ_CREATE,
15449 			 length, LPFC_SLI4_MBX_EMBED);
15450 	mq_create = &mbox->u.mqe.un.mq_create;
15451 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
15452 	       mq->page_count);
15453 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
15454 	       cq->queue_id);
15455 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
15456 	switch (mq->entry_count) {
15457 	case 16:
15458 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15459 		       LPFC_MQ_RING_SIZE_16);
15460 		break;
15461 	case 32:
15462 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15463 		       LPFC_MQ_RING_SIZE_32);
15464 		break;
15465 	case 64:
15466 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15467 		       LPFC_MQ_RING_SIZE_64);
15468 		break;
15469 	case 128:
15470 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15471 		       LPFC_MQ_RING_SIZE_128);
15472 		break;
15473 	}
15474 	list_for_each_entry(dmabuf, &mq->page_list, list) {
15475 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15476 			putPaddrLow(dmabuf->phys);
15477 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15478 			putPaddrHigh(dmabuf->phys);
15479 	}
15480 }
15481 
15482 /**
15483  * lpfc_mq_create - Create a mailbox Queue on the HBA
15484  * @phba: HBA structure that indicates port to create a queue on.
15485  * @mq: The queue structure to use to create the mailbox queue.
15486  * @cq: The completion queue to associate with this cq.
15487  * @subtype: The queue's subtype.
15488  *
15489  * This function creates a mailbox queue, as detailed in @mq, on a port,
15490  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
15491  *
15492  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15493  * is used to get the entry count and entry size that are necessary to
15494  * determine the number of pages to allocate and use for this queue. This
15495  * function will send the MQ_CREATE mailbox command to the HBA to setup the
15496  * mailbox queue. This function is asynchronous and will wait for the mailbox
15497  * command to finish before continuing.
15498  *
15499  * On success this function will return a zero. If unable to allocate enough
15500  * memory this function will return -ENOMEM. If the queue create mailbox command
15501  * fails this function will return -ENXIO.
15502  **/
15503 int32_t
15504 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
15505 	       struct lpfc_queue *cq, uint32_t subtype)
15506 {
15507 	struct lpfc_mbx_mq_create *mq_create;
15508 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
15509 	struct lpfc_dmabuf *dmabuf;
15510 	LPFC_MBOXQ_t *mbox;
15511 	int rc, length, status = 0;
15512 	uint32_t shdr_status, shdr_add_status;
15513 	union lpfc_sli4_cfg_shdr *shdr;
15514 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15515 
15516 	/* sanity check on queue memory */
15517 	if (!mq || !cq)
15518 		return -ENODEV;
15519 	if (!phba->sli4_hba.pc_sli4_params.supported)
15520 		hw_page_size = SLI4_PAGE_SIZE;
15521 
15522 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15523 	if (!mbox)
15524 		return -ENOMEM;
15525 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
15526 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15527 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15528 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
15529 			 length, LPFC_SLI4_MBX_EMBED);
15530 
15531 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
15532 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
15533 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
15534 	       &mq_create_ext->u.request, mq->page_count);
15535 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
15536 	       &mq_create_ext->u.request, 1);
15537 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
15538 	       &mq_create_ext->u.request, 1);
15539 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
15540 	       &mq_create_ext->u.request, 1);
15541 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
15542 	       &mq_create_ext->u.request, 1);
15543 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
15544 	       &mq_create_ext->u.request, 1);
15545 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
15546 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15547 	       phba->sli4_hba.pc_sli4_params.mqv);
15548 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
15549 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
15550 		       cq->queue_id);
15551 	else
15552 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
15553 		       cq->queue_id);
15554 	switch (mq->entry_count) {
15555 	default:
15556 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15557 				"0362 Unsupported MQ count. (%d)\n",
15558 				mq->entry_count);
15559 		if (mq->entry_count < 16) {
15560 			status = -EINVAL;
15561 			goto out;
15562 		}
15563 		/* fall through - otherwise default to smallest count */
15564 	case 16:
15565 		bf_set(lpfc_mq_context_ring_size,
15566 		       &mq_create_ext->u.request.context,
15567 		       LPFC_MQ_RING_SIZE_16);
15568 		break;
15569 	case 32:
15570 		bf_set(lpfc_mq_context_ring_size,
15571 		       &mq_create_ext->u.request.context,
15572 		       LPFC_MQ_RING_SIZE_32);
15573 		break;
15574 	case 64:
15575 		bf_set(lpfc_mq_context_ring_size,
15576 		       &mq_create_ext->u.request.context,
15577 		       LPFC_MQ_RING_SIZE_64);
15578 		break;
15579 	case 128:
15580 		bf_set(lpfc_mq_context_ring_size,
15581 		       &mq_create_ext->u.request.context,
15582 		       LPFC_MQ_RING_SIZE_128);
15583 		break;
15584 	}
15585 	list_for_each_entry(dmabuf, &mq->page_list, list) {
15586 		memset(dmabuf->virt, 0, hw_page_size);
15587 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
15588 					putPaddrLow(dmabuf->phys);
15589 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
15590 					putPaddrHigh(dmabuf->phys);
15591 	}
15592 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15593 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
15594 			      &mq_create_ext->u.response);
15595 	if (rc != MBX_SUCCESS) {
15596 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15597 				"2795 MQ_CREATE_EXT failed with "
15598 				"status x%x. Failback to MQ_CREATE.\n",
15599 				rc);
15600 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
15601 		mq_create = &mbox->u.mqe.un.mq_create;
15602 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15603 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
15604 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
15605 				      &mq_create->u.response);
15606 	}
15607 
15608 	/* The IOCTL status is embedded in the mailbox subheader. */
15609 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15610 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15611 	if (shdr_status || shdr_add_status || rc) {
15612 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15613 				"2502 MQ_CREATE mailbox failed with "
15614 				"status x%x add_status x%x, mbx status x%x\n",
15615 				shdr_status, shdr_add_status, rc);
15616 		status = -ENXIO;
15617 		goto out;
15618 	}
15619 	if (mq->queue_id == 0xFFFF) {
15620 		status = -ENXIO;
15621 		goto out;
15622 	}
15623 	mq->type = LPFC_MQ;
15624 	mq->assoc_qid = cq->queue_id;
15625 	mq->subtype = subtype;
15626 	mq->host_index = 0;
15627 	mq->hba_index = 0;
15628 
15629 	/* link the mq onto the parent cq child list */
15630 	list_add_tail(&mq->list, &cq->child_list);
15631 out:
15632 	mempool_free(mbox, phba->mbox_mem_pool);
15633 	return status;
15634 }
15635 
15636 /**
15637  * lpfc_wq_create - Create a Work Queue on the HBA
15638  * @phba: HBA structure that indicates port to create a queue on.
15639  * @wq: The queue structure to use to create the work queue.
15640  * @cq: The completion queue to bind this work queue to.
15641  * @subtype: The subtype of the work queue indicating its functionality.
15642  *
15643  * This function creates a work queue, as detailed in @wq, on a port, described
15644  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
15645  *
15646  * The @phba struct is used to send mailbox command to HBA. The @wq struct
15647  * is used to get the entry count and entry size that are necessary to
15648  * determine the number of pages to allocate and use for this queue. The @cq
15649  * is used to indicate which completion queue to bind this work queue to. This
15650  * function will send the WQ_CREATE mailbox command to the HBA to setup the
15651  * work queue. This function is asynchronous and will wait for the mailbox
15652  * command to finish before continuing.
15653  *
15654  * On success this function will return a zero. If unable to allocate enough
15655  * memory this function will return -ENOMEM. If the queue create mailbox command
15656  * fails this function will return -ENXIO.
15657  **/
15658 int
15659 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
15660 	       struct lpfc_queue *cq, uint32_t subtype)
15661 {
15662 	struct lpfc_mbx_wq_create *wq_create;
15663 	struct lpfc_dmabuf *dmabuf;
15664 	LPFC_MBOXQ_t *mbox;
15665 	int rc, length, status = 0;
15666 	uint32_t shdr_status, shdr_add_status;
15667 	union lpfc_sli4_cfg_shdr *shdr;
15668 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15669 	struct dma_address *page;
15670 	void __iomem *bar_memmap_p;
15671 	uint32_t db_offset;
15672 	uint16_t pci_barset;
15673 	uint8_t dpp_barset;
15674 	uint32_t dpp_offset;
15675 	unsigned long pg_addr;
15676 	uint8_t wq_create_version;
15677 
15678 	/* sanity check on queue memory */
15679 	if (!wq || !cq)
15680 		return -ENODEV;
15681 	if (!phba->sli4_hba.pc_sli4_params.supported)
15682 		hw_page_size = wq->page_size;
15683 
15684 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15685 	if (!mbox)
15686 		return -ENOMEM;
15687 	length = (sizeof(struct lpfc_mbx_wq_create) -
15688 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15689 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15690 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
15691 			 length, LPFC_SLI4_MBX_EMBED);
15692 	wq_create = &mbox->u.mqe.un.wq_create;
15693 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
15694 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
15695 		    wq->page_count);
15696 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
15697 		    cq->queue_id);
15698 
15699 	/* wqv is the earliest version supported, NOT the latest */
15700 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15701 	       phba->sli4_hba.pc_sli4_params.wqv);
15702 
15703 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
15704 	    (wq->page_size > SLI4_PAGE_SIZE))
15705 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
15706 	else
15707 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
15708 
15709 
15710 	if (phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT)
15711 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
15712 	else
15713 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
15714 
15715 	switch (wq_create_version) {
15716 	case LPFC_Q_CREATE_VERSION_1:
15717 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
15718 		       wq->entry_count);
15719 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
15720 		       LPFC_Q_CREATE_VERSION_1);
15721 
15722 		switch (wq->entry_size) {
15723 		default:
15724 		case 64:
15725 			bf_set(lpfc_mbx_wq_create_wqe_size,
15726 			       &wq_create->u.request_1,
15727 			       LPFC_WQ_WQE_SIZE_64);
15728 			break;
15729 		case 128:
15730 			bf_set(lpfc_mbx_wq_create_wqe_size,
15731 			       &wq_create->u.request_1,
15732 			       LPFC_WQ_WQE_SIZE_128);
15733 			break;
15734 		}
15735 		/* Request DPP by default */
15736 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
15737 		bf_set(lpfc_mbx_wq_create_page_size,
15738 		       &wq_create->u.request_1,
15739 		       (wq->page_size / SLI4_PAGE_SIZE));
15740 		page = wq_create->u.request_1.page;
15741 		break;
15742 	default:
15743 		page = wq_create->u.request.page;
15744 		break;
15745 	}
15746 
15747 	list_for_each_entry(dmabuf, &wq->page_list, list) {
15748 		memset(dmabuf->virt, 0, hw_page_size);
15749 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
15750 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
15751 	}
15752 
15753 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
15754 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
15755 
15756 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15757 	/* The IOCTL status is embedded in the mailbox subheader. */
15758 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15759 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15760 	if (shdr_status || shdr_add_status || rc) {
15761 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15762 				"2503 WQ_CREATE mailbox failed with "
15763 				"status x%x add_status x%x, mbx status x%x\n",
15764 				shdr_status, shdr_add_status, rc);
15765 		status = -ENXIO;
15766 		goto out;
15767 	}
15768 
15769 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
15770 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
15771 					&wq_create->u.response);
15772 	else
15773 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
15774 					&wq_create->u.response_1);
15775 
15776 	if (wq->queue_id == 0xFFFF) {
15777 		status = -ENXIO;
15778 		goto out;
15779 	}
15780 
15781 	wq->db_format = LPFC_DB_LIST_FORMAT;
15782 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
15783 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
15784 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
15785 					       &wq_create->u.response);
15786 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
15787 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
15788 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15789 						"3265 WQ[%d] doorbell format "
15790 						"not supported: x%x\n",
15791 						wq->queue_id, wq->db_format);
15792 				status = -EINVAL;
15793 				goto out;
15794 			}
15795 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
15796 					    &wq_create->u.response);
15797 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15798 								   pci_barset);
15799 			if (!bar_memmap_p) {
15800 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15801 						"3263 WQ[%d] failed to memmap "
15802 						"pci barset:x%x\n",
15803 						wq->queue_id, pci_barset);
15804 				status = -ENOMEM;
15805 				goto out;
15806 			}
15807 			db_offset = wq_create->u.response.doorbell_offset;
15808 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
15809 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
15810 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15811 						"3252 WQ[%d] doorbell offset "
15812 						"not supported: x%x\n",
15813 						wq->queue_id, db_offset);
15814 				status = -EINVAL;
15815 				goto out;
15816 			}
15817 			wq->db_regaddr = bar_memmap_p + db_offset;
15818 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15819 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
15820 					"format:x%x\n", wq->queue_id,
15821 					pci_barset, db_offset, wq->db_format);
15822 		} else
15823 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
15824 	} else {
15825 		/* Check if DPP was honored by the firmware */
15826 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
15827 				    &wq_create->u.response_1);
15828 		if (wq->dpp_enable) {
15829 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
15830 					    &wq_create->u.response_1);
15831 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15832 								   pci_barset);
15833 			if (!bar_memmap_p) {
15834 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15835 						"3267 WQ[%d] failed to memmap "
15836 						"pci barset:x%x\n",
15837 						wq->queue_id, pci_barset);
15838 				status = -ENOMEM;
15839 				goto out;
15840 			}
15841 			db_offset = wq_create->u.response_1.doorbell_offset;
15842 			wq->db_regaddr = bar_memmap_p + db_offset;
15843 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
15844 					    &wq_create->u.response_1);
15845 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
15846 					    &wq_create->u.response_1);
15847 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15848 								   dpp_barset);
15849 			if (!bar_memmap_p) {
15850 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15851 						"3268 WQ[%d] failed to memmap "
15852 						"pci barset:x%x\n",
15853 						wq->queue_id, dpp_barset);
15854 				status = -ENOMEM;
15855 				goto out;
15856 			}
15857 			dpp_offset = wq_create->u.response_1.dpp_offset;
15858 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
15859 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15860 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
15861 					"dpp_id:x%x dpp_barset:x%x "
15862 					"dpp_offset:x%x\n",
15863 					wq->queue_id, pci_barset, db_offset,
15864 					wq->dpp_id, dpp_barset, dpp_offset);
15865 
15866 			/* Enable combined writes for DPP aperture */
15867 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
15868 #ifdef CONFIG_X86
15869 			rc = set_memory_wc(pg_addr, 1);
15870 			if (rc) {
15871 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15872 					"3272 Cannot setup Combined "
15873 					"Write on WQ[%d] - disable DPP\n",
15874 					wq->queue_id);
15875 				phba->cfg_enable_dpp = 0;
15876 			}
15877 #else
15878 			phba->cfg_enable_dpp = 0;
15879 #endif
15880 		} else
15881 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
15882 	}
15883 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
15884 	if (wq->pring == NULL) {
15885 		status = -ENOMEM;
15886 		goto out;
15887 	}
15888 	wq->type = LPFC_WQ;
15889 	wq->assoc_qid = cq->queue_id;
15890 	wq->subtype = subtype;
15891 	wq->host_index = 0;
15892 	wq->hba_index = 0;
15893 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
15894 
15895 	/* link the wq onto the parent cq child list */
15896 	list_add_tail(&wq->list, &cq->child_list);
15897 out:
15898 	mempool_free(mbox, phba->mbox_mem_pool);
15899 	return status;
15900 }
15901 
15902 /**
15903  * lpfc_rq_create - Create a Receive Queue on the HBA
15904  * @phba: HBA structure that indicates port to create a queue on.
15905  * @hrq: The queue structure to use to create the header receive queue.
15906  * @drq: The queue structure to use to create the data receive queue.
15907  * @cq: The completion queue to bind this work queue to.
15908  *
15909  * This function creates a receive buffer queue pair , as detailed in @hrq and
15910  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
15911  * to the HBA.
15912  *
15913  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
15914  * struct is used to get the entry count that is necessary to determine the
15915  * number of pages to use for this queue. The @cq is used to indicate which
15916  * completion queue to bind received buffers that are posted to these queues to.
15917  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
15918  * receive queue pair. This function is asynchronous and will wait for the
15919  * mailbox command to finish before continuing.
15920  *
15921  * On success this function will return a zero. If unable to allocate enough
15922  * memory this function will return -ENOMEM. If the queue create mailbox command
15923  * fails this function will return -ENXIO.
15924  **/
15925 int
15926 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
15927 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
15928 {
15929 	struct lpfc_mbx_rq_create *rq_create;
15930 	struct lpfc_dmabuf *dmabuf;
15931 	LPFC_MBOXQ_t *mbox;
15932 	int rc, length, status = 0;
15933 	uint32_t shdr_status, shdr_add_status;
15934 	union lpfc_sli4_cfg_shdr *shdr;
15935 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15936 	void __iomem *bar_memmap_p;
15937 	uint32_t db_offset;
15938 	uint16_t pci_barset;
15939 
15940 	/* sanity check on queue memory */
15941 	if (!hrq || !drq || !cq)
15942 		return -ENODEV;
15943 	if (!phba->sli4_hba.pc_sli4_params.supported)
15944 		hw_page_size = SLI4_PAGE_SIZE;
15945 
15946 	if (hrq->entry_count != drq->entry_count)
15947 		return -EINVAL;
15948 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15949 	if (!mbox)
15950 		return -ENOMEM;
15951 	length = (sizeof(struct lpfc_mbx_rq_create) -
15952 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15953 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15954 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
15955 			 length, LPFC_SLI4_MBX_EMBED);
15956 	rq_create = &mbox->u.mqe.un.rq_create;
15957 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
15958 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15959 	       phba->sli4_hba.pc_sli4_params.rqv);
15960 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
15961 		bf_set(lpfc_rq_context_rqe_count_1,
15962 		       &rq_create->u.request.context,
15963 		       hrq->entry_count);
15964 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
15965 		bf_set(lpfc_rq_context_rqe_size,
15966 		       &rq_create->u.request.context,
15967 		       LPFC_RQE_SIZE_8);
15968 		bf_set(lpfc_rq_context_page_size,
15969 		       &rq_create->u.request.context,
15970 		       LPFC_RQ_PAGE_SIZE_4096);
15971 	} else {
15972 		switch (hrq->entry_count) {
15973 		default:
15974 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15975 					"2535 Unsupported RQ count. (%d)\n",
15976 					hrq->entry_count);
15977 			if (hrq->entry_count < 512) {
15978 				status = -EINVAL;
15979 				goto out;
15980 			}
15981 			/* fall through - otherwise default to smallest count */
15982 		case 512:
15983 			bf_set(lpfc_rq_context_rqe_count,
15984 			       &rq_create->u.request.context,
15985 			       LPFC_RQ_RING_SIZE_512);
15986 			break;
15987 		case 1024:
15988 			bf_set(lpfc_rq_context_rqe_count,
15989 			       &rq_create->u.request.context,
15990 			       LPFC_RQ_RING_SIZE_1024);
15991 			break;
15992 		case 2048:
15993 			bf_set(lpfc_rq_context_rqe_count,
15994 			       &rq_create->u.request.context,
15995 			       LPFC_RQ_RING_SIZE_2048);
15996 			break;
15997 		case 4096:
15998 			bf_set(lpfc_rq_context_rqe_count,
15999 			       &rq_create->u.request.context,
16000 			       LPFC_RQ_RING_SIZE_4096);
16001 			break;
16002 		}
16003 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
16004 		       LPFC_HDR_BUF_SIZE);
16005 	}
16006 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16007 	       cq->queue_id);
16008 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16009 	       hrq->page_count);
16010 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
16011 		memset(dmabuf->virt, 0, hw_page_size);
16012 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16013 					putPaddrLow(dmabuf->phys);
16014 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16015 					putPaddrHigh(dmabuf->phys);
16016 	}
16017 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16018 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16019 
16020 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16021 	/* The IOCTL status is embedded in the mailbox subheader. */
16022 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16023 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16024 	if (shdr_status || shdr_add_status || rc) {
16025 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16026 				"2504 RQ_CREATE mailbox failed with "
16027 				"status x%x add_status x%x, mbx status x%x\n",
16028 				shdr_status, shdr_add_status, rc);
16029 		status = -ENXIO;
16030 		goto out;
16031 	}
16032 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16033 	if (hrq->queue_id == 0xFFFF) {
16034 		status = -ENXIO;
16035 		goto out;
16036 	}
16037 
16038 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16039 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
16040 					&rq_create->u.response);
16041 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
16042 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
16043 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16044 					"3262 RQ [%d] doorbell format not "
16045 					"supported: x%x\n", hrq->queue_id,
16046 					hrq->db_format);
16047 			status = -EINVAL;
16048 			goto out;
16049 		}
16050 
16051 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
16052 				    &rq_create->u.response);
16053 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
16054 		if (!bar_memmap_p) {
16055 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16056 					"3269 RQ[%d] failed to memmap pci "
16057 					"barset:x%x\n", hrq->queue_id,
16058 					pci_barset);
16059 			status = -ENOMEM;
16060 			goto out;
16061 		}
16062 
16063 		db_offset = rq_create->u.response.doorbell_offset;
16064 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
16065 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
16066 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16067 					"3270 RQ[%d] doorbell offset not "
16068 					"supported: x%x\n", hrq->queue_id,
16069 					db_offset);
16070 			status = -EINVAL;
16071 			goto out;
16072 		}
16073 		hrq->db_regaddr = bar_memmap_p + db_offset;
16074 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16075 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
16076 				"format:x%x\n", hrq->queue_id, pci_barset,
16077 				db_offset, hrq->db_format);
16078 	} else {
16079 		hrq->db_format = LPFC_DB_RING_FORMAT;
16080 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16081 	}
16082 	hrq->type = LPFC_HRQ;
16083 	hrq->assoc_qid = cq->queue_id;
16084 	hrq->subtype = subtype;
16085 	hrq->host_index = 0;
16086 	hrq->hba_index = 0;
16087 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16088 
16089 	/* now create the data queue */
16090 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16091 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
16092 			 length, LPFC_SLI4_MBX_EMBED);
16093 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16094 	       phba->sli4_hba.pc_sli4_params.rqv);
16095 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
16096 		bf_set(lpfc_rq_context_rqe_count_1,
16097 		       &rq_create->u.request.context, hrq->entry_count);
16098 		if (subtype == LPFC_NVMET)
16099 			rq_create->u.request.context.buffer_size =
16100 				LPFC_NVMET_DATA_BUF_SIZE;
16101 		else
16102 			rq_create->u.request.context.buffer_size =
16103 				LPFC_DATA_BUF_SIZE;
16104 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
16105 		       LPFC_RQE_SIZE_8);
16106 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
16107 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
16108 	} else {
16109 		switch (drq->entry_count) {
16110 		default:
16111 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16112 					"2536 Unsupported RQ count. (%d)\n",
16113 					drq->entry_count);
16114 			if (drq->entry_count < 512) {
16115 				status = -EINVAL;
16116 				goto out;
16117 			}
16118 			/* fall through - otherwise default to smallest count */
16119 		case 512:
16120 			bf_set(lpfc_rq_context_rqe_count,
16121 			       &rq_create->u.request.context,
16122 			       LPFC_RQ_RING_SIZE_512);
16123 			break;
16124 		case 1024:
16125 			bf_set(lpfc_rq_context_rqe_count,
16126 			       &rq_create->u.request.context,
16127 			       LPFC_RQ_RING_SIZE_1024);
16128 			break;
16129 		case 2048:
16130 			bf_set(lpfc_rq_context_rqe_count,
16131 			       &rq_create->u.request.context,
16132 			       LPFC_RQ_RING_SIZE_2048);
16133 			break;
16134 		case 4096:
16135 			bf_set(lpfc_rq_context_rqe_count,
16136 			       &rq_create->u.request.context,
16137 			       LPFC_RQ_RING_SIZE_4096);
16138 			break;
16139 		}
16140 		if (subtype == LPFC_NVMET)
16141 			bf_set(lpfc_rq_context_buf_size,
16142 			       &rq_create->u.request.context,
16143 			       LPFC_NVMET_DATA_BUF_SIZE);
16144 		else
16145 			bf_set(lpfc_rq_context_buf_size,
16146 			       &rq_create->u.request.context,
16147 			       LPFC_DATA_BUF_SIZE);
16148 	}
16149 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16150 	       cq->queue_id);
16151 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16152 	       drq->page_count);
16153 	list_for_each_entry(dmabuf, &drq->page_list, list) {
16154 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16155 					putPaddrLow(dmabuf->phys);
16156 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16157 					putPaddrHigh(dmabuf->phys);
16158 	}
16159 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16160 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16161 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16162 	/* The IOCTL status is embedded in the mailbox subheader. */
16163 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
16164 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16165 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16166 	if (shdr_status || shdr_add_status || rc) {
16167 		status = -ENXIO;
16168 		goto out;
16169 	}
16170 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16171 	if (drq->queue_id == 0xFFFF) {
16172 		status = -ENXIO;
16173 		goto out;
16174 	}
16175 	drq->type = LPFC_DRQ;
16176 	drq->assoc_qid = cq->queue_id;
16177 	drq->subtype = subtype;
16178 	drq->host_index = 0;
16179 	drq->hba_index = 0;
16180 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16181 
16182 	/* link the header and data RQs onto the parent cq child list */
16183 	list_add_tail(&hrq->list, &cq->child_list);
16184 	list_add_tail(&drq->list, &cq->child_list);
16185 
16186 out:
16187 	mempool_free(mbox, phba->mbox_mem_pool);
16188 	return status;
16189 }
16190 
16191 /**
16192  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
16193  * @phba: HBA structure that indicates port to create a queue on.
16194  * @hrqp: The queue structure array to use to create the header receive queues.
16195  * @drqp: The queue structure array to use to create the data receive queues.
16196  * @cqp: The completion queue array to bind these receive queues to.
16197  *
16198  * This function creates a receive buffer queue pair , as detailed in @hrq and
16199  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
16200  * to the HBA.
16201  *
16202  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
16203  * struct is used to get the entry count that is necessary to determine the
16204  * number of pages to use for this queue. The @cq is used to indicate which
16205  * completion queue to bind received buffers that are posted to these queues to.
16206  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
16207  * receive queue pair. This function is asynchronous and will wait for the
16208  * mailbox command to finish before continuing.
16209  *
16210  * On success this function will return a zero. If unable to allocate enough
16211  * memory this function will return -ENOMEM. If the queue create mailbox command
16212  * fails this function will return -ENXIO.
16213  **/
16214 int
16215 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
16216 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
16217 		uint32_t subtype)
16218 {
16219 	struct lpfc_queue *hrq, *drq, *cq;
16220 	struct lpfc_mbx_rq_create_v2 *rq_create;
16221 	struct lpfc_dmabuf *dmabuf;
16222 	LPFC_MBOXQ_t *mbox;
16223 	int rc, length, alloclen, status = 0;
16224 	int cnt, idx, numrq, page_idx = 0;
16225 	uint32_t shdr_status, shdr_add_status;
16226 	union lpfc_sli4_cfg_shdr *shdr;
16227 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16228 
16229 	numrq = phba->cfg_nvmet_mrq;
16230 	/* sanity check on array memory */
16231 	if (!hrqp || !drqp || !cqp || !numrq)
16232 		return -ENODEV;
16233 	if (!phba->sli4_hba.pc_sli4_params.supported)
16234 		hw_page_size = SLI4_PAGE_SIZE;
16235 
16236 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16237 	if (!mbox)
16238 		return -ENOMEM;
16239 
16240 	length = sizeof(struct lpfc_mbx_rq_create_v2);
16241 	length += ((2 * numrq * hrqp[0]->page_count) *
16242 		   sizeof(struct dma_address));
16243 
16244 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16245 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
16246 				    LPFC_SLI4_MBX_NEMBED);
16247 	if (alloclen < length) {
16248 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16249 				"3099 Allocated DMA memory size (%d) is "
16250 				"less than the requested DMA memory size "
16251 				"(%d)\n", alloclen, length);
16252 		status = -ENOMEM;
16253 		goto out;
16254 	}
16255 
16256 
16257 
16258 	rq_create = mbox->sge_array->addr[0];
16259 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
16260 
16261 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
16262 	cnt = 0;
16263 
16264 	for (idx = 0; idx < numrq; idx++) {
16265 		hrq = hrqp[idx];
16266 		drq = drqp[idx];
16267 		cq  = cqp[idx];
16268 
16269 		/* sanity check on queue memory */
16270 		if (!hrq || !drq || !cq) {
16271 			status = -ENODEV;
16272 			goto out;
16273 		}
16274 
16275 		if (hrq->entry_count != drq->entry_count) {
16276 			status = -EINVAL;
16277 			goto out;
16278 		}
16279 
16280 		if (idx == 0) {
16281 			bf_set(lpfc_mbx_rq_create_num_pages,
16282 			       &rq_create->u.request,
16283 			       hrq->page_count);
16284 			bf_set(lpfc_mbx_rq_create_rq_cnt,
16285 			       &rq_create->u.request, (numrq * 2));
16286 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
16287 			       1);
16288 			bf_set(lpfc_rq_context_base_cq,
16289 			       &rq_create->u.request.context,
16290 			       cq->queue_id);
16291 			bf_set(lpfc_rq_context_data_size,
16292 			       &rq_create->u.request.context,
16293 			       LPFC_NVMET_DATA_BUF_SIZE);
16294 			bf_set(lpfc_rq_context_hdr_size,
16295 			       &rq_create->u.request.context,
16296 			       LPFC_HDR_BUF_SIZE);
16297 			bf_set(lpfc_rq_context_rqe_count_1,
16298 			       &rq_create->u.request.context,
16299 			       hrq->entry_count);
16300 			bf_set(lpfc_rq_context_rqe_size,
16301 			       &rq_create->u.request.context,
16302 			       LPFC_RQE_SIZE_8);
16303 			bf_set(lpfc_rq_context_page_size,
16304 			       &rq_create->u.request.context,
16305 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
16306 		}
16307 		rc = 0;
16308 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
16309 			memset(dmabuf->virt, 0, hw_page_size);
16310 			cnt = page_idx + dmabuf->buffer_tag;
16311 			rq_create->u.request.page[cnt].addr_lo =
16312 					putPaddrLow(dmabuf->phys);
16313 			rq_create->u.request.page[cnt].addr_hi =
16314 					putPaddrHigh(dmabuf->phys);
16315 			rc++;
16316 		}
16317 		page_idx += rc;
16318 
16319 		rc = 0;
16320 		list_for_each_entry(dmabuf, &drq->page_list, list) {
16321 			memset(dmabuf->virt, 0, hw_page_size);
16322 			cnt = page_idx + dmabuf->buffer_tag;
16323 			rq_create->u.request.page[cnt].addr_lo =
16324 					putPaddrLow(dmabuf->phys);
16325 			rq_create->u.request.page[cnt].addr_hi =
16326 					putPaddrHigh(dmabuf->phys);
16327 			rc++;
16328 		}
16329 		page_idx += rc;
16330 
16331 		hrq->db_format = LPFC_DB_RING_FORMAT;
16332 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16333 		hrq->type = LPFC_HRQ;
16334 		hrq->assoc_qid = cq->queue_id;
16335 		hrq->subtype = subtype;
16336 		hrq->host_index = 0;
16337 		hrq->hba_index = 0;
16338 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16339 
16340 		drq->db_format = LPFC_DB_RING_FORMAT;
16341 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16342 		drq->type = LPFC_DRQ;
16343 		drq->assoc_qid = cq->queue_id;
16344 		drq->subtype = subtype;
16345 		drq->host_index = 0;
16346 		drq->hba_index = 0;
16347 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16348 
16349 		list_add_tail(&hrq->list, &cq->child_list);
16350 		list_add_tail(&drq->list, &cq->child_list);
16351 	}
16352 
16353 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16354 	/* The IOCTL status is embedded in the mailbox subheader. */
16355 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16356 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16357 	if (shdr_status || shdr_add_status || rc) {
16358 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16359 				"3120 RQ_CREATE mailbox failed with "
16360 				"status x%x add_status x%x, mbx status x%x\n",
16361 				shdr_status, shdr_add_status, rc);
16362 		status = -ENXIO;
16363 		goto out;
16364 	}
16365 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16366 	if (rc == 0xFFFF) {
16367 		status = -ENXIO;
16368 		goto out;
16369 	}
16370 
16371 	/* Initialize all RQs with associated queue id */
16372 	for (idx = 0; idx < numrq; idx++) {
16373 		hrq = hrqp[idx];
16374 		hrq->queue_id = rc + (2 * idx);
16375 		drq = drqp[idx];
16376 		drq->queue_id = rc + (2 * idx) + 1;
16377 	}
16378 
16379 out:
16380 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16381 	return status;
16382 }
16383 
16384 /**
16385  * lpfc_eq_destroy - Destroy an event Queue on the HBA
16386  * @eq: The queue structure associated with the queue to destroy.
16387  *
16388  * This function destroys a queue, as detailed in @eq by sending an mailbox
16389  * command, specific to the type of queue, to the HBA.
16390  *
16391  * The @eq struct is used to get the queue ID of the queue to destroy.
16392  *
16393  * On success this function will return a zero. If the queue destroy mailbox
16394  * command fails this function will return -ENXIO.
16395  **/
16396 int
16397 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
16398 {
16399 	LPFC_MBOXQ_t *mbox;
16400 	int rc, length, status = 0;
16401 	uint32_t shdr_status, shdr_add_status;
16402 	union lpfc_sli4_cfg_shdr *shdr;
16403 
16404 	/* sanity check on queue memory */
16405 	if (!eq)
16406 		return -ENODEV;
16407 
16408 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
16409 	if (!mbox)
16410 		return -ENOMEM;
16411 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
16412 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16413 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16414 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
16415 			 length, LPFC_SLI4_MBX_EMBED);
16416 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
16417 	       eq->queue_id);
16418 	mbox->vport = eq->phba->pport;
16419 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16420 
16421 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
16422 	/* The IOCTL status is embedded in the mailbox subheader. */
16423 	shdr = (union lpfc_sli4_cfg_shdr *)
16424 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
16425 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16426 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16427 	if (shdr_status || shdr_add_status || rc) {
16428 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16429 				"2505 EQ_DESTROY mailbox failed with "
16430 				"status x%x add_status x%x, mbx status x%x\n",
16431 				shdr_status, shdr_add_status, rc);
16432 		status = -ENXIO;
16433 	}
16434 
16435 	/* Remove eq from any list */
16436 	list_del_init(&eq->list);
16437 	mempool_free(mbox, eq->phba->mbox_mem_pool);
16438 	return status;
16439 }
16440 
16441 /**
16442  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
16443  * @cq: The queue structure associated with the queue to destroy.
16444  *
16445  * This function destroys a queue, as detailed in @cq by sending an mailbox
16446  * command, specific to the type of queue, to the HBA.
16447  *
16448  * The @cq struct is used to get the queue ID of the queue to destroy.
16449  *
16450  * On success this function will return a zero. If the queue destroy mailbox
16451  * command fails this function will return -ENXIO.
16452  **/
16453 int
16454 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
16455 {
16456 	LPFC_MBOXQ_t *mbox;
16457 	int rc, length, status = 0;
16458 	uint32_t shdr_status, shdr_add_status;
16459 	union lpfc_sli4_cfg_shdr *shdr;
16460 
16461 	/* sanity check on queue memory */
16462 	if (!cq)
16463 		return -ENODEV;
16464 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
16465 	if (!mbox)
16466 		return -ENOMEM;
16467 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
16468 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16469 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16470 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
16471 			 length, LPFC_SLI4_MBX_EMBED);
16472 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
16473 	       cq->queue_id);
16474 	mbox->vport = cq->phba->pport;
16475 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16476 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
16477 	/* The IOCTL status is embedded in the mailbox subheader. */
16478 	shdr = (union lpfc_sli4_cfg_shdr *)
16479 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
16480 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16481 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16482 	if (shdr_status || shdr_add_status || rc) {
16483 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16484 				"2506 CQ_DESTROY mailbox failed with "
16485 				"status x%x add_status x%x, mbx status x%x\n",
16486 				shdr_status, shdr_add_status, rc);
16487 		status = -ENXIO;
16488 	}
16489 	/* Remove cq from any list */
16490 	list_del_init(&cq->list);
16491 	mempool_free(mbox, cq->phba->mbox_mem_pool);
16492 	return status;
16493 }
16494 
16495 /**
16496  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
16497  * @qm: The queue structure associated with the queue to destroy.
16498  *
16499  * This function destroys a queue, as detailed in @mq by sending an mailbox
16500  * command, specific to the type of queue, to the HBA.
16501  *
16502  * The @mq struct is used to get the queue ID of the queue to destroy.
16503  *
16504  * On success this function will return a zero. If the queue destroy mailbox
16505  * command fails this function will return -ENXIO.
16506  **/
16507 int
16508 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
16509 {
16510 	LPFC_MBOXQ_t *mbox;
16511 	int rc, length, status = 0;
16512 	uint32_t shdr_status, shdr_add_status;
16513 	union lpfc_sli4_cfg_shdr *shdr;
16514 
16515 	/* sanity check on queue memory */
16516 	if (!mq)
16517 		return -ENODEV;
16518 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
16519 	if (!mbox)
16520 		return -ENOMEM;
16521 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
16522 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16523 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16524 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
16525 			 length, LPFC_SLI4_MBX_EMBED);
16526 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
16527 	       mq->queue_id);
16528 	mbox->vport = mq->phba->pport;
16529 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16530 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
16531 	/* The IOCTL status is embedded in the mailbox subheader. */
16532 	shdr = (union lpfc_sli4_cfg_shdr *)
16533 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
16534 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16535 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16536 	if (shdr_status || shdr_add_status || rc) {
16537 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16538 				"2507 MQ_DESTROY mailbox failed with "
16539 				"status x%x add_status x%x, mbx status x%x\n",
16540 				shdr_status, shdr_add_status, rc);
16541 		status = -ENXIO;
16542 	}
16543 	/* Remove mq from any list */
16544 	list_del_init(&mq->list);
16545 	mempool_free(mbox, mq->phba->mbox_mem_pool);
16546 	return status;
16547 }
16548 
16549 /**
16550  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
16551  * @wq: The queue structure associated with the queue to destroy.
16552  *
16553  * This function destroys a queue, as detailed in @wq by sending an mailbox
16554  * command, specific to the type of queue, to the HBA.
16555  *
16556  * The @wq struct is used to get the queue ID of the queue to destroy.
16557  *
16558  * On success this function will return a zero. If the queue destroy mailbox
16559  * command fails this function will return -ENXIO.
16560  **/
16561 int
16562 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
16563 {
16564 	LPFC_MBOXQ_t *mbox;
16565 	int rc, length, status = 0;
16566 	uint32_t shdr_status, shdr_add_status;
16567 	union lpfc_sli4_cfg_shdr *shdr;
16568 
16569 	/* sanity check on queue memory */
16570 	if (!wq)
16571 		return -ENODEV;
16572 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
16573 	if (!mbox)
16574 		return -ENOMEM;
16575 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
16576 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16577 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16578 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
16579 			 length, LPFC_SLI4_MBX_EMBED);
16580 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
16581 	       wq->queue_id);
16582 	mbox->vport = wq->phba->pport;
16583 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16584 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
16585 	shdr = (union lpfc_sli4_cfg_shdr *)
16586 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
16587 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16588 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16589 	if (shdr_status || shdr_add_status || rc) {
16590 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16591 				"2508 WQ_DESTROY mailbox failed with "
16592 				"status x%x add_status x%x, mbx status x%x\n",
16593 				shdr_status, shdr_add_status, rc);
16594 		status = -ENXIO;
16595 	}
16596 	/* Remove wq from any list */
16597 	list_del_init(&wq->list);
16598 	kfree(wq->pring);
16599 	wq->pring = NULL;
16600 	mempool_free(mbox, wq->phba->mbox_mem_pool);
16601 	return status;
16602 }
16603 
16604 /**
16605  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
16606  * @rq: The queue structure associated with the queue to destroy.
16607  *
16608  * This function destroys a queue, as detailed in @rq by sending an mailbox
16609  * command, specific to the type of queue, to the HBA.
16610  *
16611  * The @rq struct is used to get the queue ID of the queue to destroy.
16612  *
16613  * On success this function will return a zero. If the queue destroy mailbox
16614  * command fails this function will return -ENXIO.
16615  **/
16616 int
16617 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
16618 		struct lpfc_queue *drq)
16619 {
16620 	LPFC_MBOXQ_t *mbox;
16621 	int rc, length, status = 0;
16622 	uint32_t shdr_status, shdr_add_status;
16623 	union lpfc_sli4_cfg_shdr *shdr;
16624 
16625 	/* sanity check on queue memory */
16626 	if (!hrq || !drq)
16627 		return -ENODEV;
16628 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
16629 	if (!mbox)
16630 		return -ENOMEM;
16631 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
16632 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16633 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16634 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
16635 			 length, LPFC_SLI4_MBX_EMBED);
16636 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
16637 	       hrq->queue_id);
16638 	mbox->vport = hrq->phba->pport;
16639 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16640 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
16641 	/* The IOCTL status is embedded in the mailbox subheader. */
16642 	shdr = (union lpfc_sli4_cfg_shdr *)
16643 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
16644 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16645 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16646 	if (shdr_status || shdr_add_status || rc) {
16647 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16648 				"2509 RQ_DESTROY mailbox failed with "
16649 				"status x%x add_status x%x, mbx status x%x\n",
16650 				shdr_status, shdr_add_status, rc);
16651 		if (rc != MBX_TIMEOUT)
16652 			mempool_free(mbox, hrq->phba->mbox_mem_pool);
16653 		return -ENXIO;
16654 	}
16655 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
16656 	       drq->queue_id);
16657 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
16658 	shdr = (union lpfc_sli4_cfg_shdr *)
16659 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
16660 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16661 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16662 	if (shdr_status || shdr_add_status || rc) {
16663 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16664 				"2510 RQ_DESTROY mailbox failed with "
16665 				"status x%x add_status x%x, mbx status x%x\n",
16666 				shdr_status, shdr_add_status, rc);
16667 		status = -ENXIO;
16668 	}
16669 	list_del_init(&hrq->list);
16670 	list_del_init(&drq->list);
16671 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
16672 	return status;
16673 }
16674 
16675 /**
16676  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
16677  * @phba: The virtual port for which this call being executed.
16678  * @pdma_phys_addr0: Physical address of the 1st SGL page.
16679  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
16680  * @xritag: the xritag that ties this io to the SGL pages.
16681  *
16682  * This routine will post the sgl pages for the IO that has the xritag
16683  * that is in the iocbq structure. The xritag is assigned during iocbq
16684  * creation and persists for as long as the driver is loaded.
16685  * if the caller has fewer than 256 scatter gather segments to map then
16686  * pdma_phys_addr1 should be 0.
16687  * If the caller needs to map more than 256 scatter gather segment then
16688  * pdma_phys_addr1 should be a valid physical address.
16689  * physical address for SGLs must be 64 byte aligned.
16690  * If you are going to map 2 SGL's then the first one must have 256 entries
16691  * the second sgl can have between 1 and 256 entries.
16692  *
16693  * Return codes:
16694  * 	0 - Success
16695  * 	-ENXIO, -ENOMEM - Failure
16696  **/
16697 int
16698 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
16699 		dma_addr_t pdma_phys_addr0,
16700 		dma_addr_t pdma_phys_addr1,
16701 		uint16_t xritag)
16702 {
16703 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
16704 	LPFC_MBOXQ_t *mbox;
16705 	int rc;
16706 	uint32_t shdr_status, shdr_add_status;
16707 	uint32_t mbox_tmo;
16708 	union lpfc_sli4_cfg_shdr *shdr;
16709 
16710 	if (xritag == NO_XRI) {
16711 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16712 				"0364 Invalid param:\n");
16713 		return -EINVAL;
16714 	}
16715 
16716 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16717 	if (!mbox)
16718 		return -ENOMEM;
16719 
16720 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16721 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
16722 			sizeof(struct lpfc_mbx_post_sgl_pages) -
16723 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
16724 
16725 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
16726 				&mbox->u.mqe.un.post_sgl_pages;
16727 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
16728 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
16729 
16730 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
16731 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
16732 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
16733 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
16734 
16735 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
16736 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
16737 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
16738 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
16739 	if (!phba->sli4_hba.intr_enable)
16740 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16741 	else {
16742 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16743 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16744 	}
16745 	/* The IOCTL status is embedded in the mailbox subheader. */
16746 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
16747 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16748 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16749 	if (rc != MBX_TIMEOUT)
16750 		mempool_free(mbox, phba->mbox_mem_pool);
16751 	if (shdr_status || shdr_add_status || rc) {
16752 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16753 				"2511 POST_SGL mailbox failed with "
16754 				"status x%x add_status x%x, mbx status x%x\n",
16755 				shdr_status, shdr_add_status, rc);
16756 	}
16757 	return 0;
16758 }
16759 
16760 /**
16761  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
16762  * @phba: pointer to lpfc hba data structure.
16763  *
16764  * This routine is invoked to post rpi header templates to the
16765  * HBA consistent with the SLI-4 interface spec.  This routine
16766  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
16767  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
16768  *
16769  * Returns
16770  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
16771  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
16772  **/
16773 static uint16_t
16774 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
16775 {
16776 	unsigned long xri;
16777 
16778 	/*
16779 	 * Fetch the next logical xri.  Because this index is logical,
16780 	 * the driver starts at 0 each time.
16781 	 */
16782 	spin_lock_irq(&phba->hbalock);
16783 	xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
16784 				 phba->sli4_hba.max_cfg_param.max_xri, 0);
16785 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
16786 		spin_unlock_irq(&phba->hbalock);
16787 		return NO_XRI;
16788 	} else {
16789 		set_bit(xri, phba->sli4_hba.xri_bmask);
16790 		phba->sli4_hba.max_cfg_param.xri_used++;
16791 	}
16792 	spin_unlock_irq(&phba->hbalock);
16793 	return xri;
16794 }
16795 
16796 /**
16797  * lpfc_sli4_free_xri - Release an xri for reuse.
16798  * @phba: pointer to lpfc hba data structure.
16799  *
16800  * This routine is invoked to release an xri to the pool of
16801  * available rpis maintained by the driver.
16802  **/
16803 static void
16804 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
16805 {
16806 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
16807 		phba->sli4_hba.max_cfg_param.xri_used--;
16808 	}
16809 }
16810 
16811 /**
16812  * lpfc_sli4_free_xri - Release an xri for reuse.
16813  * @phba: pointer to lpfc hba data structure.
16814  *
16815  * This routine is invoked to release an xri to the pool of
16816  * available rpis maintained by the driver.
16817  **/
16818 void
16819 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
16820 {
16821 	spin_lock_irq(&phba->hbalock);
16822 	__lpfc_sli4_free_xri(phba, xri);
16823 	spin_unlock_irq(&phba->hbalock);
16824 }
16825 
16826 /**
16827  * lpfc_sli4_next_xritag - Get an xritag for the io
16828  * @phba: Pointer to HBA context object.
16829  *
16830  * This function gets an xritag for the iocb. If there is no unused xritag
16831  * it will return 0xffff.
16832  * The function returns the allocated xritag if successful, else returns zero.
16833  * Zero is not a valid xritag.
16834  * The caller is not required to hold any lock.
16835  **/
16836 uint16_t
16837 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
16838 {
16839 	uint16_t xri_index;
16840 
16841 	xri_index = lpfc_sli4_alloc_xri(phba);
16842 	if (xri_index == NO_XRI)
16843 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
16844 				"2004 Failed to allocate XRI.last XRITAG is %d"
16845 				" Max XRI is %d, Used XRI is %d\n",
16846 				xri_index,
16847 				phba->sli4_hba.max_cfg_param.max_xri,
16848 				phba->sli4_hba.max_cfg_param.xri_used);
16849 	return xri_index;
16850 }
16851 
16852 /**
16853  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
16854  * @phba: pointer to lpfc hba data structure.
16855  * @post_sgl_list: pointer to els sgl entry list.
16856  * @count: number of els sgl entries on the list.
16857  *
16858  * This routine is invoked to post a block of driver's sgl pages to the
16859  * HBA using non-embedded mailbox command. No Lock is held. This routine
16860  * is only called when the driver is loading and after all IO has been
16861  * stopped.
16862  **/
16863 static int
16864 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
16865 			    struct list_head *post_sgl_list,
16866 			    int post_cnt)
16867 {
16868 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
16869 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
16870 	struct sgl_page_pairs *sgl_pg_pairs;
16871 	void *viraddr;
16872 	LPFC_MBOXQ_t *mbox;
16873 	uint32_t reqlen, alloclen, pg_pairs;
16874 	uint32_t mbox_tmo;
16875 	uint16_t xritag_start = 0;
16876 	int rc = 0;
16877 	uint32_t shdr_status, shdr_add_status;
16878 	union lpfc_sli4_cfg_shdr *shdr;
16879 
16880 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
16881 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
16882 	if (reqlen > SLI4_PAGE_SIZE) {
16883 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16884 				"2559 Block sgl registration required DMA "
16885 				"size (%d) great than a page\n", reqlen);
16886 		return -ENOMEM;
16887 	}
16888 
16889 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16890 	if (!mbox)
16891 		return -ENOMEM;
16892 
16893 	/* Allocate DMA memory and set up the non-embedded mailbox command */
16894 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16895 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
16896 			 LPFC_SLI4_MBX_NEMBED);
16897 
16898 	if (alloclen < reqlen) {
16899 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16900 				"0285 Allocated DMA memory size (%d) is "
16901 				"less than the requested DMA memory "
16902 				"size (%d)\n", alloclen, reqlen);
16903 		lpfc_sli4_mbox_cmd_free(phba, mbox);
16904 		return -ENOMEM;
16905 	}
16906 	/* Set up the SGL pages in the non-embedded DMA pages */
16907 	viraddr = mbox->sge_array->addr[0];
16908 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
16909 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
16910 
16911 	pg_pairs = 0;
16912 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
16913 		/* Set up the sge entry */
16914 		sgl_pg_pairs->sgl_pg0_addr_lo =
16915 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
16916 		sgl_pg_pairs->sgl_pg0_addr_hi =
16917 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
16918 		sgl_pg_pairs->sgl_pg1_addr_lo =
16919 				cpu_to_le32(putPaddrLow(0));
16920 		sgl_pg_pairs->sgl_pg1_addr_hi =
16921 				cpu_to_le32(putPaddrHigh(0));
16922 
16923 		/* Keep the first xritag on the list */
16924 		if (pg_pairs == 0)
16925 			xritag_start = sglq_entry->sli4_xritag;
16926 		sgl_pg_pairs++;
16927 		pg_pairs++;
16928 	}
16929 
16930 	/* Complete initialization and perform endian conversion. */
16931 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
16932 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
16933 	sgl->word0 = cpu_to_le32(sgl->word0);
16934 
16935 	if (!phba->sli4_hba.intr_enable)
16936 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16937 	else {
16938 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16939 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16940 	}
16941 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
16942 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16943 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16944 	if (rc != MBX_TIMEOUT)
16945 		lpfc_sli4_mbox_cmd_free(phba, mbox);
16946 	if (shdr_status || shdr_add_status || rc) {
16947 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16948 				"2513 POST_SGL_BLOCK mailbox command failed "
16949 				"status x%x add_status x%x mbx status x%x\n",
16950 				shdr_status, shdr_add_status, rc);
16951 		rc = -ENXIO;
16952 	}
16953 	return rc;
16954 }
16955 
16956 /**
16957  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
16958  * @phba: pointer to lpfc hba data structure.
16959  * @nblist: pointer to nvme buffer list.
16960  * @count: number of scsi buffers on the list.
16961  *
16962  * This routine is invoked to post a block of @count scsi sgl pages from a
16963  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
16964  * No Lock is held.
16965  *
16966  **/
16967 static int
16968 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
16969 			    int count)
16970 {
16971 	struct lpfc_io_buf *lpfc_ncmd;
16972 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
16973 	struct sgl_page_pairs *sgl_pg_pairs;
16974 	void *viraddr;
16975 	LPFC_MBOXQ_t *mbox;
16976 	uint32_t reqlen, alloclen, pg_pairs;
16977 	uint32_t mbox_tmo;
16978 	uint16_t xritag_start = 0;
16979 	int rc = 0;
16980 	uint32_t shdr_status, shdr_add_status;
16981 	dma_addr_t pdma_phys_bpl1;
16982 	union lpfc_sli4_cfg_shdr *shdr;
16983 
16984 	/* Calculate the requested length of the dma memory */
16985 	reqlen = count * sizeof(struct sgl_page_pairs) +
16986 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
16987 	if (reqlen > SLI4_PAGE_SIZE) {
16988 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
16989 				"6118 Block sgl registration required DMA "
16990 				"size (%d) great than a page\n", reqlen);
16991 		return -ENOMEM;
16992 	}
16993 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16994 	if (!mbox) {
16995 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16996 				"6119 Failed to allocate mbox cmd memory\n");
16997 		return -ENOMEM;
16998 	}
16999 
17000 	/* Allocate DMA memory and set up the non-embedded mailbox command */
17001 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17002 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17003 				    reqlen, LPFC_SLI4_MBX_NEMBED);
17004 
17005 	if (alloclen < reqlen) {
17006 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17007 				"6120 Allocated DMA memory size (%d) is "
17008 				"less than the requested DMA memory "
17009 				"size (%d)\n", alloclen, reqlen);
17010 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17011 		return -ENOMEM;
17012 	}
17013 
17014 	/* Get the first SGE entry from the non-embedded DMA memory */
17015 	viraddr = mbox->sge_array->addr[0];
17016 
17017 	/* Set up the SGL pages in the non-embedded DMA pages */
17018 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
17019 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
17020 
17021 	pg_pairs = 0;
17022 	list_for_each_entry(lpfc_ncmd, nblist, list) {
17023 		/* Set up the sge entry */
17024 		sgl_pg_pairs->sgl_pg0_addr_lo =
17025 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
17026 		sgl_pg_pairs->sgl_pg0_addr_hi =
17027 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
17028 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
17029 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
17030 						SGL_PAGE_SIZE;
17031 		else
17032 			pdma_phys_bpl1 = 0;
17033 		sgl_pg_pairs->sgl_pg1_addr_lo =
17034 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
17035 		sgl_pg_pairs->sgl_pg1_addr_hi =
17036 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
17037 		/* Keep the first xritag on the list */
17038 		if (pg_pairs == 0)
17039 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
17040 		sgl_pg_pairs++;
17041 		pg_pairs++;
17042 	}
17043 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
17044 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
17045 	/* Perform endian conversion if necessary */
17046 	sgl->word0 = cpu_to_le32(sgl->word0);
17047 
17048 	if (!phba->sli4_hba.intr_enable) {
17049 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17050 	} else {
17051 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17052 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17053 	}
17054 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
17055 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17056 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17057 	if (rc != MBX_TIMEOUT)
17058 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17059 	if (shdr_status || shdr_add_status || rc) {
17060 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17061 				"6125 POST_SGL_BLOCK mailbox command failed "
17062 				"status x%x add_status x%x mbx status x%x\n",
17063 				shdr_status, shdr_add_status, rc);
17064 		rc = -ENXIO;
17065 	}
17066 	return rc;
17067 }
17068 
17069 /**
17070  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
17071  * @phba: pointer to lpfc hba data structure.
17072  * @post_nblist: pointer to the nvme buffer list.
17073  *
17074  * This routine walks a list of nvme buffers that was passed in. It attempts
17075  * to construct blocks of nvme buffer sgls which contains contiguous xris and
17076  * uses the non-embedded SGL block post mailbox commands to post to the port.
17077  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
17078  * embedded SGL post mailbox command for posting. The @post_nblist passed in
17079  * must be local list, thus no lock is needed when manipulate the list.
17080  *
17081  * Returns: 0 = failure, non-zero number of successfully posted buffers.
17082  **/
17083 int
17084 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
17085 			   struct list_head *post_nblist, int sb_count)
17086 {
17087 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
17088 	int status, sgl_size;
17089 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
17090 	dma_addr_t pdma_phys_sgl1;
17091 	int last_xritag = NO_XRI;
17092 	int cur_xritag;
17093 	LIST_HEAD(prep_nblist);
17094 	LIST_HEAD(blck_nblist);
17095 	LIST_HEAD(nvme_nblist);
17096 
17097 	/* sanity check */
17098 	if (sb_count <= 0)
17099 		return -EINVAL;
17100 
17101 	sgl_size = phba->cfg_sg_dma_buf_size;
17102 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
17103 		list_del_init(&lpfc_ncmd->list);
17104 		block_cnt++;
17105 		if ((last_xritag != NO_XRI) &&
17106 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
17107 			/* a hole in xri block, form a sgl posting block */
17108 			list_splice_init(&prep_nblist, &blck_nblist);
17109 			post_cnt = block_cnt - 1;
17110 			/* prepare list for next posting block */
17111 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17112 			block_cnt = 1;
17113 		} else {
17114 			/* prepare list for next posting block */
17115 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17116 			/* enough sgls for non-embed sgl mbox command */
17117 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
17118 				list_splice_init(&prep_nblist, &blck_nblist);
17119 				post_cnt = block_cnt;
17120 				block_cnt = 0;
17121 			}
17122 		}
17123 		num_posting++;
17124 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17125 
17126 		/* end of repost sgl list condition for NVME buffers */
17127 		if (num_posting == sb_count) {
17128 			if (post_cnt == 0) {
17129 				/* last sgl posting block */
17130 				list_splice_init(&prep_nblist, &blck_nblist);
17131 				post_cnt = block_cnt;
17132 			} else if (block_cnt == 1) {
17133 				/* last single sgl with non-contiguous xri */
17134 				if (sgl_size > SGL_PAGE_SIZE)
17135 					pdma_phys_sgl1 =
17136 						lpfc_ncmd->dma_phys_sgl +
17137 						SGL_PAGE_SIZE;
17138 				else
17139 					pdma_phys_sgl1 = 0;
17140 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17141 				status = lpfc_sli4_post_sgl(
17142 						phba, lpfc_ncmd->dma_phys_sgl,
17143 						pdma_phys_sgl1, cur_xritag);
17144 				if (status) {
17145 					/* Post error.  Buffer unavailable. */
17146 					lpfc_ncmd->flags |=
17147 						LPFC_SBUF_NOT_POSTED;
17148 				} else {
17149 					/* Post success. Bffer available. */
17150 					lpfc_ncmd->flags &=
17151 						~LPFC_SBUF_NOT_POSTED;
17152 					lpfc_ncmd->status = IOSTAT_SUCCESS;
17153 					num_posted++;
17154 				}
17155 				/* success, put on NVME buffer sgl list */
17156 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17157 			}
17158 		}
17159 
17160 		/* continue until a nembed page worth of sgls */
17161 		if (post_cnt == 0)
17162 			continue;
17163 
17164 		/* post block of NVME buffer list sgls */
17165 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
17166 						     post_cnt);
17167 
17168 		/* don't reset xirtag due to hole in xri block */
17169 		if (block_cnt == 0)
17170 			last_xritag = NO_XRI;
17171 
17172 		/* reset NVME buffer post count for next round of posting */
17173 		post_cnt = 0;
17174 
17175 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
17176 		while (!list_empty(&blck_nblist)) {
17177 			list_remove_head(&blck_nblist, lpfc_ncmd,
17178 					 struct lpfc_io_buf, list);
17179 			if (status) {
17180 				/* Post error.  Mark buffer unavailable. */
17181 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
17182 			} else {
17183 				/* Post success, Mark buffer available. */
17184 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
17185 				lpfc_ncmd->status = IOSTAT_SUCCESS;
17186 				num_posted++;
17187 			}
17188 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17189 		}
17190 	}
17191 	/* Push NVME buffers with sgl posted to the available list */
17192 	lpfc_io_buf_replenish(phba, &nvme_nblist);
17193 
17194 	return num_posted;
17195 }
17196 
17197 /**
17198  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
17199  * @phba: pointer to lpfc_hba struct that the frame was received on
17200  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17201  *
17202  * This function checks the fields in the @fc_hdr to see if the FC frame is a
17203  * valid type of frame that the LPFC driver will handle. This function will
17204  * return a zero if the frame is a valid frame or a non zero value when the
17205  * frame does not pass the check.
17206  **/
17207 static int
17208 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
17209 {
17210 	/*  make rctl_names static to save stack space */
17211 	struct fc_vft_header *fc_vft_hdr;
17212 	uint32_t *header = (uint32_t *) fc_hdr;
17213 
17214 #define FC_RCTL_MDS_DIAGS	0xF4
17215 
17216 	switch (fc_hdr->fh_r_ctl) {
17217 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
17218 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
17219 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
17220 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
17221 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
17222 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
17223 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
17224 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
17225 	case FC_RCTL_ELS_REQ:	/* extended link services request */
17226 	case FC_RCTL_ELS_REP:	/* extended link services reply */
17227 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
17228 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
17229 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
17230 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
17231 	case FC_RCTL_BA_RMC: 	/* remove connection */
17232 	case FC_RCTL_BA_ACC:	/* basic accept */
17233 	case FC_RCTL_BA_RJT:	/* basic reject */
17234 	case FC_RCTL_BA_PRMT:
17235 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
17236 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
17237 	case FC_RCTL_P_RJT:	/* port reject */
17238 	case FC_RCTL_F_RJT:	/* fabric reject */
17239 	case FC_RCTL_P_BSY:	/* port busy */
17240 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
17241 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
17242 	case FC_RCTL_LCR:	/* link credit reset */
17243 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
17244 	case FC_RCTL_END:	/* end */
17245 		break;
17246 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
17247 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17248 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
17249 		return lpfc_fc_frame_check(phba, fc_hdr);
17250 	default:
17251 		goto drop;
17252 	}
17253 
17254 	switch (fc_hdr->fh_type) {
17255 	case FC_TYPE_BLS:
17256 	case FC_TYPE_ELS:
17257 	case FC_TYPE_FCP:
17258 	case FC_TYPE_CT:
17259 	case FC_TYPE_NVME:
17260 		break;
17261 	case FC_TYPE_IP:
17262 	case FC_TYPE_ILS:
17263 	default:
17264 		goto drop;
17265 	}
17266 
17267 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
17268 			"2538 Received frame rctl:x%x, type:x%x, "
17269 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
17270 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
17271 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
17272 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
17273 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
17274 			be32_to_cpu(header[6]));
17275 	return 0;
17276 drop:
17277 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
17278 			"2539 Dropped frame rctl:x%x type:x%x\n",
17279 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17280 	return 1;
17281 }
17282 
17283 /**
17284  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
17285  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17286  *
17287  * This function processes the FC header to retrieve the VFI from the VF
17288  * header, if one exists. This function will return the VFI if one exists
17289  * or 0 if no VSAN Header exists.
17290  **/
17291 static uint32_t
17292 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
17293 {
17294 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17295 
17296 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
17297 		return 0;
17298 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
17299 }
17300 
17301 /**
17302  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
17303  * @phba: Pointer to the HBA structure to search for the vport on
17304  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17305  * @fcfi: The FC Fabric ID that the frame came from
17306  *
17307  * This function searches the @phba for a vport that matches the content of the
17308  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
17309  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
17310  * returns the matching vport pointer or NULL if unable to match frame to a
17311  * vport.
17312  **/
17313 static struct lpfc_vport *
17314 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
17315 		       uint16_t fcfi, uint32_t did)
17316 {
17317 	struct lpfc_vport **vports;
17318 	struct lpfc_vport *vport = NULL;
17319 	int i;
17320 
17321 	if (did == Fabric_DID)
17322 		return phba->pport;
17323 	if ((phba->pport->fc_flag & FC_PT2PT) &&
17324 		!(phba->link_state == LPFC_HBA_READY))
17325 		return phba->pport;
17326 
17327 	vports = lpfc_create_vport_work_array(phba);
17328 	if (vports != NULL) {
17329 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
17330 			if (phba->fcf.fcfi == fcfi &&
17331 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
17332 			    vports[i]->fc_myDID == did) {
17333 				vport = vports[i];
17334 				break;
17335 			}
17336 		}
17337 	}
17338 	lpfc_destroy_vport_work_array(phba, vports);
17339 	return vport;
17340 }
17341 
17342 /**
17343  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
17344  * @vport: The vport to work on.
17345  *
17346  * This function updates the receive sequence time stamp for this vport. The
17347  * receive sequence time stamp indicates the time that the last frame of the
17348  * the sequence that has been idle for the longest amount of time was received.
17349  * the driver uses this time stamp to indicate if any received sequences have
17350  * timed out.
17351  **/
17352 static void
17353 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
17354 {
17355 	struct lpfc_dmabuf *h_buf;
17356 	struct hbq_dmabuf *dmabuf = NULL;
17357 
17358 	/* get the oldest sequence on the rcv list */
17359 	h_buf = list_get_first(&vport->rcv_buffer_list,
17360 			       struct lpfc_dmabuf, list);
17361 	if (!h_buf)
17362 		return;
17363 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17364 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
17365 }
17366 
17367 /**
17368  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
17369  * @vport: The vport that the received sequences were sent to.
17370  *
17371  * This function cleans up all outstanding received sequences. This is called
17372  * by the driver when a link event or user action invalidates all the received
17373  * sequences.
17374  **/
17375 void
17376 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
17377 {
17378 	struct lpfc_dmabuf *h_buf, *hnext;
17379 	struct lpfc_dmabuf *d_buf, *dnext;
17380 	struct hbq_dmabuf *dmabuf = NULL;
17381 
17382 	/* start with the oldest sequence on the rcv list */
17383 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17384 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17385 		list_del_init(&dmabuf->hbuf.list);
17386 		list_for_each_entry_safe(d_buf, dnext,
17387 					 &dmabuf->dbuf.list, list) {
17388 			list_del_init(&d_buf->list);
17389 			lpfc_in_buf_free(vport->phba, d_buf);
17390 		}
17391 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17392 	}
17393 }
17394 
17395 /**
17396  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
17397  * @vport: The vport that the received sequences were sent to.
17398  *
17399  * This function determines whether any received sequences have timed out by
17400  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
17401  * indicates that there is at least one timed out sequence this routine will
17402  * go through the received sequences one at a time from most inactive to most
17403  * active to determine which ones need to be cleaned up. Once it has determined
17404  * that a sequence needs to be cleaned up it will simply free up the resources
17405  * without sending an abort.
17406  **/
17407 void
17408 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
17409 {
17410 	struct lpfc_dmabuf *h_buf, *hnext;
17411 	struct lpfc_dmabuf *d_buf, *dnext;
17412 	struct hbq_dmabuf *dmabuf = NULL;
17413 	unsigned long timeout;
17414 	int abort_count = 0;
17415 
17416 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17417 		   vport->rcv_buffer_time_stamp);
17418 	if (list_empty(&vport->rcv_buffer_list) ||
17419 	    time_before(jiffies, timeout))
17420 		return;
17421 	/* start with the oldest sequence on the rcv list */
17422 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17423 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17424 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17425 			   dmabuf->time_stamp);
17426 		if (time_before(jiffies, timeout))
17427 			break;
17428 		abort_count++;
17429 		list_del_init(&dmabuf->hbuf.list);
17430 		list_for_each_entry_safe(d_buf, dnext,
17431 					 &dmabuf->dbuf.list, list) {
17432 			list_del_init(&d_buf->list);
17433 			lpfc_in_buf_free(vport->phba, d_buf);
17434 		}
17435 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17436 	}
17437 	if (abort_count)
17438 		lpfc_update_rcv_time_stamp(vport);
17439 }
17440 
17441 /**
17442  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
17443  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
17444  *
17445  * This function searches through the existing incomplete sequences that have
17446  * been sent to this @vport. If the frame matches one of the incomplete
17447  * sequences then the dbuf in the @dmabuf is added to the list of frames that
17448  * make up that sequence. If no sequence is found that matches this frame then
17449  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
17450  * This function returns a pointer to the first dmabuf in the sequence list that
17451  * the frame was linked to.
17452  **/
17453 static struct hbq_dmabuf *
17454 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
17455 {
17456 	struct fc_frame_header *new_hdr;
17457 	struct fc_frame_header *temp_hdr;
17458 	struct lpfc_dmabuf *d_buf;
17459 	struct lpfc_dmabuf *h_buf;
17460 	struct hbq_dmabuf *seq_dmabuf = NULL;
17461 	struct hbq_dmabuf *temp_dmabuf = NULL;
17462 	uint8_t	found = 0;
17463 
17464 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
17465 	dmabuf->time_stamp = jiffies;
17466 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17467 
17468 	/* Use the hdr_buf to find the sequence that this frame belongs to */
17469 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
17470 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
17471 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
17472 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
17473 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
17474 			continue;
17475 		/* found a pending sequence that matches this frame */
17476 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17477 		break;
17478 	}
17479 	if (!seq_dmabuf) {
17480 		/*
17481 		 * This indicates first frame received for this sequence.
17482 		 * Queue the buffer on the vport's rcv_buffer_list.
17483 		 */
17484 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17485 		lpfc_update_rcv_time_stamp(vport);
17486 		return dmabuf;
17487 	}
17488 	temp_hdr = seq_dmabuf->hbuf.virt;
17489 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
17490 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17491 		list_del_init(&seq_dmabuf->hbuf.list);
17492 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17493 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17494 		lpfc_update_rcv_time_stamp(vport);
17495 		return dmabuf;
17496 	}
17497 	/* move this sequence to the tail to indicate a young sequence */
17498 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
17499 	seq_dmabuf->time_stamp = jiffies;
17500 	lpfc_update_rcv_time_stamp(vport);
17501 	if (list_empty(&seq_dmabuf->dbuf.list)) {
17502 		temp_hdr = dmabuf->hbuf.virt;
17503 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17504 		return seq_dmabuf;
17505 	}
17506 	/* find the correct place in the sequence to insert this frame */
17507 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
17508 	while (!found) {
17509 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17510 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
17511 		/*
17512 		 * If the frame's sequence count is greater than the frame on
17513 		 * the list then insert the frame right after this frame
17514 		 */
17515 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
17516 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17517 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
17518 			found = 1;
17519 			break;
17520 		}
17521 
17522 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
17523 			break;
17524 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
17525 	}
17526 
17527 	if (found)
17528 		return seq_dmabuf;
17529 	return NULL;
17530 }
17531 
17532 /**
17533  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
17534  * @vport: pointer to a vitural port
17535  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17536  *
17537  * This function tries to abort from the partially assembed sequence, described
17538  * by the information from basic abbort @dmabuf. It checks to see whether such
17539  * partially assembled sequence held by the driver. If so, it shall free up all
17540  * the frames from the partially assembled sequence.
17541  *
17542  * Return
17543  * true  -- if there is matching partially assembled sequence present and all
17544  *          the frames freed with the sequence;
17545  * false -- if there is no matching partially assembled sequence present so
17546  *          nothing got aborted in the lower layer driver
17547  **/
17548 static bool
17549 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
17550 			    struct hbq_dmabuf *dmabuf)
17551 {
17552 	struct fc_frame_header *new_hdr;
17553 	struct fc_frame_header *temp_hdr;
17554 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
17555 	struct hbq_dmabuf *seq_dmabuf = NULL;
17556 
17557 	/* Use the hdr_buf to find the sequence that matches this frame */
17558 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
17559 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
17560 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17561 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
17562 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
17563 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
17564 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
17565 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
17566 			continue;
17567 		/* found a pending sequence that matches this frame */
17568 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17569 		break;
17570 	}
17571 
17572 	/* Free up all the frames from the partially assembled sequence */
17573 	if (seq_dmabuf) {
17574 		list_for_each_entry_safe(d_buf, n_buf,
17575 					 &seq_dmabuf->dbuf.list, list) {
17576 			list_del_init(&d_buf->list);
17577 			lpfc_in_buf_free(vport->phba, d_buf);
17578 		}
17579 		return true;
17580 	}
17581 	return false;
17582 }
17583 
17584 /**
17585  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
17586  * @vport: pointer to a vitural port
17587  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17588  *
17589  * This function tries to abort from the assembed sequence from upper level
17590  * protocol, described by the information from basic abbort @dmabuf. It
17591  * checks to see whether such pending context exists at upper level protocol.
17592  * If so, it shall clean up the pending context.
17593  *
17594  * Return
17595  * true  -- if there is matching pending context of the sequence cleaned
17596  *          at ulp;
17597  * false -- if there is no matching pending context of the sequence present
17598  *          at ulp.
17599  **/
17600 static bool
17601 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
17602 {
17603 	struct lpfc_hba *phba = vport->phba;
17604 	int handled;
17605 
17606 	/* Accepting abort at ulp with SLI4 only */
17607 	if (phba->sli_rev < LPFC_SLI_REV4)
17608 		return false;
17609 
17610 	/* Register all caring upper level protocols to attend abort */
17611 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
17612 	if (handled)
17613 		return true;
17614 
17615 	return false;
17616 }
17617 
17618 /**
17619  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
17620  * @phba: Pointer to HBA context object.
17621  * @cmd_iocbq: pointer to the command iocbq structure.
17622  * @rsp_iocbq: pointer to the response iocbq structure.
17623  *
17624  * This function handles the sequence abort response iocb command complete
17625  * event. It properly releases the memory allocated to the sequence abort
17626  * accept iocb.
17627  **/
17628 static void
17629 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
17630 			     struct lpfc_iocbq *cmd_iocbq,
17631 			     struct lpfc_iocbq *rsp_iocbq)
17632 {
17633 	struct lpfc_nodelist *ndlp;
17634 
17635 	if (cmd_iocbq) {
17636 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
17637 		lpfc_nlp_put(ndlp);
17638 		lpfc_nlp_not_used(ndlp);
17639 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
17640 	}
17641 
17642 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
17643 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
17644 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17645 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
17646 			rsp_iocbq->iocb.ulpStatus,
17647 			rsp_iocbq->iocb.un.ulpWord[4]);
17648 }
17649 
17650 /**
17651  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
17652  * @phba: Pointer to HBA context object.
17653  * @xri: xri id in transaction.
17654  *
17655  * This function validates the xri maps to the known range of XRIs allocated an
17656  * used by the driver.
17657  **/
17658 uint16_t
17659 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
17660 		      uint16_t xri)
17661 {
17662 	uint16_t i;
17663 
17664 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
17665 		if (xri == phba->sli4_hba.xri_ids[i])
17666 			return i;
17667 	}
17668 	return NO_XRI;
17669 }
17670 
17671 /**
17672  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
17673  * @phba: Pointer to HBA context object.
17674  * @fc_hdr: pointer to a FC frame header.
17675  *
17676  * This function sends a basic response to a previous unsol sequence abort
17677  * event after aborting the sequence handling.
17678  **/
17679 void
17680 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
17681 			struct fc_frame_header *fc_hdr, bool aborted)
17682 {
17683 	struct lpfc_hba *phba = vport->phba;
17684 	struct lpfc_iocbq *ctiocb = NULL;
17685 	struct lpfc_nodelist *ndlp;
17686 	uint16_t oxid, rxid, xri, lxri;
17687 	uint32_t sid, fctl;
17688 	IOCB_t *icmd;
17689 	int rc;
17690 
17691 	if (!lpfc_is_link_up(phba))
17692 		return;
17693 
17694 	sid = sli4_sid_from_fc_hdr(fc_hdr);
17695 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
17696 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
17697 
17698 	ndlp = lpfc_findnode_did(vport, sid);
17699 	if (!ndlp) {
17700 		ndlp = lpfc_nlp_init(vport, sid);
17701 		if (!ndlp) {
17702 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
17703 					 "1268 Failed to allocate ndlp for "
17704 					 "oxid:x%x SID:x%x\n", oxid, sid);
17705 			return;
17706 		}
17707 		/* Put ndlp onto pport node list */
17708 		lpfc_enqueue_node(vport, ndlp);
17709 	} else if (!NLP_CHK_NODE_ACT(ndlp)) {
17710 		/* re-setup ndlp without removing from node list */
17711 		ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
17712 		if (!ndlp) {
17713 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
17714 					 "3275 Failed to active ndlp found "
17715 					 "for oxid:x%x SID:x%x\n", oxid, sid);
17716 			return;
17717 		}
17718 	}
17719 
17720 	/* Allocate buffer for rsp iocb */
17721 	ctiocb = lpfc_sli_get_iocbq(phba);
17722 	if (!ctiocb)
17723 		return;
17724 
17725 	/* Extract the F_CTL field from FC_HDR */
17726 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
17727 
17728 	icmd = &ctiocb->iocb;
17729 	icmd->un.xseq64.bdl.bdeSize = 0;
17730 	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
17731 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
17732 	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
17733 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
17734 
17735 	/* Fill in the rest of iocb fields */
17736 	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
17737 	icmd->ulpBdeCount = 0;
17738 	icmd->ulpLe = 1;
17739 	icmd->ulpClass = CLASS3;
17740 	icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
17741 	ctiocb->context1 = lpfc_nlp_get(ndlp);
17742 
17743 	ctiocb->vport = phba->pport;
17744 	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
17745 	ctiocb->sli4_lxritag = NO_XRI;
17746 	ctiocb->sli4_xritag = NO_XRI;
17747 
17748 	if (fctl & FC_FC_EX_CTX)
17749 		/* Exchange responder sent the abort so we
17750 		 * own the oxid.
17751 		 */
17752 		xri = oxid;
17753 	else
17754 		xri = rxid;
17755 	lxri = lpfc_sli4_xri_inrange(phba, xri);
17756 	if (lxri != NO_XRI)
17757 		lpfc_set_rrq_active(phba, ndlp, lxri,
17758 			(xri == oxid) ? rxid : oxid, 0);
17759 	/* For BA_ABTS from exchange responder, if the logical xri with
17760 	 * the oxid maps to the FCP XRI range, the port no longer has
17761 	 * that exchange context, send a BLS_RJT. Override the IOCB for
17762 	 * a BA_RJT.
17763 	 */
17764 	if ((fctl & FC_FC_EX_CTX) &&
17765 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
17766 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
17767 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
17768 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
17769 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
17770 	}
17771 
17772 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
17773 	 * the driver no longer has that exchange, send a BLS_RJT. Override
17774 	 * the IOCB for a BA_RJT.
17775 	 */
17776 	if (aborted == false) {
17777 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
17778 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
17779 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
17780 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
17781 	}
17782 
17783 	if (fctl & FC_FC_EX_CTX) {
17784 		/* ABTS sent by responder to CT exchange, construction
17785 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
17786 		 * field and RX_ID from ABTS for RX_ID field.
17787 		 */
17788 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
17789 	} else {
17790 		/* ABTS sent by initiator to CT exchange, construction
17791 		 * of BA_ACC will need to allocate a new XRI as for the
17792 		 * XRI_TAG field.
17793 		 */
17794 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
17795 	}
17796 	bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
17797 	bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
17798 
17799 	/* Xmit CT abts response on exchange <xid> */
17800 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
17801 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
17802 			 icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
17803 
17804 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
17805 	if (rc == IOCB_ERROR) {
17806 		lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
17807 				 "2925 Failed to issue CT ABTS RSP x%x on "
17808 				 "xri x%x, Data x%x\n",
17809 				 icmd->un.xseq64.w5.hcsw.Rctl, oxid,
17810 				 phba->link_state);
17811 		lpfc_nlp_put(ndlp);
17812 		ctiocb->context1 = NULL;
17813 		lpfc_sli_release_iocbq(phba, ctiocb);
17814 	}
17815 }
17816 
17817 /**
17818  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
17819  * @vport: Pointer to the vport on which this sequence was received
17820  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17821  *
17822  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
17823  * receive sequence is only partially assembed by the driver, it shall abort
17824  * the partially assembled frames for the sequence. Otherwise, if the
17825  * unsolicited receive sequence has been completely assembled and passed to
17826  * the Upper Layer Protocol (UPL), it then mark the per oxid status for the
17827  * unsolicited sequence has been aborted. After that, it will issue a basic
17828  * accept to accept the abort.
17829  **/
17830 static void
17831 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
17832 			     struct hbq_dmabuf *dmabuf)
17833 {
17834 	struct lpfc_hba *phba = vport->phba;
17835 	struct fc_frame_header fc_hdr;
17836 	uint32_t fctl;
17837 	bool aborted;
17838 
17839 	/* Make a copy of fc_hdr before the dmabuf being released */
17840 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
17841 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
17842 
17843 	if (fctl & FC_FC_EX_CTX) {
17844 		/* ABTS by responder to exchange, no cleanup needed */
17845 		aborted = true;
17846 	} else {
17847 		/* ABTS by initiator to exchange, need to do cleanup */
17848 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
17849 		if (aborted == false)
17850 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
17851 	}
17852 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
17853 
17854 	if (phba->nvmet_support) {
17855 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
17856 		return;
17857 	}
17858 
17859 	/* Respond with BA_ACC or BA_RJT accordingly */
17860 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
17861 }
17862 
17863 /**
17864  * lpfc_seq_complete - Indicates if a sequence is complete
17865  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17866  *
17867  * This function checks the sequence, starting with the frame described by
17868  * @dmabuf, to see if all the frames associated with this sequence are present.
17869  * the frames associated with this sequence are linked to the @dmabuf using the
17870  * dbuf list. This function looks for two major things. 1) That the first frame
17871  * has a sequence count of zero. 2) There is a frame with last frame of sequence
17872  * set. 3) That there are no holes in the sequence count. The function will
17873  * return 1 when the sequence is complete, otherwise it will return 0.
17874  **/
17875 static int
17876 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
17877 {
17878 	struct fc_frame_header *hdr;
17879 	struct lpfc_dmabuf *d_buf;
17880 	struct hbq_dmabuf *seq_dmabuf;
17881 	uint32_t fctl;
17882 	int seq_count = 0;
17883 
17884 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17885 	/* make sure first fame of sequence has a sequence count of zero */
17886 	if (hdr->fh_seq_cnt != seq_count)
17887 		return 0;
17888 	fctl = (hdr->fh_f_ctl[0] << 16 |
17889 		hdr->fh_f_ctl[1] << 8 |
17890 		hdr->fh_f_ctl[2]);
17891 	/* If last frame of sequence we can return success. */
17892 	if (fctl & FC_FC_END_SEQ)
17893 		return 1;
17894 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
17895 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17896 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
17897 		/* If there is a hole in the sequence count then fail. */
17898 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
17899 			return 0;
17900 		fctl = (hdr->fh_f_ctl[0] << 16 |
17901 			hdr->fh_f_ctl[1] << 8 |
17902 			hdr->fh_f_ctl[2]);
17903 		/* If last frame of sequence we can return success. */
17904 		if (fctl & FC_FC_END_SEQ)
17905 			return 1;
17906 	}
17907 	return 0;
17908 }
17909 
17910 /**
17911  * lpfc_prep_seq - Prep sequence for ULP processing
17912  * @vport: Pointer to the vport on which this sequence was received
17913  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17914  *
17915  * This function takes a sequence, described by a list of frames, and creates
17916  * a list of iocbq structures to describe the sequence. This iocbq list will be
17917  * used to issue to the generic unsolicited sequence handler. This routine
17918  * returns a pointer to the first iocbq in the list. If the function is unable
17919  * to allocate an iocbq then it throw out the received frames that were not
17920  * able to be described and return a pointer to the first iocbq. If unable to
17921  * allocate any iocbqs (including the first) this function will return NULL.
17922  **/
17923 static struct lpfc_iocbq *
17924 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
17925 {
17926 	struct hbq_dmabuf *hbq_buf;
17927 	struct lpfc_dmabuf *d_buf, *n_buf;
17928 	struct lpfc_iocbq *first_iocbq, *iocbq;
17929 	struct fc_frame_header *fc_hdr;
17930 	uint32_t sid;
17931 	uint32_t len, tot_len;
17932 	struct ulp_bde64 *pbde;
17933 
17934 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
17935 	/* remove from receive buffer list */
17936 	list_del_init(&seq_dmabuf->hbuf.list);
17937 	lpfc_update_rcv_time_stamp(vport);
17938 	/* get the Remote Port's SID */
17939 	sid = sli4_sid_from_fc_hdr(fc_hdr);
17940 	tot_len = 0;
17941 	/* Get an iocbq struct to fill in. */
17942 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
17943 	if (first_iocbq) {
17944 		/* Initialize the first IOCB. */
17945 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
17946 		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
17947 		first_iocbq->vport = vport;
17948 
17949 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
17950 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
17951 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
17952 			first_iocbq->iocb.un.rcvels.parmRo =
17953 				sli4_did_from_fc_hdr(fc_hdr);
17954 			first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
17955 		} else
17956 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
17957 		first_iocbq->iocb.ulpContext = NO_XRI;
17958 		first_iocbq->iocb.unsli3.rcvsli3.ox_id =
17959 			be16_to_cpu(fc_hdr->fh_ox_id);
17960 		/* iocbq is prepped for internal consumption.  Physical vpi. */
17961 		first_iocbq->iocb.unsli3.rcvsli3.vpi =
17962 			vport->phba->vpi_ids[vport->vpi];
17963 		/* put the first buffer into the first IOCBq */
17964 		tot_len = bf_get(lpfc_rcqe_length,
17965 				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
17966 
17967 		first_iocbq->context2 = &seq_dmabuf->dbuf;
17968 		first_iocbq->context3 = NULL;
17969 		first_iocbq->iocb.ulpBdeCount = 1;
17970 		if (tot_len > LPFC_DATA_BUF_SIZE)
17971 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
17972 							LPFC_DATA_BUF_SIZE;
17973 		else
17974 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
17975 
17976 		first_iocbq->iocb.un.rcvels.remoteID = sid;
17977 
17978 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
17979 	}
17980 	iocbq = first_iocbq;
17981 	/*
17982 	 * Each IOCBq can have two Buffers assigned, so go through the list
17983 	 * of buffers for this sequence and save two buffers in each IOCBq
17984 	 */
17985 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
17986 		if (!iocbq) {
17987 			lpfc_in_buf_free(vport->phba, d_buf);
17988 			continue;
17989 		}
17990 		if (!iocbq->context3) {
17991 			iocbq->context3 = d_buf;
17992 			iocbq->iocb.ulpBdeCount++;
17993 			/* We need to get the size out of the right CQE */
17994 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17995 			len = bf_get(lpfc_rcqe_length,
17996 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
17997 			pbde = (struct ulp_bde64 *)
17998 					&iocbq->iocb.unsli3.sli3Words[4];
17999 			if (len > LPFC_DATA_BUF_SIZE)
18000 				pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
18001 			else
18002 				pbde->tus.f.bdeSize = len;
18003 
18004 			iocbq->iocb.unsli3.rcvsli3.acc_len += len;
18005 			tot_len += len;
18006 		} else {
18007 			iocbq = lpfc_sli_get_iocbq(vport->phba);
18008 			if (!iocbq) {
18009 				if (first_iocbq) {
18010 					first_iocbq->iocb.ulpStatus =
18011 							IOSTAT_FCP_RSP_ERROR;
18012 					first_iocbq->iocb.un.ulpWord[4] =
18013 							IOERR_NO_RESOURCES;
18014 				}
18015 				lpfc_in_buf_free(vport->phba, d_buf);
18016 				continue;
18017 			}
18018 			/* We need to get the size out of the right CQE */
18019 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18020 			len = bf_get(lpfc_rcqe_length,
18021 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
18022 			iocbq->context2 = d_buf;
18023 			iocbq->context3 = NULL;
18024 			iocbq->iocb.ulpBdeCount = 1;
18025 			if (len > LPFC_DATA_BUF_SIZE)
18026 				iocbq->iocb.un.cont64[0].tus.f.bdeSize =
18027 							LPFC_DATA_BUF_SIZE;
18028 			else
18029 				iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
18030 
18031 			tot_len += len;
18032 			iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
18033 
18034 			iocbq->iocb.un.rcvels.remoteID = sid;
18035 			list_add_tail(&iocbq->list, &first_iocbq->list);
18036 		}
18037 	}
18038 	/* Free the sequence's header buffer */
18039 	if (!first_iocbq)
18040 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
18041 
18042 	return first_iocbq;
18043 }
18044 
18045 static void
18046 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
18047 			  struct hbq_dmabuf *seq_dmabuf)
18048 {
18049 	struct fc_frame_header *fc_hdr;
18050 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
18051 	struct lpfc_hba *phba = vport->phba;
18052 
18053 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18054 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
18055 	if (!iocbq) {
18056 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18057 				"2707 Ring %d handler: Failed to allocate "
18058 				"iocb Rctl x%x Type x%x received\n",
18059 				LPFC_ELS_RING,
18060 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18061 		return;
18062 	}
18063 	if (!lpfc_complete_unsol_iocb(phba,
18064 				      phba->sli4_hba.els_wq->pring,
18065 				      iocbq, fc_hdr->fh_r_ctl,
18066 				      fc_hdr->fh_type))
18067 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18068 				"2540 Ring %d handler: unexpected Rctl "
18069 				"x%x Type x%x received\n",
18070 				LPFC_ELS_RING,
18071 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18072 
18073 	/* Free iocb created in lpfc_prep_seq */
18074 	list_for_each_entry_safe(curr_iocb, next_iocb,
18075 		&iocbq->list, list) {
18076 		list_del_init(&curr_iocb->list);
18077 		lpfc_sli_release_iocbq(phba, curr_iocb);
18078 	}
18079 	lpfc_sli_release_iocbq(phba, iocbq);
18080 }
18081 
18082 static void
18083 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
18084 			    struct lpfc_iocbq *rspiocb)
18085 {
18086 	struct lpfc_dmabuf *pcmd = cmdiocb->context2;
18087 
18088 	if (pcmd && pcmd->virt)
18089 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18090 	kfree(pcmd);
18091 	lpfc_sli_release_iocbq(phba, cmdiocb);
18092 	lpfc_drain_txq(phba);
18093 }
18094 
18095 static void
18096 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
18097 			      struct hbq_dmabuf *dmabuf)
18098 {
18099 	struct fc_frame_header *fc_hdr;
18100 	struct lpfc_hba *phba = vport->phba;
18101 	struct lpfc_iocbq *iocbq = NULL;
18102 	union  lpfc_wqe *wqe;
18103 	struct lpfc_dmabuf *pcmd = NULL;
18104 	uint32_t frame_len;
18105 	int rc;
18106 	unsigned long iflags;
18107 
18108 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18109 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
18110 
18111 	/* Send the received frame back */
18112 	iocbq = lpfc_sli_get_iocbq(phba);
18113 	if (!iocbq) {
18114 		/* Queue cq event and wakeup worker thread to process it */
18115 		spin_lock_irqsave(&phba->hbalock, iflags);
18116 		list_add_tail(&dmabuf->cq_event.list,
18117 			      &phba->sli4_hba.sp_queue_event);
18118 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
18119 		spin_unlock_irqrestore(&phba->hbalock, iflags);
18120 		lpfc_worker_wake_up(phba);
18121 		return;
18122 	}
18123 
18124 	/* Allocate buffer for command payload */
18125 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
18126 	if (pcmd)
18127 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
18128 					    &pcmd->phys);
18129 	if (!pcmd || !pcmd->virt)
18130 		goto exit;
18131 
18132 	INIT_LIST_HEAD(&pcmd->list);
18133 
18134 	/* copyin the payload */
18135 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
18136 
18137 	/* fill in BDE's for command */
18138 	iocbq->iocb.un.xseq64.bdl.addrHigh = putPaddrHigh(pcmd->phys);
18139 	iocbq->iocb.un.xseq64.bdl.addrLow = putPaddrLow(pcmd->phys);
18140 	iocbq->iocb.un.xseq64.bdl.bdeFlags = BUFF_TYPE_BDE_64;
18141 	iocbq->iocb.un.xseq64.bdl.bdeSize = frame_len;
18142 
18143 	iocbq->context2 = pcmd;
18144 	iocbq->vport = vport;
18145 	iocbq->iocb_flag &= ~LPFC_FIP_ELS_ID_MASK;
18146 	iocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
18147 
18148 	/*
18149 	 * Setup rest of the iocb as though it were a WQE
18150 	 * Build the SEND_FRAME WQE
18151 	 */
18152 	wqe = (union lpfc_wqe *)&iocbq->iocb;
18153 
18154 	wqe->send_frame.frame_len = frame_len;
18155 	wqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((uint32_t *)fc_hdr));
18156 	wqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((uint32_t *)fc_hdr + 1));
18157 	wqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((uint32_t *)fc_hdr + 2));
18158 	wqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((uint32_t *)fc_hdr + 3));
18159 	wqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((uint32_t *)fc_hdr + 4));
18160 	wqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((uint32_t *)fc_hdr + 5));
18161 
18162 	iocbq->iocb.ulpCommand = CMD_SEND_FRAME;
18163 	iocbq->iocb.ulpLe = 1;
18164 	iocbq->iocb_cmpl = lpfc_sli4_mds_loopback_cmpl;
18165 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
18166 	if (rc == IOCB_ERROR)
18167 		goto exit;
18168 
18169 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18170 	return;
18171 
18172 exit:
18173 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18174 			"2023 Unable to process MDS loopback frame\n");
18175 	if (pcmd && pcmd->virt)
18176 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18177 	kfree(pcmd);
18178 	if (iocbq)
18179 		lpfc_sli_release_iocbq(phba, iocbq);
18180 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18181 }
18182 
18183 /**
18184  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
18185  * @phba: Pointer to HBA context object.
18186  *
18187  * This function is called with no lock held. This function processes all
18188  * the received buffers and gives it to upper layers when a received buffer
18189  * indicates that it is the final frame in the sequence. The interrupt
18190  * service routine processes received buffers at interrupt contexts.
18191  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
18192  * appropriate receive function when the final frame in a sequence is received.
18193  **/
18194 void
18195 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
18196 				 struct hbq_dmabuf *dmabuf)
18197 {
18198 	struct hbq_dmabuf *seq_dmabuf;
18199 	struct fc_frame_header *fc_hdr;
18200 	struct lpfc_vport *vport;
18201 	uint32_t fcfi;
18202 	uint32_t did;
18203 
18204 	/* Process each received buffer */
18205 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18206 
18207 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
18208 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
18209 		vport = phba->pport;
18210 		/* Handle MDS Loopback frames */
18211 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18212 		return;
18213 	}
18214 
18215 	/* check to see if this a valid type of frame */
18216 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
18217 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18218 		return;
18219 	}
18220 
18221 	if ((bf_get(lpfc_cqe_code,
18222 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
18223 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
18224 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
18225 	else
18226 		fcfi = bf_get(lpfc_rcqe_fcf_id,
18227 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
18228 
18229 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
18230 		vport = phba->pport;
18231 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
18232 				"2023 MDS Loopback %d bytes\n",
18233 				bf_get(lpfc_rcqe_length,
18234 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
18235 		/* Handle MDS Loopback frames */
18236 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18237 		return;
18238 	}
18239 
18240 	/* d_id this frame is directed to */
18241 	did = sli4_did_from_fc_hdr(fc_hdr);
18242 
18243 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
18244 	if (!vport) {
18245 		/* throw out the frame */
18246 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18247 		return;
18248 	}
18249 
18250 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
18251 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
18252 		(did != Fabric_DID)) {
18253 		/*
18254 		 * Throw out the frame if we are not pt2pt.
18255 		 * The pt2pt protocol allows for discovery frames
18256 		 * to be received without a registered VPI.
18257 		 */
18258 		if (!(vport->fc_flag & FC_PT2PT) ||
18259 			(phba->link_state == LPFC_HBA_READY)) {
18260 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
18261 			return;
18262 		}
18263 	}
18264 
18265 	/* Handle the basic abort sequence (BA_ABTS) event */
18266 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
18267 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
18268 		return;
18269 	}
18270 
18271 	/* Link this frame */
18272 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
18273 	if (!seq_dmabuf) {
18274 		/* unable to add frame to vport - throw it out */
18275 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18276 		return;
18277 	}
18278 	/* If not last frame in sequence continue processing frames. */
18279 	if (!lpfc_seq_complete(seq_dmabuf))
18280 		return;
18281 
18282 	/* Send the complete sequence to the upper layer protocol */
18283 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
18284 }
18285 
18286 /**
18287  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
18288  * @phba: pointer to lpfc hba data structure.
18289  *
18290  * This routine is invoked to post rpi header templates to the
18291  * HBA consistent with the SLI-4 interface spec.  This routine
18292  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18293  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18294  *
18295  * This routine does not require any locks.  It's usage is expected
18296  * to be driver load or reset recovery when the driver is
18297  * sequential.
18298  *
18299  * Return codes
18300  * 	0 - successful
18301  *      -EIO - The mailbox failed to complete successfully.
18302  * 	When this error occurs, the driver is not guaranteed
18303  *	to have any rpi regions posted to the device and
18304  *	must either attempt to repost the regions or take a
18305  *	fatal error.
18306  **/
18307 int
18308 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
18309 {
18310 	struct lpfc_rpi_hdr *rpi_page;
18311 	uint32_t rc = 0;
18312 	uint16_t lrpi = 0;
18313 
18314 	/* SLI4 ports that support extents do not require RPI headers. */
18315 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18316 		goto exit;
18317 	if (phba->sli4_hba.extents_in_use)
18318 		return -EIO;
18319 
18320 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
18321 		/*
18322 		 * Assign the rpi headers a physical rpi only if the driver
18323 		 * has not initialized those resources.  A port reset only
18324 		 * needs the headers posted.
18325 		 */
18326 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
18327 		    LPFC_RPI_RSRC_RDY)
18328 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18329 
18330 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
18331 		if (rc != MBX_SUCCESS) {
18332 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18333 					"2008 Error %d posting all rpi "
18334 					"headers\n", rc);
18335 			rc = -EIO;
18336 			break;
18337 		}
18338 	}
18339 
18340  exit:
18341 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
18342 	       LPFC_RPI_RSRC_RDY);
18343 	return rc;
18344 }
18345 
18346 /**
18347  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
18348  * @phba: pointer to lpfc hba data structure.
18349  * @rpi_page:  pointer to the rpi memory region.
18350  *
18351  * This routine is invoked to post a single rpi header to the
18352  * HBA consistent with the SLI-4 interface spec.  This memory region
18353  * maps up to 64 rpi context regions.
18354  *
18355  * Return codes
18356  * 	0 - successful
18357  * 	-ENOMEM - No available memory
18358  *      -EIO - The mailbox failed to complete successfully.
18359  **/
18360 int
18361 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
18362 {
18363 	LPFC_MBOXQ_t *mboxq;
18364 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
18365 	uint32_t rc = 0;
18366 	uint32_t shdr_status, shdr_add_status;
18367 	union lpfc_sli4_cfg_shdr *shdr;
18368 
18369 	/* SLI4 ports that support extents do not require RPI headers. */
18370 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18371 		return rc;
18372 	if (phba->sli4_hba.extents_in_use)
18373 		return -EIO;
18374 
18375 	/* The port is notified of the header region via a mailbox command. */
18376 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18377 	if (!mboxq) {
18378 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18379 				"2001 Unable to allocate memory for issuing "
18380 				"SLI_CONFIG_SPECIAL mailbox command\n");
18381 		return -ENOMEM;
18382 	}
18383 
18384 	/* Post all rpi memory regions to the port. */
18385 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
18386 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
18387 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
18388 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
18389 			 sizeof(struct lpfc_sli4_cfg_mhdr),
18390 			 LPFC_SLI4_MBX_EMBED);
18391 
18392 
18393 	/* Post the physical rpi to the port for this rpi header. */
18394 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
18395 	       rpi_page->start_rpi);
18396 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
18397 	       hdr_tmpl, rpi_page->page_count);
18398 
18399 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
18400 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
18401 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
18402 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
18403 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18404 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18405 	if (rc != MBX_TIMEOUT)
18406 		mempool_free(mboxq, phba->mbox_mem_pool);
18407 	if (shdr_status || shdr_add_status || rc) {
18408 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18409 				"2514 POST_RPI_HDR mailbox failed with "
18410 				"status x%x add_status x%x, mbx status x%x\n",
18411 				shdr_status, shdr_add_status, rc);
18412 		rc = -ENXIO;
18413 	} else {
18414 		/*
18415 		 * The next_rpi stores the next logical module-64 rpi value used
18416 		 * to post physical rpis in subsequent rpi postings.
18417 		 */
18418 		spin_lock_irq(&phba->hbalock);
18419 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
18420 		spin_unlock_irq(&phba->hbalock);
18421 	}
18422 	return rc;
18423 }
18424 
18425 /**
18426  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
18427  * @phba: pointer to lpfc hba data structure.
18428  *
18429  * This routine is invoked to post rpi header templates to the
18430  * HBA consistent with the SLI-4 interface spec.  This routine
18431  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18432  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18433  *
18434  * Returns
18435  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
18436  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
18437  **/
18438 int
18439 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
18440 {
18441 	unsigned long rpi;
18442 	uint16_t max_rpi, rpi_limit;
18443 	uint16_t rpi_remaining, lrpi = 0;
18444 	struct lpfc_rpi_hdr *rpi_hdr;
18445 	unsigned long iflag;
18446 
18447 	/*
18448 	 * Fetch the next logical rpi.  Because this index is logical,
18449 	 * the  driver starts at 0 each time.
18450 	 */
18451 	spin_lock_irqsave(&phba->hbalock, iflag);
18452 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
18453 	rpi_limit = phba->sli4_hba.next_rpi;
18454 
18455 	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
18456 	if (rpi >= rpi_limit)
18457 		rpi = LPFC_RPI_ALLOC_ERROR;
18458 	else {
18459 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
18460 		phba->sli4_hba.max_cfg_param.rpi_used++;
18461 		phba->sli4_hba.rpi_count++;
18462 	}
18463 	lpfc_printf_log(phba, KERN_INFO,
18464 			LOG_NODE | LOG_DISCOVERY,
18465 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
18466 			(int) rpi, max_rpi, rpi_limit);
18467 
18468 	/*
18469 	 * Don't try to allocate more rpi header regions if the device limit
18470 	 * has been exhausted.
18471 	 */
18472 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
18473 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
18474 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18475 		return rpi;
18476 	}
18477 
18478 	/*
18479 	 * RPI header postings are not required for SLI4 ports capable of
18480 	 * extents.
18481 	 */
18482 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
18483 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18484 		return rpi;
18485 	}
18486 
18487 	/*
18488 	 * If the driver is running low on rpi resources, allocate another
18489 	 * page now.  Note that the next_rpi value is used because
18490 	 * it represents how many are actually in use whereas max_rpi notes
18491 	 * how many are supported max by the device.
18492 	 */
18493 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
18494 	spin_unlock_irqrestore(&phba->hbalock, iflag);
18495 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
18496 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
18497 		if (!rpi_hdr) {
18498 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18499 					"2002 Error Could not grow rpi "
18500 					"count\n");
18501 		} else {
18502 			lrpi = rpi_hdr->start_rpi;
18503 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18504 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
18505 		}
18506 	}
18507 
18508 	return rpi;
18509 }
18510 
18511 /**
18512  * lpfc_sli4_free_rpi - Release an rpi for reuse.
18513  * @phba: pointer to lpfc hba data structure.
18514  *
18515  * This routine is invoked to release an rpi to the pool of
18516  * available rpis maintained by the driver.
18517  **/
18518 static void
18519 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
18520 {
18521 	/*
18522 	 * if the rpi value indicates a prior unreg has already
18523 	 * been done, skip the unreg.
18524 	 */
18525 	if (rpi == LPFC_RPI_ALLOC_ERROR)
18526 		return;
18527 
18528 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
18529 		phba->sli4_hba.rpi_count--;
18530 		phba->sli4_hba.max_cfg_param.rpi_used--;
18531 	} else {
18532 		lpfc_printf_log(phba, KERN_INFO,
18533 				LOG_NODE | LOG_DISCOVERY,
18534 				"2016 rpi %x not inuse\n",
18535 				rpi);
18536 	}
18537 }
18538 
18539 /**
18540  * lpfc_sli4_free_rpi - Release an rpi for reuse.
18541  * @phba: pointer to lpfc hba data structure.
18542  *
18543  * This routine is invoked to release an rpi to the pool of
18544  * available rpis maintained by the driver.
18545  **/
18546 void
18547 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
18548 {
18549 	spin_lock_irq(&phba->hbalock);
18550 	__lpfc_sli4_free_rpi(phba, rpi);
18551 	spin_unlock_irq(&phba->hbalock);
18552 }
18553 
18554 /**
18555  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
18556  * @phba: pointer to lpfc hba data structure.
18557  *
18558  * This routine is invoked to remove the memory region that
18559  * provided rpi via a bitmask.
18560  **/
18561 void
18562 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
18563 {
18564 	kfree(phba->sli4_hba.rpi_bmask);
18565 	kfree(phba->sli4_hba.rpi_ids);
18566 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
18567 }
18568 
18569 /**
18570  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
18571  * @phba: pointer to lpfc hba data structure.
18572  *
18573  * This routine is invoked to remove the memory region that
18574  * provided rpi via a bitmask.
18575  **/
18576 int
18577 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
18578 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
18579 {
18580 	LPFC_MBOXQ_t *mboxq;
18581 	struct lpfc_hba *phba = ndlp->phba;
18582 	int rc;
18583 
18584 	/* The port is notified of the header region via a mailbox command. */
18585 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18586 	if (!mboxq)
18587 		return -ENOMEM;
18588 
18589 	/* Post all rpi memory regions to the port. */
18590 	lpfc_resume_rpi(mboxq, ndlp);
18591 	if (cmpl) {
18592 		mboxq->mbox_cmpl = cmpl;
18593 		mboxq->ctx_buf = arg;
18594 		mboxq->ctx_ndlp = ndlp;
18595 	} else
18596 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
18597 	mboxq->vport = ndlp->vport;
18598 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18599 	if (rc == MBX_NOT_FINISHED) {
18600 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18601 				"2010 Resume RPI Mailbox failed "
18602 				"status %d, mbxStatus x%x\n", rc,
18603 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
18604 		mempool_free(mboxq, phba->mbox_mem_pool);
18605 		return -EIO;
18606 	}
18607 	return 0;
18608 }
18609 
18610 /**
18611  * lpfc_sli4_init_vpi - Initialize a vpi with the port
18612  * @vport: Pointer to the vport for which the vpi is being initialized
18613  *
18614  * This routine is invoked to activate a vpi with the port.
18615  *
18616  * Returns:
18617  *    0 success
18618  *    -Evalue otherwise
18619  **/
18620 int
18621 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
18622 {
18623 	LPFC_MBOXQ_t *mboxq;
18624 	int rc = 0;
18625 	int retval = MBX_SUCCESS;
18626 	uint32_t mbox_tmo;
18627 	struct lpfc_hba *phba = vport->phba;
18628 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18629 	if (!mboxq)
18630 		return -ENOMEM;
18631 	lpfc_init_vpi(phba, mboxq, vport->vpi);
18632 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
18633 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
18634 	if (rc != MBX_SUCCESS) {
18635 		lpfc_printf_vlog(vport, KERN_ERR, LOG_SLI,
18636 				"2022 INIT VPI Mailbox failed "
18637 				"status %d, mbxStatus x%x\n", rc,
18638 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
18639 		retval = -EIO;
18640 	}
18641 	if (rc != MBX_TIMEOUT)
18642 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
18643 
18644 	return retval;
18645 }
18646 
18647 /**
18648  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
18649  * @phba: pointer to lpfc hba data structure.
18650  * @mboxq: Pointer to mailbox object.
18651  *
18652  * This routine is invoked to manually add a single FCF record. The caller
18653  * must pass a completely initialized FCF_Record.  This routine takes
18654  * care of the nonembedded mailbox operations.
18655  **/
18656 static void
18657 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
18658 {
18659 	void *virt_addr;
18660 	union lpfc_sli4_cfg_shdr *shdr;
18661 	uint32_t shdr_status, shdr_add_status;
18662 
18663 	virt_addr = mboxq->sge_array->addr[0];
18664 	/* The IOCTL status is embedded in the mailbox subheader. */
18665 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
18666 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18667 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18668 
18669 	if ((shdr_status || shdr_add_status) &&
18670 		(shdr_status != STATUS_FCF_IN_USE))
18671 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18672 			"2558 ADD_FCF_RECORD mailbox failed with "
18673 			"status x%x add_status x%x\n",
18674 			shdr_status, shdr_add_status);
18675 
18676 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
18677 }
18678 
18679 /**
18680  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
18681  * @phba: pointer to lpfc hba data structure.
18682  * @fcf_record:  pointer to the initialized fcf record to add.
18683  *
18684  * This routine is invoked to manually add a single FCF record. The caller
18685  * must pass a completely initialized FCF_Record.  This routine takes
18686  * care of the nonembedded mailbox operations.
18687  **/
18688 int
18689 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
18690 {
18691 	int rc = 0;
18692 	LPFC_MBOXQ_t *mboxq;
18693 	uint8_t *bytep;
18694 	void *virt_addr;
18695 	struct lpfc_mbx_sge sge;
18696 	uint32_t alloc_len, req_len;
18697 	uint32_t fcfindex;
18698 
18699 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18700 	if (!mboxq) {
18701 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18702 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
18703 		return -ENOMEM;
18704 	}
18705 
18706 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
18707 		  sizeof(uint32_t);
18708 
18709 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18710 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
18711 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
18712 				     req_len, LPFC_SLI4_MBX_NEMBED);
18713 	if (alloc_len < req_len) {
18714 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18715 			"2523 Allocated DMA memory size (x%x) is "
18716 			"less than the requested DMA memory "
18717 			"size (x%x)\n", alloc_len, req_len);
18718 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18719 		return -ENOMEM;
18720 	}
18721 
18722 	/*
18723 	 * Get the first SGE entry from the non-embedded DMA memory.  This
18724 	 * routine only uses a single SGE.
18725 	 */
18726 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
18727 	virt_addr = mboxq->sge_array->addr[0];
18728 	/*
18729 	 * Configure the FCF record for FCFI 0.  This is the driver's
18730 	 * hardcoded default and gets used in nonFIP mode.
18731 	 */
18732 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
18733 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
18734 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
18735 
18736 	/*
18737 	 * Copy the fcf_index and the FCF Record Data. The data starts after
18738 	 * the FCoE header plus word10. The data copy needs to be endian
18739 	 * correct.
18740 	 */
18741 	bytep += sizeof(uint32_t);
18742 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
18743 	mboxq->vport = phba->pport;
18744 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
18745 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18746 	if (rc == MBX_NOT_FINISHED) {
18747 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18748 			"2515 ADD_FCF_RECORD mailbox failed with "
18749 			"status 0x%x\n", rc);
18750 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18751 		rc = -EIO;
18752 	} else
18753 		rc = 0;
18754 
18755 	return rc;
18756 }
18757 
18758 /**
18759  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
18760  * @phba: pointer to lpfc hba data structure.
18761  * @fcf_record:  pointer to the fcf record to write the default data.
18762  * @fcf_index: FCF table entry index.
18763  *
18764  * This routine is invoked to build the driver's default FCF record.  The
18765  * values used are hardcoded.  This routine handles memory initialization.
18766  *
18767  **/
18768 void
18769 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
18770 				struct fcf_record *fcf_record,
18771 				uint16_t fcf_index)
18772 {
18773 	memset(fcf_record, 0, sizeof(struct fcf_record));
18774 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
18775 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
18776 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
18777 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
18778 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
18779 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
18780 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
18781 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
18782 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
18783 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
18784 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
18785 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
18786 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
18787 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
18788 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
18789 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
18790 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
18791 	/* Set the VLAN bit map */
18792 	if (phba->valid_vlan) {
18793 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
18794 			= 1 << (phba->vlan_id % 8);
18795 	}
18796 }
18797 
18798 /**
18799  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
18800  * @phba: pointer to lpfc hba data structure.
18801  * @fcf_index: FCF table entry offset.
18802  *
18803  * This routine is invoked to scan the entire FCF table by reading FCF
18804  * record and processing it one at a time starting from the @fcf_index
18805  * for initial FCF discovery or fast FCF failover rediscovery.
18806  *
18807  * Return 0 if the mailbox command is submitted successfully, none 0
18808  * otherwise.
18809  **/
18810 int
18811 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
18812 {
18813 	int rc = 0, error;
18814 	LPFC_MBOXQ_t *mboxq;
18815 
18816 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
18817 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
18818 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18819 	if (!mboxq) {
18820 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18821 				"2000 Failed to allocate mbox for "
18822 				"READ_FCF cmd\n");
18823 		error = -ENOMEM;
18824 		goto fail_fcf_scan;
18825 	}
18826 	/* Construct the read FCF record mailbox command */
18827 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
18828 	if (rc) {
18829 		error = -EINVAL;
18830 		goto fail_fcf_scan;
18831 	}
18832 	/* Issue the mailbox command asynchronously */
18833 	mboxq->vport = phba->pport;
18834 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
18835 
18836 	spin_lock_irq(&phba->hbalock);
18837 	phba->hba_flag |= FCF_TS_INPROG;
18838 	spin_unlock_irq(&phba->hbalock);
18839 
18840 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18841 	if (rc == MBX_NOT_FINISHED)
18842 		error = -EIO;
18843 	else {
18844 		/* Reset eligible FCF count for new scan */
18845 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
18846 			phba->fcf.eligible_fcf_cnt = 0;
18847 		error = 0;
18848 	}
18849 fail_fcf_scan:
18850 	if (error) {
18851 		if (mboxq)
18852 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
18853 		/* FCF scan failed, clear FCF_TS_INPROG flag */
18854 		spin_lock_irq(&phba->hbalock);
18855 		phba->hba_flag &= ~FCF_TS_INPROG;
18856 		spin_unlock_irq(&phba->hbalock);
18857 	}
18858 	return error;
18859 }
18860 
18861 /**
18862  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
18863  * @phba: pointer to lpfc hba data structure.
18864  * @fcf_index: FCF table entry offset.
18865  *
18866  * This routine is invoked to read an FCF record indicated by @fcf_index
18867  * and to use it for FLOGI roundrobin FCF failover.
18868  *
18869  * Return 0 if the mailbox command is submitted successfully, none 0
18870  * otherwise.
18871  **/
18872 int
18873 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
18874 {
18875 	int rc = 0, error;
18876 	LPFC_MBOXQ_t *mboxq;
18877 
18878 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18879 	if (!mboxq) {
18880 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
18881 				"2763 Failed to allocate mbox for "
18882 				"READ_FCF cmd\n");
18883 		error = -ENOMEM;
18884 		goto fail_fcf_read;
18885 	}
18886 	/* Construct the read FCF record mailbox command */
18887 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
18888 	if (rc) {
18889 		error = -EINVAL;
18890 		goto fail_fcf_read;
18891 	}
18892 	/* Issue the mailbox command asynchronously */
18893 	mboxq->vport = phba->pport;
18894 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
18895 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18896 	if (rc == MBX_NOT_FINISHED)
18897 		error = -EIO;
18898 	else
18899 		error = 0;
18900 
18901 fail_fcf_read:
18902 	if (error && mboxq)
18903 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18904 	return error;
18905 }
18906 
18907 /**
18908  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
18909  * @phba: pointer to lpfc hba data structure.
18910  * @fcf_index: FCF table entry offset.
18911  *
18912  * This routine is invoked to read an FCF record indicated by @fcf_index to
18913  * determine whether it's eligible for FLOGI roundrobin failover list.
18914  *
18915  * Return 0 if the mailbox command is submitted successfully, none 0
18916  * otherwise.
18917  **/
18918 int
18919 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
18920 {
18921 	int rc = 0, error;
18922 	LPFC_MBOXQ_t *mboxq;
18923 
18924 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18925 	if (!mboxq) {
18926 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
18927 				"2758 Failed to allocate mbox for "
18928 				"READ_FCF cmd\n");
18929 				error = -ENOMEM;
18930 				goto fail_fcf_read;
18931 	}
18932 	/* Construct the read FCF record mailbox command */
18933 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
18934 	if (rc) {
18935 		error = -EINVAL;
18936 		goto fail_fcf_read;
18937 	}
18938 	/* Issue the mailbox command asynchronously */
18939 	mboxq->vport = phba->pport;
18940 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
18941 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18942 	if (rc == MBX_NOT_FINISHED)
18943 		error = -EIO;
18944 	else
18945 		error = 0;
18946 
18947 fail_fcf_read:
18948 	if (error && mboxq)
18949 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18950 	return error;
18951 }
18952 
18953 /**
18954  * lpfc_check_next_fcf_pri_level
18955  * phba pointer to the lpfc_hba struct for this port.
18956  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
18957  * routine when the rr_bmask is empty. The FCF indecies are put into the
18958  * rr_bmask based on their priority level. Starting from the highest priority
18959  * to the lowest. The most likely FCF candidate will be in the highest
18960  * priority group. When this routine is called it searches the fcf_pri list for
18961  * next lowest priority group and repopulates the rr_bmask with only those
18962  * fcf_indexes.
18963  * returns:
18964  * 1=success 0=failure
18965  **/
18966 static int
18967 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
18968 {
18969 	uint16_t next_fcf_pri;
18970 	uint16_t last_index;
18971 	struct lpfc_fcf_pri *fcf_pri;
18972 	int rc;
18973 	int ret = 0;
18974 
18975 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
18976 			LPFC_SLI4_FCF_TBL_INDX_MAX);
18977 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
18978 			"3060 Last IDX %d\n", last_index);
18979 
18980 	/* Verify the priority list has 2 or more entries */
18981 	spin_lock_irq(&phba->hbalock);
18982 	if (list_empty(&phba->fcf.fcf_pri_list) ||
18983 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
18984 		spin_unlock_irq(&phba->hbalock);
18985 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
18986 			"3061 Last IDX %d\n", last_index);
18987 		return 0; /* Empty rr list */
18988 	}
18989 	spin_unlock_irq(&phba->hbalock);
18990 
18991 	next_fcf_pri = 0;
18992 	/*
18993 	 * Clear the rr_bmask and set all of the bits that are at this
18994 	 * priority.
18995 	 */
18996 	memset(phba->fcf.fcf_rr_bmask, 0,
18997 			sizeof(*phba->fcf.fcf_rr_bmask));
18998 	spin_lock_irq(&phba->hbalock);
18999 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
19000 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
19001 			continue;
19002 		/*
19003 		 * the 1st priority that has not FLOGI failed
19004 		 * will be the highest.
19005 		 */
19006 		if (!next_fcf_pri)
19007 			next_fcf_pri = fcf_pri->fcf_rec.priority;
19008 		spin_unlock_irq(&phba->hbalock);
19009 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
19010 			rc = lpfc_sli4_fcf_rr_index_set(phba,
19011 						fcf_pri->fcf_rec.fcf_index);
19012 			if (rc)
19013 				return 0;
19014 		}
19015 		spin_lock_irq(&phba->hbalock);
19016 	}
19017 	/*
19018 	 * if next_fcf_pri was not set above and the list is not empty then
19019 	 * we have failed flogis on all of them. So reset flogi failed
19020 	 * and start at the beginning.
19021 	 */
19022 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
19023 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
19024 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
19025 			/*
19026 			 * the 1st priority that has not FLOGI failed
19027 			 * will be the highest.
19028 			 */
19029 			if (!next_fcf_pri)
19030 				next_fcf_pri = fcf_pri->fcf_rec.priority;
19031 			spin_unlock_irq(&phba->hbalock);
19032 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
19033 				rc = lpfc_sli4_fcf_rr_index_set(phba,
19034 						fcf_pri->fcf_rec.fcf_index);
19035 				if (rc)
19036 					return 0;
19037 			}
19038 			spin_lock_irq(&phba->hbalock);
19039 		}
19040 	} else
19041 		ret = 1;
19042 	spin_unlock_irq(&phba->hbalock);
19043 
19044 	return ret;
19045 }
19046 /**
19047  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
19048  * @phba: pointer to lpfc hba data structure.
19049  *
19050  * This routine is to get the next eligible FCF record index in a round
19051  * robin fashion. If the next eligible FCF record index equals to the
19052  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
19053  * shall be returned, otherwise, the next eligible FCF record's index
19054  * shall be returned.
19055  **/
19056 uint16_t
19057 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
19058 {
19059 	uint16_t next_fcf_index;
19060 
19061 initial_priority:
19062 	/* Search start from next bit of currently registered FCF index */
19063 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
19064 
19065 next_priority:
19066 	/* Determine the next fcf index to check */
19067 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
19068 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
19069 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
19070 				       next_fcf_index);
19071 
19072 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
19073 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19074 		/*
19075 		 * If we have wrapped then we need to clear the bits that
19076 		 * have been tested so that we can detect when we should
19077 		 * change the priority level.
19078 		 */
19079 		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
19080 					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
19081 	}
19082 
19083 
19084 	/* Check roundrobin failover list empty condition */
19085 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
19086 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
19087 		/*
19088 		 * If next fcf index is not found check if there are lower
19089 		 * Priority level fcf's in the fcf_priority list.
19090 		 * Set up the rr_bmask with all of the avaiable fcf bits
19091 		 * at that level and continue the selection process.
19092 		 */
19093 		if (lpfc_check_next_fcf_pri_level(phba))
19094 			goto initial_priority;
19095 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
19096 				"2844 No roundrobin failover FCF available\n");
19097 
19098 		return LPFC_FCOE_FCF_NEXT_NONE;
19099 	}
19100 
19101 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
19102 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
19103 		LPFC_FCF_FLOGI_FAILED) {
19104 		if (list_is_singular(&phba->fcf.fcf_pri_list))
19105 			return LPFC_FCOE_FCF_NEXT_NONE;
19106 
19107 		goto next_priority;
19108 	}
19109 
19110 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19111 			"2845 Get next roundrobin failover FCF (x%x)\n",
19112 			next_fcf_index);
19113 
19114 	return next_fcf_index;
19115 }
19116 
19117 /**
19118  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
19119  * @phba: pointer to lpfc hba data structure.
19120  *
19121  * This routine sets the FCF record index in to the eligible bmask for
19122  * roundrobin failover search. It checks to make sure that the index
19123  * does not go beyond the range of the driver allocated bmask dimension
19124  * before setting the bit.
19125  *
19126  * Returns 0 if the index bit successfully set, otherwise, it returns
19127  * -EINVAL.
19128  **/
19129 int
19130 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
19131 {
19132 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19133 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19134 				"2610 FCF (x%x) reached driver's book "
19135 				"keeping dimension:x%x\n",
19136 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19137 		return -EINVAL;
19138 	}
19139 	/* Set the eligible FCF record index bmask */
19140 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19141 
19142 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19143 			"2790 Set FCF (x%x) to roundrobin FCF failover "
19144 			"bmask\n", fcf_index);
19145 
19146 	return 0;
19147 }
19148 
19149 /**
19150  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
19151  * @phba: pointer to lpfc hba data structure.
19152  *
19153  * This routine clears the FCF record index from the eligible bmask for
19154  * roundrobin failover search. It checks to make sure that the index
19155  * does not go beyond the range of the driver allocated bmask dimension
19156  * before clearing the bit.
19157  **/
19158 void
19159 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
19160 {
19161 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
19162 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19163 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19164 				"2762 FCF (x%x) reached driver's book "
19165 				"keeping dimension:x%x\n",
19166 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19167 		return;
19168 	}
19169 	/* Clear the eligible FCF record index bmask */
19170 	spin_lock_irq(&phba->hbalock);
19171 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
19172 				 list) {
19173 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
19174 			list_del_init(&fcf_pri->list);
19175 			break;
19176 		}
19177 	}
19178 	spin_unlock_irq(&phba->hbalock);
19179 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19180 
19181 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19182 			"2791 Clear FCF (x%x) from roundrobin failover "
19183 			"bmask\n", fcf_index);
19184 }
19185 
19186 /**
19187  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
19188  * @phba: pointer to lpfc hba data structure.
19189  *
19190  * This routine is the completion routine for the rediscover FCF table mailbox
19191  * command. If the mailbox command returned failure, it will try to stop the
19192  * FCF rediscover wait timer.
19193  **/
19194 static void
19195 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
19196 {
19197 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19198 	uint32_t shdr_status, shdr_add_status;
19199 
19200 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19201 
19202 	shdr_status = bf_get(lpfc_mbox_hdr_status,
19203 			     &redisc_fcf->header.cfg_shdr.response);
19204 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
19205 			     &redisc_fcf->header.cfg_shdr.response);
19206 	if (shdr_status || shdr_add_status) {
19207 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19208 				"2746 Requesting for FCF rediscovery failed "
19209 				"status x%x add_status x%x\n",
19210 				shdr_status, shdr_add_status);
19211 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
19212 			spin_lock_irq(&phba->hbalock);
19213 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
19214 			spin_unlock_irq(&phba->hbalock);
19215 			/*
19216 			 * CVL event triggered FCF rediscover request failed,
19217 			 * last resort to re-try current registered FCF entry.
19218 			 */
19219 			lpfc_retry_pport_discovery(phba);
19220 		} else {
19221 			spin_lock_irq(&phba->hbalock);
19222 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
19223 			spin_unlock_irq(&phba->hbalock);
19224 			/*
19225 			 * DEAD FCF event triggered FCF rediscover request
19226 			 * failed, last resort to fail over as a link down
19227 			 * to FCF registration.
19228 			 */
19229 			lpfc_sli4_fcf_dead_failthrough(phba);
19230 		}
19231 	} else {
19232 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19233 				"2775 Start FCF rediscover quiescent timer\n");
19234 		/*
19235 		 * Start FCF rediscovery wait timer for pending FCF
19236 		 * before rescan FCF record table.
19237 		 */
19238 		lpfc_fcf_redisc_wait_start_timer(phba);
19239 	}
19240 
19241 	mempool_free(mbox, phba->mbox_mem_pool);
19242 }
19243 
19244 /**
19245  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
19246  * @phba: pointer to lpfc hba data structure.
19247  *
19248  * This routine is invoked to request for rediscovery of the entire FCF table
19249  * by the port.
19250  **/
19251 int
19252 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
19253 {
19254 	LPFC_MBOXQ_t *mbox;
19255 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19256 	int rc, length;
19257 
19258 	/* Cancel retry delay timers to all vports before FCF rediscover */
19259 	lpfc_cancel_all_vport_retry_delay_timer(phba);
19260 
19261 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19262 	if (!mbox) {
19263 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
19264 				"2745 Failed to allocate mbox for "
19265 				"requesting FCF rediscover.\n");
19266 		return -ENOMEM;
19267 	}
19268 
19269 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
19270 		  sizeof(struct lpfc_sli4_cfg_mhdr));
19271 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
19272 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
19273 			 length, LPFC_SLI4_MBX_EMBED);
19274 
19275 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19276 	/* Set count to 0 for invalidating the entire FCF database */
19277 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
19278 
19279 	/* Issue the mailbox command asynchronously */
19280 	mbox->vport = phba->pport;
19281 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
19282 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
19283 
19284 	if (rc == MBX_NOT_FINISHED) {
19285 		mempool_free(mbox, phba->mbox_mem_pool);
19286 		return -EIO;
19287 	}
19288 	return 0;
19289 }
19290 
19291 /**
19292  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
19293  * @phba: pointer to lpfc hba data structure.
19294  *
19295  * This function is the failover routine as a last resort to the FCF DEAD
19296  * event when driver failed to perform fast FCF failover.
19297  **/
19298 void
19299 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
19300 {
19301 	uint32_t link_state;
19302 
19303 	/*
19304 	 * Last resort as FCF DEAD event failover will treat this as
19305 	 * a link down, but save the link state because we don't want
19306 	 * it to be changed to Link Down unless it is already down.
19307 	 */
19308 	link_state = phba->link_state;
19309 	lpfc_linkdown(phba);
19310 	phba->link_state = link_state;
19311 
19312 	/* Unregister FCF if no devices connected to it */
19313 	lpfc_unregister_unused_fcf(phba);
19314 }
19315 
19316 /**
19317  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
19318  * @phba: pointer to lpfc hba data structure.
19319  * @rgn23_data: pointer to configure region 23 data.
19320  *
19321  * This function gets SLI3 port configure region 23 data through memory dump
19322  * mailbox command. When it successfully retrieves data, the size of the data
19323  * will be returned, otherwise, 0 will be returned.
19324  **/
19325 static uint32_t
19326 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19327 {
19328 	LPFC_MBOXQ_t *pmb = NULL;
19329 	MAILBOX_t *mb;
19330 	uint32_t offset = 0;
19331 	int rc;
19332 
19333 	if (!rgn23_data)
19334 		return 0;
19335 
19336 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19337 	if (!pmb) {
19338 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19339 				"2600 failed to allocate mailbox memory\n");
19340 		return 0;
19341 	}
19342 	mb = &pmb->u.mb;
19343 
19344 	do {
19345 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
19346 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
19347 
19348 		if (rc != MBX_SUCCESS) {
19349 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19350 					"2601 failed to read config "
19351 					"region 23, rc 0x%x Status 0x%x\n",
19352 					rc, mb->mbxStatus);
19353 			mb->un.varDmp.word_cnt = 0;
19354 		}
19355 		/*
19356 		 * dump mem may return a zero when finished or we got a
19357 		 * mailbox error, either way we are done.
19358 		 */
19359 		if (mb->un.varDmp.word_cnt == 0)
19360 			break;
19361 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
19362 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
19363 
19364 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
19365 				       rgn23_data + offset,
19366 				       mb->un.varDmp.word_cnt);
19367 		offset += mb->un.varDmp.word_cnt;
19368 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
19369 
19370 	mempool_free(pmb, phba->mbox_mem_pool);
19371 	return offset;
19372 }
19373 
19374 /**
19375  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
19376  * @phba: pointer to lpfc hba data structure.
19377  * @rgn23_data: pointer to configure region 23 data.
19378  *
19379  * This function gets SLI4 port configure region 23 data through memory dump
19380  * mailbox command. When it successfully retrieves data, the size of the data
19381  * will be returned, otherwise, 0 will be returned.
19382  **/
19383 static uint32_t
19384 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19385 {
19386 	LPFC_MBOXQ_t *mboxq = NULL;
19387 	struct lpfc_dmabuf *mp = NULL;
19388 	struct lpfc_mqe *mqe;
19389 	uint32_t data_length = 0;
19390 	int rc;
19391 
19392 	if (!rgn23_data)
19393 		return 0;
19394 
19395 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19396 	if (!mboxq) {
19397 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19398 				"3105 failed to allocate mailbox memory\n");
19399 		return 0;
19400 	}
19401 
19402 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
19403 		goto out;
19404 	mqe = &mboxq->u.mqe;
19405 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
19406 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19407 	if (rc)
19408 		goto out;
19409 	data_length = mqe->un.mb_words[5];
19410 	if (data_length == 0)
19411 		goto out;
19412 	if (data_length > DMP_RGN23_SIZE) {
19413 		data_length = 0;
19414 		goto out;
19415 	}
19416 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
19417 out:
19418 	mempool_free(mboxq, phba->mbox_mem_pool);
19419 	if (mp) {
19420 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
19421 		kfree(mp);
19422 	}
19423 	return data_length;
19424 }
19425 
19426 /**
19427  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
19428  * @phba: pointer to lpfc hba data structure.
19429  *
19430  * This function read region 23 and parse TLV for port status to
19431  * decide if the user disaled the port. If the TLV indicates the
19432  * port is disabled, the hba_flag is set accordingly.
19433  **/
19434 void
19435 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
19436 {
19437 	uint8_t *rgn23_data = NULL;
19438 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
19439 	uint32_t offset = 0;
19440 
19441 	/* Get adapter Region 23 data */
19442 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
19443 	if (!rgn23_data)
19444 		goto out;
19445 
19446 	if (phba->sli_rev < LPFC_SLI_REV4)
19447 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
19448 	else {
19449 		if_type = bf_get(lpfc_sli_intf_if_type,
19450 				 &phba->sli4_hba.sli_intf);
19451 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
19452 			goto out;
19453 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
19454 	}
19455 
19456 	if (!data_size)
19457 		goto out;
19458 
19459 	/* Check the region signature first */
19460 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
19461 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19462 			"2619 Config region 23 has bad signature\n");
19463 			goto out;
19464 	}
19465 	offset += 4;
19466 
19467 	/* Check the data structure version */
19468 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
19469 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19470 			"2620 Config region 23 has bad version\n");
19471 		goto out;
19472 	}
19473 	offset += 4;
19474 
19475 	/* Parse TLV entries in the region */
19476 	while (offset < data_size) {
19477 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
19478 			break;
19479 		/*
19480 		 * If the TLV is not driver specific TLV or driver id is
19481 		 * not linux driver id, skip the record.
19482 		 */
19483 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
19484 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
19485 		    (rgn23_data[offset + 3] != 0)) {
19486 			offset += rgn23_data[offset + 1] * 4 + 4;
19487 			continue;
19488 		}
19489 
19490 		/* Driver found a driver specific TLV in the config region */
19491 		sub_tlv_len = rgn23_data[offset + 1] * 4;
19492 		offset += 4;
19493 		tlv_offset = 0;
19494 
19495 		/*
19496 		 * Search for configured port state sub-TLV.
19497 		 */
19498 		while ((offset < data_size) &&
19499 			(tlv_offset < sub_tlv_len)) {
19500 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
19501 				offset += 4;
19502 				tlv_offset += 4;
19503 				break;
19504 			}
19505 			if (rgn23_data[offset] != PORT_STE_TYPE) {
19506 				offset += rgn23_data[offset + 1] * 4 + 4;
19507 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
19508 				continue;
19509 			}
19510 
19511 			/* This HBA contains PORT_STE configured */
19512 			if (!rgn23_data[offset + 2])
19513 				phba->hba_flag |= LINK_DISABLED;
19514 
19515 			goto out;
19516 		}
19517 	}
19518 
19519 out:
19520 	kfree(rgn23_data);
19521 	return;
19522 }
19523 
19524 /**
19525  * lpfc_wr_object - write an object to the firmware
19526  * @phba: HBA structure that indicates port to create a queue on.
19527  * @dmabuf_list: list of dmabufs to write to the port.
19528  * @size: the total byte value of the objects to write to the port.
19529  * @offset: the current offset to be used to start the transfer.
19530  *
19531  * This routine will create a wr_object mailbox command to send to the port.
19532  * the mailbox command will be constructed using the dma buffers described in
19533  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
19534  * BDEs that the imbedded mailbox can support. The @offset variable will be
19535  * used to indicate the starting offset of the transfer and will also return
19536  * the offset after the write object mailbox has completed. @size is used to
19537  * determine the end of the object and whether the eof bit should be set.
19538  *
19539  * Return 0 is successful and offset will contain the the new offset to use
19540  * for the next write.
19541  * Return negative value for error cases.
19542  **/
19543 int
19544 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
19545 	       uint32_t size, uint32_t *offset)
19546 {
19547 	struct lpfc_mbx_wr_object *wr_object;
19548 	LPFC_MBOXQ_t *mbox;
19549 	int rc = 0, i = 0;
19550 	uint32_t shdr_status, shdr_add_status, shdr_change_status, shdr_csf;
19551 	uint32_t mbox_tmo;
19552 	struct lpfc_dmabuf *dmabuf;
19553 	uint32_t written = 0;
19554 	bool check_change_status = false;
19555 
19556 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19557 	if (!mbox)
19558 		return -ENOMEM;
19559 
19560 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
19561 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
19562 			sizeof(struct lpfc_mbx_wr_object) -
19563 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
19564 
19565 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
19566 	wr_object->u.request.write_offset = *offset;
19567 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
19568 	wr_object->u.request.object_name[0] =
19569 		cpu_to_le32(wr_object->u.request.object_name[0]);
19570 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
19571 	list_for_each_entry(dmabuf, dmabuf_list, list) {
19572 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
19573 			break;
19574 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
19575 		wr_object->u.request.bde[i].addrHigh =
19576 			putPaddrHigh(dmabuf->phys);
19577 		if (written + SLI4_PAGE_SIZE >= size) {
19578 			wr_object->u.request.bde[i].tus.f.bdeSize =
19579 				(size - written);
19580 			written += (size - written);
19581 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
19582 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
19583 			check_change_status = true;
19584 		} else {
19585 			wr_object->u.request.bde[i].tus.f.bdeSize =
19586 				SLI4_PAGE_SIZE;
19587 			written += SLI4_PAGE_SIZE;
19588 		}
19589 		i++;
19590 	}
19591 	wr_object->u.request.bde_count = i;
19592 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
19593 	if (!phba->sli4_hba.intr_enable)
19594 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
19595 	else {
19596 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
19597 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
19598 	}
19599 	/* The IOCTL status is embedded in the mailbox subheader. */
19600 	shdr_status = bf_get(lpfc_mbox_hdr_status,
19601 			     &wr_object->header.cfg_shdr.response);
19602 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
19603 				 &wr_object->header.cfg_shdr.response);
19604 	if (check_change_status) {
19605 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
19606 					    &wr_object->u.response);
19607 
19608 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
19609 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
19610 			shdr_csf = bf_get(lpfc_wr_object_csf,
19611 					  &wr_object->u.response);
19612 			if (shdr_csf)
19613 				shdr_change_status =
19614 						   LPFC_CHANGE_STATUS_PCI_RESET;
19615 		}
19616 
19617 		switch (shdr_change_status) {
19618 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
19619 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19620 					"3198 Firmware write complete: System "
19621 					"reboot required to instantiate\n");
19622 			break;
19623 		case (LPFC_CHANGE_STATUS_FW_RESET):
19624 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19625 					"3199 Firmware write complete: Firmware"
19626 					" reset required to instantiate\n");
19627 			break;
19628 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
19629 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19630 					"3200 Firmware write complete: Port "
19631 					"Migration or PCI Reset required to "
19632 					"instantiate\n");
19633 			break;
19634 		case (LPFC_CHANGE_STATUS_PCI_RESET):
19635 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19636 					"3201 Firmware write complete: PCI "
19637 					"Reset required to instantiate\n");
19638 			break;
19639 		default:
19640 			break;
19641 		}
19642 	}
19643 	if (rc != MBX_TIMEOUT)
19644 		mempool_free(mbox, phba->mbox_mem_pool);
19645 	if (shdr_status || shdr_add_status || rc) {
19646 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19647 				"3025 Write Object mailbox failed with "
19648 				"status x%x add_status x%x, mbx status x%x\n",
19649 				shdr_status, shdr_add_status, rc);
19650 		rc = -ENXIO;
19651 		*offset = shdr_add_status;
19652 	} else
19653 		*offset += wr_object->u.response.actual_write_length;
19654 	return rc;
19655 }
19656 
19657 /**
19658  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
19659  * @vport: pointer to vport data structure.
19660  *
19661  * This function iterate through the mailboxq and clean up all REG_LOGIN
19662  * and REG_VPI mailbox commands associated with the vport. This function
19663  * is called when driver want to restart discovery of the vport due to
19664  * a Clear Virtual Link event.
19665  **/
19666 void
19667 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
19668 {
19669 	struct lpfc_hba *phba = vport->phba;
19670 	LPFC_MBOXQ_t *mb, *nextmb;
19671 	struct lpfc_dmabuf *mp;
19672 	struct lpfc_nodelist *ndlp;
19673 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
19674 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
19675 	LIST_HEAD(mbox_cmd_list);
19676 	uint8_t restart_loop;
19677 
19678 	/* Clean up internally queued mailbox commands with the vport */
19679 	spin_lock_irq(&phba->hbalock);
19680 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
19681 		if (mb->vport != vport)
19682 			continue;
19683 
19684 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
19685 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
19686 			continue;
19687 
19688 		list_del(&mb->list);
19689 		list_add_tail(&mb->list, &mbox_cmd_list);
19690 	}
19691 	/* Clean up active mailbox command with the vport */
19692 	mb = phba->sli.mbox_active;
19693 	if (mb && (mb->vport == vport)) {
19694 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
19695 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
19696 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19697 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19698 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19699 			/* Put reference count for delayed processing */
19700 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
19701 			/* Unregister the RPI when mailbox complete */
19702 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
19703 		}
19704 	}
19705 	/* Cleanup any mailbox completions which are not yet processed */
19706 	do {
19707 		restart_loop = 0;
19708 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
19709 			/*
19710 			 * If this mailox is already processed or it is
19711 			 * for another vport ignore it.
19712 			 */
19713 			if ((mb->vport != vport) ||
19714 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
19715 				continue;
19716 
19717 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
19718 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
19719 				continue;
19720 
19721 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19722 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19723 				ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19724 				/* Unregister the RPI when mailbox complete */
19725 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
19726 				restart_loop = 1;
19727 				spin_unlock_irq(&phba->hbalock);
19728 				spin_lock(shost->host_lock);
19729 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19730 				spin_unlock(shost->host_lock);
19731 				spin_lock_irq(&phba->hbalock);
19732 				break;
19733 			}
19734 		}
19735 	} while (restart_loop);
19736 
19737 	spin_unlock_irq(&phba->hbalock);
19738 
19739 	/* Release the cleaned-up mailbox commands */
19740 	while (!list_empty(&mbox_cmd_list)) {
19741 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
19742 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19743 			mp = (struct lpfc_dmabuf *)(mb->ctx_buf);
19744 			if (mp) {
19745 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
19746 				kfree(mp);
19747 			}
19748 			mb->ctx_buf = NULL;
19749 			ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19750 			mb->ctx_ndlp = NULL;
19751 			if (ndlp) {
19752 				spin_lock(shost->host_lock);
19753 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19754 				spin_unlock(shost->host_lock);
19755 				lpfc_nlp_put(ndlp);
19756 			}
19757 		}
19758 		mempool_free(mb, phba->mbox_mem_pool);
19759 	}
19760 
19761 	/* Release the ndlp with the cleaned-up active mailbox command */
19762 	if (act_mbx_ndlp) {
19763 		spin_lock(shost->host_lock);
19764 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19765 		spin_unlock(shost->host_lock);
19766 		lpfc_nlp_put(act_mbx_ndlp);
19767 	}
19768 }
19769 
19770 /**
19771  * lpfc_drain_txq - Drain the txq
19772  * @phba: Pointer to HBA context object.
19773  *
19774  * This function attempt to submit IOCBs on the txq
19775  * to the adapter.  For SLI4 adapters, the txq contains
19776  * ELS IOCBs that have been deferred because the there
19777  * are no SGLs.  This congestion can occur with large
19778  * vport counts during node discovery.
19779  **/
19780 
19781 uint32_t
19782 lpfc_drain_txq(struct lpfc_hba *phba)
19783 {
19784 	LIST_HEAD(completions);
19785 	struct lpfc_sli_ring *pring;
19786 	struct lpfc_iocbq *piocbq = NULL;
19787 	unsigned long iflags = 0;
19788 	char *fail_msg = NULL;
19789 	struct lpfc_sglq *sglq;
19790 	union lpfc_wqe128 wqe;
19791 	uint32_t txq_cnt = 0;
19792 	struct lpfc_queue *wq;
19793 
19794 	if (phba->link_flag & LS_MDS_LOOPBACK) {
19795 		/* MDS WQE are posted only to first WQ*/
19796 		wq = phba->sli4_hba.hdwq[0].io_wq;
19797 		if (unlikely(!wq))
19798 			return 0;
19799 		pring = wq->pring;
19800 	} else {
19801 		wq = phba->sli4_hba.els_wq;
19802 		if (unlikely(!wq))
19803 			return 0;
19804 		pring = lpfc_phba_elsring(phba);
19805 	}
19806 
19807 	if (unlikely(!pring) || list_empty(&pring->txq))
19808 		return 0;
19809 
19810 	spin_lock_irqsave(&pring->ring_lock, iflags);
19811 	list_for_each_entry(piocbq, &pring->txq, list) {
19812 		txq_cnt++;
19813 	}
19814 
19815 	if (txq_cnt > pring->txq_max)
19816 		pring->txq_max = txq_cnt;
19817 
19818 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
19819 
19820 	while (!list_empty(&pring->txq)) {
19821 		spin_lock_irqsave(&pring->ring_lock, iflags);
19822 
19823 		piocbq = lpfc_sli_ringtx_get(phba, pring);
19824 		if (!piocbq) {
19825 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19826 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
19827 				"2823 txq empty and txq_cnt is %d\n ",
19828 				txq_cnt);
19829 			break;
19830 		}
19831 		sglq = __lpfc_sli_get_els_sglq(phba, piocbq);
19832 		if (!sglq) {
19833 			__lpfc_sli_ringtx_put(phba, pring, piocbq);
19834 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19835 			break;
19836 		}
19837 		txq_cnt--;
19838 
19839 		/* The xri and iocb resources secured,
19840 		 * attempt to issue request
19841 		 */
19842 		piocbq->sli4_lxritag = sglq->sli4_lxritag;
19843 		piocbq->sli4_xritag = sglq->sli4_xritag;
19844 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
19845 			fail_msg = "to convert bpl to sgl";
19846 		else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
19847 			fail_msg = "to convert iocb to wqe";
19848 		else if (lpfc_sli4_wq_put(wq, &wqe))
19849 			fail_msg = " - Wq is full";
19850 		else
19851 			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
19852 
19853 		if (fail_msg) {
19854 			/* Failed means we can't issue and need to cancel */
19855 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
19856 					"2822 IOCB failed %s iotag 0x%x "
19857 					"xri 0x%x\n",
19858 					fail_msg,
19859 					piocbq->iotag, piocbq->sli4_xritag);
19860 			list_add_tail(&piocbq->list, &completions);
19861 		}
19862 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
19863 	}
19864 
19865 	/* Cancel all the IOCBs that cannot be issued */
19866 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
19867 				IOERR_SLI_ABORTED);
19868 
19869 	return txq_cnt;
19870 }
19871 
19872 /**
19873  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
19874  * @phba: Pointer to HBA context object.
19875  * @pwqe: Pointer to command WQE.
19876  * @sglq: Pointer to the scatter gather queue object.
19877  *
19878  * This routine converts the bpl or bde that is in the WQE
19879  * to a sgl list for the sli4 hardware. The physical address
19880  * of the bpl/bde is converted back to a virtual address.
19881  * If the WQE contains a BPL then the list of BDE's is
19882  * converted to sli4_sge's. If the WQE contains a single
19883  * BDE then it is converted to a single sli_sge.
19884  * The WQE is still in cpu endianness so the contents of
19885  * the bpl can be used without byte swapping.
19886  *
19887  * Returns valid XRI = Success, NO_XRI = Failure.
19888  */
19889 static uint16_t
19890 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
19891 		 struct lpfc_sglq *sglq)
19892 {
19893 	uint16_t xritag = NO_XRI;
19894 	struct ulp_bde64 *bpl = NULL;
19895 	struct ulp_bde64 bde;
19896 	struct sli4_sge *sgl  = NULL;
19897 	struct lpfc_dmabuf *dmabuf;
19898 	union lpfc_wqe128 *wqe;
19899 	int numBdes = 0;
19900 	int i = 0;
19901 	uint32_t offset = 0; /* accumulated offset in the sg request list */
19902 	int inbound = 0; /* number of sg reply entries inbound from firmware */
19903 	uint32_t cmd;
19904 
19905 	if (!pwqeq || !sglq)
19906 		return xritag;
19907 
19908 	sgl  = (struct sli4_sge *)sglq->sgl;
19909 	wqe = &pwqeq->wqe;
19910 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
19911 
19912 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
19913 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
19914 		return sglq->sli4_xritag;
19915 	numBdes = pwqeq->rsvd2;
19916 	if (numBdes) {
19917 		/* The addrHigh and addrLow fields within the WQE
19918 		 * have not been byteswapped yet so there is no
19919 		 * need to swap them back.
19920 		 */
19921 		if (pwqeq->context3)
19922 			dmabuf = (struct lpfc_dmabuf *)pwqeq->context3;
19923 		else
19924 			return xritag;
19925 
19926 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
19927 		if (!bpl)
19928 			return xritag;
19929 
19930 		for (i = 0; i < numBdes; i++) {
19931 			/* Should already be byte swapped. */
19932 			sgl->addr_hi = bpl->addrHigh;
19933 			sgl->addr_lo = bpl->addrLow;
19934 
19935 			sgl->word2 = le32_to_cpu(sgl->word2);
19936 			if ((i+1) == numBdes)
19937 				bf_set(lpfc_sli4_sge_last, sgl, 1);
19938 			else
19939 				bf_set(lpfc_sli4_sge_last, sgl, 0);
19940 			/* swap the size field back to the cpu so we
19941 			 * can assign it to the sgl.
19942 			 */
19943 			bde.tus.w = le32_to_cpu(bpl->tus.w);
19944 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
19945 			/* The offsets in the sgl need to be accumulated
19946 			 * separately for the request and reply lists.
19947 			 * The request is always first, the reply follows.
19948 			 */
19949 			switch (cmd) {
19950 			case CMD_GEN_REQUEST64_WQE:
19951 				/* add up the reply sg entries */
19952 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
19953 					inbound++;
19954 				/* first inbound? reset the offset */
19955 				if (inbound == 1)
19956 					offset = 0;
19957 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
19958 				bf_set(lpfc_sli4_sge_type, sgl,
19959 					LPFC_SGE_TYPE_DATA);
19960 				offset += bde.tus.f.bdeSize;
19961 				break;
19962 			case CMD_FCP_TRSP64_WQE:
19963 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
19964 				bf_set(lpfc_sli4_sge_type, sgl,
19965 					LPFC_SGE_TYPE_DATA);
19966 				break;
19967 			case CMD_FCP_TSEND64_WQE:
19968 			case CMD_FCP_TRECEIVE64_WQE:
19969 				bf_set(lpfc_sli4_sge_type, sgl,
19970 					bpl->tus.f.bdeFlags);
19971 				if (i < 3)
19972 					offset = 0;
19973 				else
19974 					offset += bde.tus.f.bdeSize;
19975 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
19976 				break;
19977 			}
19978 			sgl->word2 = cpu_to_le32(sgl->word2);
19979 			bpl++;
19980 			sgl++;
19981 		}
19982 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
19983 		/* The addrHigh and addrLow fields of the BDE have not
19984 		 * been byteswapped yet so they need to be swapped
19985 		 * before putting them in the sgl.
19986 		 */
19987 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
19988 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
19989 		sgl->word2 = le32_to_cpu(sgl->word2);
19990 		bf_set(lpfc_sli4_sge_last, sgl, 1);
19991 		sgl->word2 = cpu_to_le32(sgl->word2);
19992 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
19993 	}
19994 	return sglq->sli4_xritag;
19995 }
19996 
19997 /**
19998  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
19999  * @phba: Pointer to HBA context object.
20000  * @ring_number: Base sli ring number
20001  * @pwqe: Pointer to command WQE.
20002  **/
20003 int
20004 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
20005 		    struct lpfc_iocbq *pwqe)
20006 {
20007 	union lpfc_wqe128 *wqe = &pwqe->wqe;
20008 	struct lpfc_async_xchg_ctx *ctxp;
20009 	struct lpfc_queue *wq;
20010 	struct lpfc_sglq *sglq;
20011 	struct lpfc_sli_ring *pring;
20012 	unsigned long iflags;
20013 	uint32_t ret = 0;
20014 
20015 	/* NVME_LS and NVME_LS ABTS requests. */
20016 	if (pwqe->iocb_flag & LPFC_IO_NVME_LS) {
20017 		pring =  phba->sli4_hba.nvmels_wq->pring;
20018 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20019 					  qp, wq_access);
20020 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
20021 		if (!sglq) {
20022 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20023 			return WQE_BUSY;
20024 		}
20025 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
20026 		pwqe->sli4_xritag = sglq->sli4_xritag;
20027 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
20028 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20029 			return WQE_ERROR;
20030 		}
20031 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
20032 		       pwqe->sli4_xritag);
20033 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
20034 		if (ret) {
20035 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20036 			return ret;
20037 		}
20038 
20039 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20040 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20041 
20042 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20043 		return 0;
20044 	}
20045 
20046 	/* NVME_FCREQ and NVME_ABTS requests */
20047 	if (pwqe->iocb_flag & LPFC_IO_NVME) {
20048 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
20049 		wq = qp->io_wq;
20050 		pring = wq->pring;
20051 
20052 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
20053 
20054 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20055 					  qp, wq_access);
20056 		ret = lpfc_sli4_wq_put(wq, wqe);
20057 		if (ret) {
20058 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20059 			return ret;
20060 		}
20061 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20062 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20063 
20064 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20065 		return 0;
20066 	}
20067 
20068 	/* NVMET requests */
20069 	if (pwqe->iocb_flag & LPFC_IO_NVMET) {
20070 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
20071 		wq = qp->io_wq;
20072 		pring = wq->pring;
20073 
20074 		ctxp = pwqe->context2;
20075 		sglq = ctxp->ctxbuf->sglq;
20076 		if (pwqe->sli4_xritag ==  NO_XRI) {
20077 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
20078 			pwqe->sli4_xritag = sglq->sli4_xritag;
20079 		}
20080 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
20081 		       pwqe->sli4_xritag);
20082 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
20083 
20084 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20085 					  qp, wq_access);
20086 		ret = lpfc_sli4_wq_put(wq, wqe);
20087 		if (ret) {
20088 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20089 			return ret;
20090 		}
20091 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20092 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20093 
20094 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20095 		return 0;
20096 	}
20097 	return WQE_ERROR;
20098 }
20099 
20100 #ifdef LPFC_MXP_STAT
20101 /**
20102  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
20103  * @phba: pointer to lpfc hba data structure.
20104  * @hwqid: belong to which HWQ.
20105  *
20106  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
20107  * 15 seconds after a test case is running.
20108  *
20109  * The user should call lpfc_debugfs_multixripools_write before running a test
20110  * case to clear stat_snapshot_taken. Then the user starts a test case. During
20111  * test case is running, stat_snapshot_taken is incremented by 1 every time when
20112  * this routine is called from heartbeat timer. When stat_snapshot_taken is
20113  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
20114  **/
20115 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
20116 {
20117 	struct lpfc_sli4_hdw_queue *qp;
20118 	struct lpfc_multixri_pool *multixri_pool;
20119 	struct lpfc_pvt_pool *pvt_pool;
20120 	struct lpfc_pbl_pool *pbl_pool;
20121 	u32 txcmplq_cnt;
20122 
20123 	qp = &phba->sli4_hba.hdwq[hwqid];
20124 	multixri_pool = qp->p_multixri_pool;
20125 	if (!multixri_pool)
20126 		return;
20127 
20128 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
20129 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
20130 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
20131 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20132 
20133 		multixri_pool->stat_pbl_count = pbl_pool->count;
20134 		multixri_pool->stat_pvt_count = pvt_pool->count;
20135 		multixri_pool->stat_busy_count = txcmplq_cnt;
20136 	}
20137 
20138 	multixri_pool->stat_snapshot_taken++;
20139 }
20140 #endif
20141 
20142 /**
20143  * lpfc_adjust_pvt_pool_count - Adjust private pool count
20144  * @phba: pointer to lpfc hba data structure.
20145  * @hwqid: belong to which HWQ.
20146  *
20147  * This routine moves some XRIs from private to public pool when private pool
20148  * is not busy.
20149  **/
20150 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
20151 {
20152 	struct lpfc_multixri_pool *multixri_pool;
20153 	u32 io_req_count;
20154 	u32 prev_io_req_count;
20155 
20156 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
20157 	if (!multixri_pool)
20158 		return;
20159 	io_req_count = multixri_pool->io_req_count;
20160 	prev_io_req_count = multixri_pool->prev_io_req_count;
20161 
20162 	if (prev_io_req_count != io_req_count) {
20163 		/* Private pool is busy */
20164 		multixri_pool->prev_io_req_count = io_req_count;
20165 	} else {
20166 		/* Private pool is not busy.
20167 		 * Move XRIs from private to public pool.
20168 		 */
20169 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
20170 	}
20171 }
20172 
20173 /**
20174  * lpfc_adjust_high_watermark - Adjust high watermark
20175  * @phba: pointer to lpfc hba data structure.
20176  * @hwqid: belong to which HWQ.
20177  *
20178  * This routine sets high watermark as number of outstanding XRIs,
20179  * but make sure the new value is between xri_limit/2 and xri_limit.
20180  **/
20181 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
20182 {
20183 	u32 new_watermark;
20184 	u32 watermark_max;
20185 	u32 watermark_min;
20186 	u32 xri_limit;
20187 	u32 txcmplq_cnt;
20188 	u32 abts_io_bufs;
20189 	struct lpfc_multixri_pool *multixri_pool;
20190 	struct lpfc_sli4_hdw_queue *qp;
20191 
20192 	qp = &phba->sli4_hba.hdwq[hwqid];
20193 	multixri_pool = qp->p_multixri_pool;
20194 	if (!multixri_pool)
20195 		return;
20196 	xri_limit = multixri_pool->xri_limit;
20197 
20198 	watermark_max = xri_limit;
20199 	watermark_min = xri_limit / 2;
20200 
20201 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20202 	abts_io_bufs = qp->abts_scsi_io_bufs;
20203 	abts_io_bufs += qp->abts_nvme_io_bufs;
20204 
20205 	new_watermark = txcmplq_cnt + abts_io_bufs;
20206 	new_watermark = min(watermark_max, new_watermark);
20207 	new_watermark = max(watermark_min, new_watermark);
20208 	multixri_pool->pvt_pool.high_watermark = new_watermark;
20209 
20210 #ifdef LPFC_MXP_STAT
20211 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
20212 					  new_watermark);
20213 #endif
20214 }
20215 
20216 /**
20217  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
20218  * @phba: pointer to lpfc hba data structure.
20219  * @hwqid: belong to which HWQ.
20220  *
20221  * This routine is called from hearbeat timer when pvt_pool is idle.
20222  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
20223  * The first step moves (all - low_watermark) amount of XRIs.
20224  * The second step moves the rest of XRIs.
20225  **/
20226 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
20227 {
20228 	struct lpfc_pbl_pool *pbl_pool;
20229 	struct lpfc_pvt_pool *pvt_pool;
20230 	struct lpfc_sli4_hdw_queue *qp;
20231 	struct lpfc_io_buf *lpfc_ncmd;
20232 	struct lpfc_io_buf *lpfc_ncmd_next;
20233 	unsigned long iflag;
20234 	struct list_head tmp_list;
20235 	u32 tmp_count;
20236 
20237 	qp = &phba->sli4_hba.hdwq[hwqid];
20238 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
20239 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
20240 	tmp_count = 0;
20241 
20242 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
20243 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
20244 
20245 	if (pvt_pool->count > pvt_pool->low_watermark) {
20246 		/* Step 1: move (all - low_watermark) from pvt_pool
20247 		 * to pbl_pool
20248 		 */
20249 
20250 		/* Move low watermark of bufs from pvt_pool to tmp_list */
20251 		INIT_LIST_HEAD(&tmp_list);
20252 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20253 					 &pvt_pool->list, list) {
20254 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
20255 			tmp_count++;
20256 			if (tmp_count >= pvt_pool->low_watermark)
20257 				break;
20258 		}
20259 
20260 		/* Move all bufs from pvt_pool to pbl_pool */
20261 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
20262 
20263 		/* Move all bufs from tmp_list to pvt_pool */
20264 		list_splice(&tmp_list, &pvt_pool->list);
20265 
20266 		pbl_pool->count += (pvt_pool->count - tmp_count);
20267 		pvt_pool->count = tmp_count;
20268 	} else {
20269 		/* Step 2: move the rest from pvt_pool to pbl_pool */
20270 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
20271 		pbl_pool->count += pvt_pool->count;
20272 		pvt_pool->count = 0;
20273 	}
20274 
20275 	spin_unlock(&pvt_pool->lock);
20276 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20277 }
20278 
20279 /**
20280  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
20281  * @phba: pointer to lpfc hba data structure
20282  * @pbl_pool: specified public free XRI pool
20283  * @pvt_pool: specified private free XRI pool
20284  * @count: number of XRIs to move
20285  *
20286  * This routine tries to move some free common bufs from the specified pbl_pool
20287  * to the specified pvt_pool. It might move less than count XRIs if there's not
20288  * enough in public pool.
20289  *
20290  * Return:
20291  *   true - if XRIs are successfully moved from the specified pbl_pool to the
20292  *          specified pvt_pool
20293  *   false - if the specified pbl_pool is empty or locked by someone else
20294  **/
20295 static bool
20296 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
20297 			  struct lpfc_pbl_pool *pbl_pool,
20298 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
20299 {
20300 	struct lpfc_io_buf *lpfc_ncmd;
20301 	struct lpfc_io_buf *lpfc_ncmd_next;
20302 	unsigned long iflag;
20303 	int ret;
20304 
20305 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
20306 	if (ret) {
20307 		if (pbl_pool->count) {
20308 			/* Move a batch of XRIs from public to private pool */
20309 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
20310 			list_for_each_entry_safe(lpfc_ncmd,
20311 						 lpfc_ncmd_next,
20312 						 &pbl_pool->list,
20313 						 list) {
20314 				list_move_tail(&lpfc_ncmd->list,
20315 					       &pvt_pool->list);
20316 				pvt_pool->count++;
20317 				pbl_pool->count--;
20318 				count--;
20319 				if (count == 0)
20320 					break;
20321 			}
20322 
20323 			spin_unlock(&pvt_pool->lock);
20324 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20325 			return true;
20326 		}
20327 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20328 	}
20329 
20330 	return false;
20331 }
20332 
20333 /**
20334  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
20335  * @phba: pointer to lpfc hba data structure.
20336  * @hwqid: belong to which HWQ.
20337  * @count: number of XRIs to move
20338  *
20339  * This routine tries to find some free common bufs in one of public pools with
20340  * Round Robin method. The search always starts from local hwqid, then the next
20341  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
20342  * a batch of free common bufs are moved to private pool on hwqid.
20343  * It might move less than count XRIs if there's not enough in public pool.
20344  **/
20345 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
20346 {
20347 	struct lpfc_multixri_pool *multixri_pool;
20348 	struct lpfc_multixri_pool *next_multixri_pool;
20349 	struct lpfc_pvt_pool *pvt_pool;
20350 	struct lpfc_pbl_pool *pbl_pool;
20351 	struct lpfc_sli4_hdw_queue *qp;
20352 	u32 next_hwqid;
20353 	u32 hwq_count;
20354 	int ret;
20355 
20356 	qp = &phba->sli4_hba.hdwq[hwqid];
20357 	multixri_pool = qp->p_multixri_pool;
20358 	pvt_pool = &multixri_pool->pvt_pool;
20359 	pbl_pool = &multixri_pool->pbl_pool;
20360 
20361 	/* Check if local pbl_pool is available */
20362 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
20363 	if (ret) {
20364 #ifdef LPFC_MXP_STAT
20365 		multixri_pool->local_pbl_hit_count++;
20366 #endif
20367 		return;
20368 	}
20369 
20370 	hwq_count = phba->cfg_hdw_queue;
20371 
20372 	/* Get the next hwqid which was found last time */
20373 	next_hwqid = multixri_pool->rrb_next_hwqid;
20374 
20375 	do {
20376 		/* Go to next hwq */
20377 		next_hwqid = (next_hwqid + 1) % hwq_count;
20378 
20379 		next_multixri_pool =
20380 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
20381 		pbl_pool = &next_multixri_pool->pbl_pool;
20382 
20383 		/* Check if the public free xri pool is available */
20384 		ret = _lpfc_move_xri_pbl_to_pvt(
20385 			phba, qp, pbl_pool, pvt_pool, count);
20386 
20387 		/* Exit while-loop if success or all hwqid are checked */
20388 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
20389 
20390 	/* Starting point for the next time */
20391 	multixri_pool->rrb_next_hwqid = next_hwqid;
20392 
20393 	if (!ret) {
20394 		/* stats: all public pools are empty*/
20395 		multixri_pool->pbl_empty_count++;
20396 	}
20397 
20398 #ifdef LPFC_MXP_STAT
20399 	if (ret) {
20400 		if (next_hwqid == hwqid)
20401 			multixri_pool->local_pbl_hit_count++;
20402 		else
20403 			multixri_pool->other_pbl_hit_count++;
20404 	}
20405 #endif
20406 }
20407 
20408 /**
20409  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
20410  * @phba: pointer to lpfc hba data structure.
20411  * @qp: belong to which HWQ.
20412  *
20413  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
20414  * low watermark.
20415  **/
20416 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
20417 {
20418 	struct lpfc_multixri_pool *multixri_pool;
20419 	struct lpfc_pvt_pool *pvt_pool;
20420 
20421 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
20422 	pvt_pool = &multixri_pool->pvt_pool;
20423 
20424 	if (pvt_pool->count < pvt_pool->low_watermark)
20425 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
20426 }
20427 
20428 /**
20429  * lpfc_release_io_buf - Return one IO buf back to free pool
20430  * @phba: pointer to lpfc hba data structure.
20431  * @lpfc_ncmd: IO buf to be returned.
20432  * @qp: belong to which HWQ.
20433  *
20434  * This routine returns one IO buf back to free pool. If this is an urgent IO,
20435  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
20436  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
20437  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
20438  * lpfc_io_buf_list_put.
20439  **/
20440 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
20441 			 struct lpfc_sli4_hdw_queue *qp)
20442 {
20443 	unsigned long iflag;
20444 	struct lpfc_pbl_pool *pbl_pool;
20445 	struct lpfc_pvt_pool *pvt_pool;
20446 	struct lpfc_epd_pool *epd_pool;
20447 	u32 txcmplq_cnt;
20448 	u32 xri_owned;
20449 	u32 xri_limit;
20450 	u32 abts_io_bufs;
20451 
20452 	/* MUST zero fields if buffer is reused by another protocol */
20453 	lpfc_ncmd->nvmeCmd = NULL;
20454 	lpfc_ncmd->cur_iocbq.wqe_cmpl = NULL;
20455 	lpfc_ncmd->cur_iocbq.iocb_cmpl = NULL;
20456 
20457 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
20458 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
20459 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
20460 
20461 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
20462 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
20463 
20464 	if (phba->cfg_xri_rebalancing) {
20465 		if (lpfc_ncmd->expedite) {
20466 			/* Return to expedite pool */
20467 			epd_pool = &phba->epd_pool;
20468 			spin_lock_irqsave(&epd_pool->lock, iflag);
20469 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
20470 			epd_pool->count++;
20471 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
20472 			return;
20473 		}
20474 
20475 		/* Avoid invalid access if an IO sneaks in and is being rejected
20476 		 * just _after_ xri pools are destroyed in lpfc_offline.
20477 		 * Nothing much can be done at this point.
20478 		 */
20479 		if (!qp->p_multixri_pool)
20480 			return;
20481 
20482 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
20483 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
20484 
20485 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20486 		abts_io_bufs = qp->abts_scsi_io_bufs;
20487 		abts_io_bufs += qp->abts_nvme_io_bufs;
20488 
20489 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
20490 		xri_limit = qp->p_multixri_pool->xri_limit;
20491 
20492 #ifdef LPFC_MXP_STAT
20493 		if (xri_owned <= xri_limit)
20494 			qp->p_multixri_pool->below_limit_count++;
20495 		else
20496 			qp->p_multixri_pool->above_limit_count++;
20497 #endif
20498 
20499 		/* XRI goes to either public or private free xri pool
20500 		 *     based on watermark and xri_limit
20501 		 */
20502 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
20503 		    (xri_owned < xri_limit &&
20504 		     pvt_pool->count < pvt_pool->high_watermark)) {
20505 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
20506 						  qp, free_pvt_pool);
20507 			list_add_tail(&lpfc_ncmd->list,
20508 				      &pvt_pool->list);
20509 			pvt_pool->count++;
20510 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
20511 		} else {
20512 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
20513 						  qp, free_pub_pool);
20514 			list_add_tail(&lpfc_ncmd->list,
20515 				      &pbl_pool->list);
20516 			pbl_pool->count++;
20517 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20518 		}
20519 	} else {
20520 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
20521 					  qp, free_xri);
20522 		list_add_tail(&lpfc_ncmd->list,
20523 			      &qp->lpfc_io_buf_list_put);
20524 		qp->put_io_bufs++;
20525 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
20526 				       iflag);
20527 	}
20528 }
20529 
20530 /**
20531  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
20532  * @phba: pointer to lpfc hba data structure.
20533  * @pvt_pool: pointer to private pool data structure.
20534  * @ndlp: pointer to lpfc nodelist data structure.
20535  *
20536  * This routine tries to get one free IO buf from private pool.
20537  *
20538  * Return:
20539  *   pointer to one free IO buf - if private pool is not empty
20540  *   NULL - if private pool is empty
20541  **/
20542 static struct lpfc_io_buf *
20543 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
20544 				  struct lpfc_sli4_hdw_queue *qp,
20545 				  struct lpfc_pvt_pool *pvt_pool,
20546 				  struct lpfc_nodelist *ndlp)
20547 {
20548 	struct lpfc_io_buf *lpfc_ncmd;
20549 	struct lpfc_io_buf *lpfc_ncmd_next;
20550 	unsigned long iflag;
20551 
20552 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
20553 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20554 				 &pvt_pool->list, list) {
20555 		if (lpfc_test_rrq_active(
20556 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
20557 			continue;
20558 		list_del(&lpfc_ncmd->list);
20559 		pvt_pool->count--;
20560 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
20561 		return lpfc_ncmd;
20562 	}
20563 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
20564 
20565 	return NULL;
20566 }
20567 
20568 /**
20569  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
20570  * @phba: pointer to lpfc hba data structure.
20571  *
20572  * This routine tries to get one free IO buf from expedite pool.
20573  *
20574  * Return:
20575  *   pointer to one free IO buf - if expedite pool is not empty
20576  *   NULL - if expedite pool is empty
20577  **/
20578 static struct lpfc_io_buf *
20579 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
20580 {
20581 	struct lpfc_io_buf *lpfc_ncmd;
20582 	struct lpfc_io_buf *lpfc_ncmd_next;
20583 	unsigned long iflag;
20584 	struct lpfc_epd_pool *epd_pool;
20585 
20586 	epd_pool = &phba->epd_pool;
20587 	lpfc_ncmd = NULL;
20588 
20589 	spin_lock_irqsave(&epd_pool->lock, iflag);
20590 	if (epd_pool->count > 0) {
20591 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20592 					 &epd_pool->list, list) {
20593 			list_del(&lpfc_ncmd->list);
20594 			epd_pool->count--;
20595 			break;
20596 		}
20597 	}
20598 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
20599 
20600 	return lpfc_ncmd;
20601 }
20602 
20603 /**
20604  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
20605  * @phba: pointer to lpfc hba data structure.
20606  * @ndlp: pointer to lpfc nodelist data structure.
20607  * @hwqid: belong to which HWQ
20608  * @expedite: 1 means this request is urgent.
20609  *
20610  * This routine will do the following actions and then return a pointer to
20611  * one free IO buf.
20612  *
20613  * 1. If private free xri count is empty, move some XRIs from public to
20614  *    private pool.
20615  * 2. Get one XRI from private free xri pool.
20616  * 3. If we fail to get one from pvt_pool and this is an expedite request,
20617  *    get one free xri from expedite pool.
20618  *
20619  * Note: ndlp is only used on SCSI side for RRQ testing.
20620  *       The caller should pass NULL for ndlp on NVME side.
20621  *
20622  * Return:
20623  *   pointer to one free IO buf - if private pool is not empty
20624  *   NULL - if private pool is empty
20625  **/
20626 static struct lpfc_io_buf *
20627 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
20628 				    struct lpfc_nodelist *ndlp,
20629 				    int hwqid, int expedite)
20630 {
20631 	struct lpfc_sli4_hdw_queue *qp;
20632 	struct lpfc_multixri_pool *multixri_pool;
20633 	struct lpfc_pvt_pool *pvt_pool;
20634 	struct lpfc_io_buf *lpfc_ncmd;
20635 
20636 	qp = &phba->sli4_hba.hdwq[hwqid];
20637 	lpfc_ncmd = NULL;
20638 	multixri_pool = qp->p_multixri_pool;
20639 	pvt_pool = &multixri_pool->pvt_pool;
20640 	multixri_pool->io_req_count++;
20641 
20642 	/* If pvt_pool is empty, move some XRIs from public to private pool */
20643 	if (pvt_pool->count == 0)
20644 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
20645 
20646 	/* Get one XRI from private free xri pool */
20647 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
20648 
20649 	if (lpfc_ncmd) {
20650 		lpfc_ncmd->hdwq = qp;
20651 		lpfc_ncmd->hdwq_no = hwqid;
20652 	} else if (expedite) {
20653 		/* If we fail to get one from pvt_pool and this is an expedite
20654 		 * request, get one free xri from expedite pool.
20655 		 */
20656 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
20657 	}
20658 
20659 	return lpfc_ncmd;
20660 }
20661 
20662 static inline struct lpfc_io_buf *
20663 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
20664 {
20665 	struct lpfc_sli4_hdw_queue *qp;
20666 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
20667 
20668 	qp = &phba->sli4_hba.hdwq[idx];
20669 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
20670 				 &qp->lpfc_io_buf_list_get, list) {
20671 		if (lpfc_test_rrq_active(phba, ndlp,
20672 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
20673 			continue;
20674 
20675 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
20676 			continue;
20677 
20678 		list_del_init(&lpfc_cmd->list);
20679 		qp->get_io_bufs--;
20680 		lpfc_cmd->hdwq = qp;
20681 		lpfc_cmd->hdwq_no = idx;
20682 		return lpfc_cmd;
20683 	}
20684 	return NULL;
20685 }
20686 
20687 /**
20688  * lpfc_get_io_buf - Get one IO buffer from free pool
20689  * @phba: The HBA for which this call is being executed.
20690  * @ndlp: pointer to lpfc nodelist data structure.
20691  * @hwqid: belong to which HWQ
20692  * @expedite: 1 means this request is urgent.
20693  *
20694  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
20695  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
20696  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
20697  *
20698  * Note: ndlp is only used on SCSI side for RRQ testing.
20699  *       The caller should pass NULL for ndlp on NVME side.
20700  *
20701  * Return codes:
20702  *   NULL - Error
20703  *   Pointer to lpfc_io_buf - Success
20704  **/
20705 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
20706 				    struct lpfc_nodelist *ndlp,
20707 				    u32 hwqid, int expedite)
20708 {
20709 	struct lpfc_sli4_hdw_queue *qp;
20710 	unsigned long iflag;
20711 	struct lpfc_io_buf *lpfc_cmd;
20712 
20713 	qp = &phba->sli4_hba.hdwq[hwqid];
20714 	lpfc_cmd = NULL;
20715 
20716 	if (phba->cfg_xri_rebalancing)
20717 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
20718 			phba, ndlp, hwqid, expedite);
20719 	else {
20720 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
20721 					  qp, alloc_xri_get);
20722 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
20723 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
20724 		if (!lpfc_cmd) {
20725 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
20726 					  qp, alloc_xri_put);
20727 			list_splice(&qp->lpfc_io_buf_list_put,
20728 				    &qp->lpfc_io_buf_list_get);
20729 			qp->get_io_bufs += qp->put_io_bufs;
20730 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
20731 			qp->put_io_bufs = 0;
20732 			spin_unlock(&qp->io_buf_list_put_lock);
20733 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
20734 			    expedite)
20735 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
20736 		}
20737 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
20738 	}
20739 
20740 	return lpfc_cmd;
20741 }
20742 
20743 /**
20744  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
20745  * @phba: The HBA for which this call is being executed.
20746  * @lpfc_buf: IO buf structure to append the SGL chunk
20747  *
20748  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
20749  * and will allocate an SGL chunk if the pool is empty.
20750  *
20751  * Return codes:
20752  *   NULL - Error
20753  *   Pointer to sli4_hybrid_sgl - Success
20754  **/
20755 struct sli4_hybrid_sgl *
20756 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
20757 {
20758 	struct sli4_hybrid_sgl *list_entry = NULL;
20759 	struct sli4_hybrid_sgl *tmp = NULL;
20760 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
20761 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20762 	struct list_head *buf_list = &hdwq->sgl_list;
20763 	unsigned long iflags;
20764 
20765 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20766 
20767 	if (likely(!list_empty(buf_list))) {
20768 		/* break off 1 chunk from the sgl_list */
20769 		list_for_each_entry_safe(list_entry, tmp,
20770 					 buf_list, list_node) {
20771 			list_move_tail(&list_entry->list_node,
20772 				       &lpfc_buf->dma_sgl_xtra_list);
20773 			break;
20774 		}
20775 	} else {
20776 		/* allocate more */
20777 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20778 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
20779 				   cpu_to_node(hdwq->io_wq->chann));
20780 		if (!tmp) {
20781 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20782 					"8353 error kmalloc memory for HDWQ "
20783 					"%d %s\n",
20784 					lpfc_buf->hdwq_no, __func__);
20785 			return NULL;
20786 		}
20787 
20788 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
20789 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
20790 		if (!tmp->dma_sgl) {
20791 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20792 					"8354 error pool_alloc memory for HDWQ "
20793 					"%d %s\n",
20794 					lpfc_buf->hdwq_no, __func__);
20795 			kfree(tmp);
20796 			return NULL;
20797 		}
20798 
20799 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20800 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
20801 	}
20802 
20803 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
20804 					struct sli4_hybrid_sgl,
20805 					list_node);
20806 
20807 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20808 
20809 	return allocated_sgl;
20810 }
20811 
20812 /**
20813  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
20814  * @phba: The HBA for which this call is being executed.
20815  * @lpfc_buf: IO buf structure with the SGL chunk
20816  *
20817  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
20818  *
20819  * Return codes:
20820  *   0 - Success
20821  *   -EINVAL - Error
20822  **/
20823 int
20824 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
20825 {
20826 	int rc = 0;
20827 	struct sli4_hybrid_sgl *list_entry = NULL;
20828 	struct sli4_hybrid_sgl *tmp = NULL;
20829 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20830 	struct list_head *buf_list = &hdwq->sgl_list;
20831 	unsigned long iflags;
20832 
20833 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20834 
20835 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
20836 		list_for_each_entry_safe(list_entry, tmp,
20837 					 &lpfc_buf->dma_sgl_xtra_list,
20838 					 list_node) {
20839 			list_move_tail(&list_entry->list_node,
20840 				       buf_list);
20841 		}
20842 	} else {
20843 		rc = -EINVAL;
20844 	}
20845 
20846 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20847 	return rc;
20848 }
20849 
20850 /**
20851  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
20852  * @phba: phba object
20853  * @hdwq: hdwq to cleanup sgl buff resources on
20854  *
20855  * This routine frees all SGL chunks of hdwq SGL chunk pool.
20856  *
20857  * Return codes:
20858  *   None
20859  **/
20860 void
20861 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
20862 		       struct lpfc_sli4_hdw_queue *hdwq)
20863 {
20864 	struct list_head *buf_list = &hdwq->sgl_list;
20865 	struct sli4_hybrid_sgl *list_entry = NULL;
20866 	struct sli4_hybrid_sgl *tmp = NULL;
20867 	unsigned long iflags;
20868 
20869 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20870 
20871 	/* Free sgl pool */
20872 	list_for_each_entry_safe(list_entry, tmp,
20873 				 buf_list, list_node) {
20874 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
20875 			      list_entry->dma_sgl,
20876 			      list_entry->dma_phys_sgl);
20877 		list_del(&list_entry->list_node);
20878 		kfree(list_entry);
20879 	}
20880 
20881 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20882 }
20883 
20884 /**
20885  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
20886  * @phba: The HBA for which this call is being executed.
20887  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
20888  *
20889  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
20890  * and will allocate an CMD/RSP buffer if the pool is empty.
20891  *
20892  * Return codes:
20893  *   NULL - Error
20894  *   Pointer to fcp_cmd_rsp_buf - Success
20895  **/
20896 struct fcp_cmd_rsp_buf *
20897 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
20898 			      struct lpfc_io_buf *lpfc_buf)
20899 {
20900 	struct fcp_cmd_rsp_buf *list_entry = NULL;
20901 	struct fcp_cmd_rsp_buf *tmp = NULL;
20902 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
20903 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20904 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
20905 	unsigned long iflags;
20906 
20907 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20908 
20909 	if (likely(!list_empty(buf_list))) {
20910 		/* break off 1 chunk from the list */
20911 		list_for_each_entry_safe(list_entry, tmp,
20912 					 buf_list,
20913 					 list_node) {
20914 			list_move_tail(&list_entry->list_node,
20915 				       &lpfc_buf->dma_cmd_rsp_list);
20916 			break;
20917 		}
20918 	} else {
20919 		/* allocate more */
20920 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20921 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
20922 				   cpu_to_node(hdwq->io_wq->chann));
20923 		if (!tmp) {
20924 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20925 					"8355 error kmalloc memory for HDWQ "
20926 					"%d %s\n",
20927 					lpfc_buf->hdwq_no, __func__);
20928 			return NULL;
20929 		}
20930 
20931 		tmp->fcp_cmnd = dma_pool_alloc(phba->lpfc_cmd_rsp_buf_pool,
20932 						GFP_ATOMIC,
20933 						&tmp->fcp_cmd_rsp_dma_handle);
20934 
20935 		if (!tmp->fcp_cmnd) {
20936 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20937 					"8356 error pool_alloc memory for HDWQ "
20938 					"%d %s\n",
20939 					lpfc_buf->hdwq_no, __func__);
20940 			kfree(tmp);
20941 			return NULL;
20942 		}
20943 
20944 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
20945 				sizeof(struct fcp_cmnd));
20946 
20947 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20948 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
20949 	}
20950 
20951 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
20952 					struct fcp_cmd_rsp_buf,
20953 					list_node);
20954 
20955 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20956 
20957 	return allocated_buf;
20958 }
20959 
20960 /**
20961  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
20962  * @phba: The HBA for which this call is being executed.
20963  * @lpfc_buf: IO buf structure with the CMD/RSP buf
20964  *
20965  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
20966  *
20967  * Return codes:
20968  *   0 - Success
20969  *   -EINVAL - Error
20970  **/
20971 int
20972 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
20973 			      struct lpfc_io_buf *lpfc_buf)
20974 {
20975 	int rc = 0;
20976 	struct fcp_cmd_rsp_buf *list_entry = NULL;
20977 	struct fcp_cmd_rsp_buf *tmp = NULL;
20978 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20979 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
20980 	unsigned long iflags;
20981 
20982 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20983 
20984 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
20985 		list_for_each_entry_safe(list_entry, tmp,
20986 					 &lpfc_buf->dma_cmd_rsp_list,
20987 					 list_node) {
20988 			list_move_tail(&list_entry->list_node,
20989 				       buf_list);
20990 		}
20991 	} else {
20992 		rc = -EINVAL;
20993 	}
20994 
20995 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20996 	return rc;
20997 }
20998 
20999 /**
21000  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
21001  * @phba: phba object
21002  * @hdwq: hdwq to cleanup cmd rsp buff resources on
21003  *
21004  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
21005  *
21006  * Return codes:
21007  *   None
21008  **/
21009 void
21010 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
21011 			       struct lpfc_sli4_hdw_queue *hdwq)
21012 {
21013 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
21014 	struct fcp_cmd_rsp_buf *list_entry = NULL;
21015 	struct fcp_cmd_rsp_buf *tmp = NULL;
21016 	unsigned long iflags;
21017 
21018 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21019 
21020 	/* Free cmd_rsp buf pool */
21021 	list_for_each_entry_safe(list_entry, tmp,
21022 				 buf_list,
21023 				 list_node) {
21024 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
21025 			      list_entry->fcp_cmnd,
21026 			      list_entry->fcp_cmd_rsp_dma_handle);
21027 		list_del(&list_entry->list_node);
21028 		kfree(list_entry);
21029 	}
21030 
21031 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21032 }
21033