xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision b1a3e75e)
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 #include <linux/crash_dump.h>
39 #ifdef CONFIG_X86
40 #include <asm/set_memory.h>
41 #endif
42 
43 #include "lpfc_hw4.h"
44 #include "lpfc_hw.h"
45 #include "lpfc_sli.h"
46 #include "lpfc_sli4.h"
47 #include "lpfc_nl.h"
48 #include "lpfc_disc.h"
49 #include "lpfc.h"
50 #include "lpfc_scsi.h"
51 #include "lpfc_nvme.h"
52 #include "lpfc_crtn.h"
53 #include "lpfc_logmsg.h"
54 #include "lpfc_compat.h"
55 #include "lpfc_debugfs.h"
56 #include "lpfc_vport.h"
57 #include "lpfc_version.h"
58 
59 /* There are only four IOCB completion types. */
60 typedef enum _lpfc_iocb_type {
61 	LPFC_UNKNOWN_IOCB,
62 	LPFC_UNSOL_IOCB,
63 	LPFC_SOL_IOCB,
64 	LPFC_ABORT_IOCB
65 } lpfc_iocb_type;
66 
67 
68 /* Provide function prototypes local to this module. */
69 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
70 				  uint32_t);
71 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
72 			      uint8_t *, uint32_t *);
73 static struct lpfc_iocbq *lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *,
74 							 struct lpfc_iocbq *);
75 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
76 				      struct hbq_dmabuf *);
77 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
78 					  struct hbq_dmabuf *dmabuf);
79 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
80 				   struct lpfc_queue *cq, struct lpfc_cqe *cqe);
81 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
82 				       int);
83 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
84 				     struct lpfc_queue *eq,
85 				     struct lpfc_eqe *eqe);
86 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
87 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
88 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
89 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
90 				    struct lpfc_queue *cq,
91 				    struct lpfc_cqe *cqe);
92 
93 static IOCB_t *
94 lpfc_get_iocb_from_iocbq(struct lpfc_iocbq *iocbq)
95 {
96 	return &iocbq->iocb;
97 }
98 
99 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
100 /**
101  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
102  * @srcp: Source memory pointer.
103  * @destp: Destination memory pointer.
104  * @cnt: Number of words required to be copied.
105  *       Must be a multiple of sizeof(uint64_t)
106  *
107  * This function is used for copying data between driver memory
108  * and the SLI WQ. This function also changes the endianness
109  * of each word if native endianness is different from SLI
110  * endianness. This function can be called with or without
111  * lock.
112  **/
113 static void
114 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
115 {
116 	uint64_t *src = srcp;
117 	uint64_t *dest = destp;
118 	int i;
119 
120 	for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
121 		*dest++ = *src++;
122 }
123 #else
124 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
125 #endif
126 
127 /**
128  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
129  * @q: The Work Queue to operate on.
130  * @wqe: The work Queue Entry to put on the Work queue.
131  *
132  * This routine will copy the contents of @wqe to the next available entry on
133  * the @q. This function will then ring the Work Queue Doorbell to signal the
134  * HBA to start processing the Work Queue Entry. This function returns 0 if
135  * successful. If no entries are available on @q then this function will return
136  * -ENOMEM.
137  * The caller is expected to hold the hbalock when calling this routine.
138  **/
139 static int
140 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
141 {
142 	union lpfc_wqe *temp_wqe;
143 	struct lpfc_register doorbell;
144 	uint32_t host_index;
145 	uint32_t idx;
146 	uint32_t i = 0;
147 	uint8_t *tmp;
148 	u32 if_type;
149 
150 	/* sanity check on queue memory */
151 	if (unlikely(!q))
152 		return -ENOMEM;
153 	temp_wqe = lpfc_sli4_qe(q, q->host_index);
154 
155 	/* If the host has not yet processed the next entry then we are done */
156 	idx = ((q->host_index + 1) % q->entry_count);
157 	if (idx == q->hba_index) {
158 		q->WQ_overflow++;
159 		return -EBUSY;
160 	}
161 	q->WQ_posted++;
162 	/* set consumption flag every once in a while */
163 	if (!((q->host_index + 1) % q->notify_interval))
164 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
165 	else
166 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
167 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
168 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
169 	lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
170 	if (q->dpp_enable && q->phba->cfg_enable_dpp) {
171 		/* write to DPP aperture taking advatage of Combined Writes */
172 		tmp = (uint8_t *)temp_wqe;
173 #ifdef __raw_writeq
174 		for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
175 			__raw_writeq(*((uint64_t *)(tmp + i)),
176 					q->dpp_regaddr + i);
177 #else
178 		for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
179 			__raw_writel(*((uint32_t *)(tmp + i)),
180 					q->dpp_regaddr + i);
181 #endif
182 	}
183 	/* ensure WQE bcopy and DPP flushed before doorbell write */
184 	wmb();
185 
186 	/* Update the host index before invoking device */
187 	host_index = q->host_index;
188 
189 	q->host_index = idx;
190 
191 	/* Ring Doorbell */
192 	doorbell.word0 = 0;
193 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
194 		if (q->dpp_enable && q->phba->cfg_enable_dpp) {
195 			bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
196 			bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
197 			bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
198 			    q->dpp_id);
199 			bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
200 			    q->queue_id);
201 		} else {
202 			bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
203 			bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
204 
205 			/* Leave bits <23:16> clear for if_type 6 dpp */
206 			if_type = bf_get(lpfc_sli_intf_if_type,
207 					 &q->phba->sli4_hba.sli_intf);
208 			if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
209 				bf_set(lpfc_wq_db_list_fm_index, &doorbell,
210 				       host_index);
211 		}
212 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
213 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
214 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
215 	} else {
216 		return -EINVAL;
217 	}
218 	writel(doorbell.word0, q->db_regaddr);
219 
220 	return 0;
221 }
222 
223 /**
224  * lpfc_sli4_wq_release - Updates internal hba index for WQ
225  * @q: The Work Queue to operate on.
226  * @index: The index to advance the hba index to.
227  *
228  * This routine will update the HBA index of a queue to reflect consumption of
229  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
230  * an entry the host calls this function to update the queue's internal
231  * pointers.
232  **/
233 static void
234 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
235 {
236 	/* sanity check on queue memory */
237 	if (unlikely(!q))
238 		return;
239 
240 	q->hba_index = index;
241 }
242 
243 /**
244  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
245  * @q: The Mailbox Queue to operate on.
246  * @mqe: The Mailbox Queue Entry to put on the Work queue.
247  *
248  * This routine will copy the contents of @mqe to the next available entry on
249  * the @q. This function will then ring the Work Queue Doorbell to signal the
250  * HBA to start processing the Work Queue Entry. This function returns 0 if
251  * successful. If no entries are available on @q then this function will return
252  * -ENOMEM.
253  * The caller is expected to hold the hbalock when calling this routine.
254  **/
255 static uint32_t
256 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
257 {
258 	struct lpfc_mqe *temp_mqe;
259 	struct lpfc_register doorbell;
260 
261 	/* sanity check on queue memory */
262 	if (unlikely(!q))
263 		return -ENOMEM;
264 	temp_mqe = lpfc_sli4_qe(q, q->host_index);
265 
266 	/* If the host has not yet processed the next entry then we are done */
267 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
268 		return -ENOMEM;
269 	lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
270 	/* Save off the mailbox pointer for completion */
271 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
272 
273 	/* Update the host index before invoking device */
274 	q->host_index = ((q->host_index + 1) % q->entry_count);
275 
276 	/* Ring Doorbell */
277 	doorbell.word0 = 0;
278 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
279 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
280 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
281 	return 0;
282 }
283 
284 /**
285  * lpfc_sli4_mq_release - Updates internal hba index for MQ
286  * @q: The Mailbox Queue to operate on.
287  *
288  * This routine will update the HBA index of a queue to reflect consumption of
289  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
290  * an entry the host calls this function to update the queue's internal
291  * pointers. This routine returns the number of entries that were consumed by
292  * the HBA.
293  **/
294 static uint32_t
295 lpfc_sli4_mq_release(struct lpfc_queue *q)
296 {
297 	/* sanity check on queue memory */
298 	if (unlikely(!q))
299 		return 0;
300 
301 	/* Clear the mailbox pointer for completion */
302 	q->phba->mbox = NULL;
303 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
304 	return 1;
305 }
306 
307 /**
308  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
309  * @q: The Event Queue to get the first valid EQE from
310  *
311  * This routine will get the first valid Event Queue Entry from @q, update
312  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
313  * the Queue (no more work to do), or the Queue is full of EQEs that have been
314  * processed, but not popped back to the HBA then this routine will return NULL.
315  **/
316 static struct lpfc_eqe *
317 lpfc_sli4_eq_get(struct lpfc_queue *q)
318 {
319 	struct lpfc_eqe *eqe;
320 
321 	/* sanity check on queue memory */
322 	if (unlikely(!q))
323 		return NULL;
324 	eqe = lpfc_sli4_qe(q, q->host_index);
325 
326 	/* If the next EQE is not valid then we are done */
327 	if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
328 		return NULL;
329 
330 	/*
331 	 * insert barrier for instruction interlock : data from the hardware
332 	 * must have the valid bit checked before it can be copied and acted
333 	 * upon. Speculative instructions were allowing a bcopy at the start
334 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
335 	 * after our return, to copy data before the valid bit check above
336 	 * was done. As such, some of the copied data was stale. The barrier
337 	 * ensures the check is before any data is copied.
338 	 */
339 	mb();
340 	return eqe;
341 }
342 
343 /**
344  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
345  * @q: The Event Queue to disable interrupts
346  *
347  **/
348 void
349 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
350 {
351 	struct lpfc_register doorbell;
352 
353 	doorbell.word0 = 0;
354 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
355 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
356 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
357 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
358 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
359 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
360 }
361 
362 /**
363  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
364  * @q: The Event Queue to disable interrupts
365  *
366  **/
367 void
368 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
369 {
370 	struct lpfc_register doorbell;
371 
372 	doorbell.word0 = 0;
373 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
374 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
375 }
376 
377 /**
378  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
379  * @phba: adapter with EQ
380  * @q: The Event Queue that the host has completed processing for.
381  * @count: Number of elements that have been consumed
382  * @arm: Indicates whether the host wants to arms this CQ.
383  *
384  * This routine will notify the HBA, by ringing the doorbell, that count
385  * number of EQEs have been processed. The @arm parameter indicates whether
386  * the queue should be rearmed when ringing the doorbell.
387  **/
388 void
389 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
390 		     uint32_t count, bool arm)
391 {
392 	struct lpfc_register doorbell;
393 
394 	/* sanity check on queue memory */
395 	if (unlikely(!q || (count == 0 && !arm)))
396 		return;
397 
398 	/* ring doorbell for number popped */
399 	doorbell.word0 = 0;
400 	if (arm) {
401 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
402 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
403 	}
404 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
405 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
406 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
407 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
408 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
409 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
410 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
411 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
412 		readl(q->phba->sli4_hba.EQDBregaddr);
413 }
414 
415 /**
416  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
417  * @phba: adapter with EQ
418  * @q: The Event Queue that the host has completed processing for.
419  * @count: Number of elements that have been consumed
420  * @arm: Indicates whether the host wants to arms this CQ.
421  *
422  * This routine will notify the HBA, by ringing the doorbell, that count
423  * number of EQEs have been processed. The @arm parameter indicates whether
424  * the queue should be rearmed when ringing the doorbell.
425  **/
426 void
427 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
428 			  uint32_t count, bool arm)
429 {
430 	struct lpfc_register doorbell;
431 
432 	/* sanity check on queue memory */
433 	if (unlikely(!q || (count == 0 && !arm)))
434 		return;
435 
436 	/* ring doorbell for number popped */
437 	doorbell.word0 = 0;
438 	if (arm)
439 		bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
440 	bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
441 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
442 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
443 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
444 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
445 		readl(q->phba->sli4_hba.EQDBregaddr);
446 }
447 
448 static void
449 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
450 			struct lpfc_eqe *eqe)
451 {
452 	if (!phba->sli4_hba.pc_sli4_params.eqav)
453 		bf_set_le32(lpfc_eqe_valid, eqe, 0);
454 
455 	eq->host_index = ((eq->host_index + 1) % eq->entry_count);
456 
457 	/* if the index wrapped around, toggle the valid bit */
458 	if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
459 		eq->qe_valid = (eq->qe_valid) ? 0 : 1;
460 }
461 
462 static void
463 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
464 {
465 	struct lpfc_eqe *eqe = NULL;
466 	u32 eq_count = 0, cq_count = 0;
467 	struct lpfc_cqe *cqe = NULL;
468 	struct lpfc_queue *cq = NULL, *childq = NULL;
469 	int cqid = 0;
470 
471 	/* walk all the EQ entries and drop on the floor */
472 	eqe = lpfc_sli4_eq_get(eq);
473 	while (eqe) {
474 		/* Get the reference to the corresponding CQ */
475 		cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
476 		cq = NULL;
477 
478 		list_for_each_entry(childq, &eq->child_list, list) {
479 			if (childq->queue_id == cqid) {
480 				cq = childq;
481 				break;
482 			}
483 		}
484 		/* If CQ is valid, iterate through it and drop all the CQEs */
485 		if (cq) {
486 			cqe = lpfc_sli4_cq_get(cq);
487 			while (cqe) {
488 				__lpfc_sli4_consume_cqe(phba, cq, cqe);
489 				cq_count++;
490 				cqe = lpfc_sli4_cq_get(cq);
491 			}
492 			/* Clear and re-arm the CQ */
493 			phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
494 			    LPFC_QUEUE_REARM);
495 			cq_count = 0;
496 		}
497 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
498 		eq_count++;
499 		eqe = lpfc_sli4_eq_get(eq);
500 	}
501 
502 	/* Clear and re-arm the EQ */
503 	phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
504 }
505 
506 static int
507 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
508 		     uint8_t rearm)
509 {
510 	struct lpfc_eqe *eqe;
511 	int count = 0, consumed = 0;
512 
513 	if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
514 		goto rearm_and_exit;
515 
516 	eqe = lpfc_sli4_eq_get(eq);
517 	while (eqe) {
518 		lpfc_sli4_hba_handle_eqe(phba, eq, eqe);
519 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
520 
521 		consumed++;
522 		if (!(++count % eq->max_proc_limit))
523 			break;
524 
525 		if (!(count % eq->notify_interval)) {
526 			phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
527 							LPFC_QUEUE_NOARM);
528 			consumed = 0;
529 		}
530 
531 		eqe = lpfc_sli4_eq_get(eq);
532 	}
533 	eq->EQ_processed += count;
534 
535 	/* Track the max number of EQEs processed in 1 intr */
536 	if (count > eq->EQ_max_eqe)
537 		eq->EQ_max_eqe = count;
538 
539 	xchg(&eq->queue_claimed, 0);
540 
541 rearm_and_exit:
542 	/* Always clear the EQ. */
543 	phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
544 
545 	return count;
546 }
547 
548 /**
549  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
550  * @q: The Completion Queue to get the first valid CQE from
551  *
552  * This routine will get the first valid Completion Queue Entry from @q, update
553  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
554  * the Queue (no more work to do), or the Queue is full of CQEs that have been
555  * processed, but not popped back to the HBA then this routine will return NULL.
556  **/
557 static struct lpfc_cqe *
558 lpfc_sli4_cq_get(struct lpfc_queue *q)
559 {
560 	struct lpfc_cqe *cqe;
561 
562 	/* sanity check on queue memory */
563 	if (unlikely(!q))
564 		return NULL;
565 	cqe = lpfc_sli4_qe(q, q->host_index);
566 
567 	/* If the next CQE is not valid then we are done */
568 	if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
569 		return NULL;
570 
571 	/*
572 	 * insert barrier for instruction interlock : data from the hardware
573 	 * must have the valid bit checked before it can be copied and acted
574 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
575 	 * instructions allowing action on content before valid bit checked,
576 	 * add barrier here as well. May not be needed as "content" is a
577 	 * single 32-bit entity here (vs multi word structure for cq's).
578 	 */
579 	mb();
580 	return cqe;
581 }
582 
583 static void
584 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
585 			struct lpfc_cqe *cqe)
586 {
587 	if (!phba->sli4_hba.pc_sli4_params.cqav)
588 		bf_set_le32(lpfc_cqe_valid, cqe, 0);
589 
590 	cq->host_index = ((cq->host_index + 1) % cq->entry_count);
591 
592 	/* if the index wrapped around, toggle the valid bit */
593 	if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
594 		cq->qe_valid = (cq->qe_valid) ? 0 : 1;
595 }
596 
597 /**
598  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
599  * @phba: the adapter with the CQ
600  * @q: The Completion Queue that the host has completed processing for.
601  * @count: the number of elements that were consumed
602  * @arm: Indicates whether the host wants to arms this CQ.
603  *
604  * This routine will notify the HBA, by ringing the doorbell, that the
605  * CQEs have been processed. The @arm parameter specifies whether the
606  * queue should be rearmed when ringing the doorbell.
607  **/
608 void
609 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
610 		     uint32_t count, bool arm)
611 {
612 	struct lpfc_register doorbell;
613 
614 	/* sanity check on queue memory */
615 	if (unlikely(!q || (count == 0 && !arm)))
616 		return;
617 
618 	/* ring doorbell for number popped */
619 	doorbell.word0 = 0;
620 	if (arm)
621 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
622 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
623 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
624 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
625 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
626 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
627 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
628 }
629 
630 /**
631  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
632  * @phba: the adapter with the CQ
633  * @q: The Completion Queue that the host has completed processing for.
634  * @count: the number of elements that were consumed
635  * @arm: Indicates whether the host wants to arms this CQ.
636  *
637  * This routine will notify the HBA, by ringing the doorbell, that the
638  * CQEs have been processed. The @arm parameter specifies whether the
639  * queue should be rearmed when ringing the doorbell.
640  **/
641 void
642 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
643 			 uint32_t count, bool arm)
644 {
645 	struct lpfc_register doorbell;
646 
647 	/* sanity check on queue memory */
648 	if (unlikely(!q || (count == 0 && !arm)))
649 		return;
650 
651 	/* ring doorbell for number popped */
652 	doorbell.word0 = 0;
653 	if (arm)
654 		bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
655 	bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
656 	bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
657 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
658 }
659 
660 /*
661  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
662  *
663  * This routine will copy the contents of @wqe to the next available entry on
664  * the @q. This function will then ring the Receive Queue Doorbell to signal the
665  * HBA to start processing the Receive Queue Entry. This function returns the
666  * index that the rqe was copied to if successful. If no entries are available
667  * on @q then this function will return -ENOMEM.
668  * The caller is expected to hold the hbalock when calling this routine.
669  **/
670 int
671 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
672 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
673 {
674 	struct lpfc_rqe *temp_hrqe;
675 	struct lpfc_rqe *temp_drqe;
676 	struct lpfc_register doorbell;
677 	int hq_put_index;
678 	int dq_put_index;
679 
680 	/* sanity check on queue memory */
681 	if (unlikely(!hq) || unlikely(!dq))
682 		return -ENOMEM;
683 	hq_put_index = hq->host_index;
684 	dq_put_index = dq->host_index;
685 	temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
686 	temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
687 
688 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
689 		return -EINVAL;
690 	if (hq_put_index != dq_put_index)
691 		return -EINVAL;
692 	/* If the host has not yet processed the next entry then we are done */
693 	if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
694 		return -EBUSY;
695 	lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
696 	lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
697 
698 	/* Update the host index to point to the next slot */
699 	hq->host_index = ((hq_put_index + 1) % hq->entry_count);
700 	dq->host_index = ((dq_put_index + 1) % dq->entry_count);
701 	hq->RQ_buf_posted++;
702 
703 	/* Ring The Header Receive Queue Doorbell */
704 	if (!(hq->host_index % hq->notify_interval)) {
705 		doorbell.word0 = 0;
706 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
707 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
708 			       hq->notify_interval);
709 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
710 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
711 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
712 			       hq->notify_interval);
713 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
714 			       hq->host_index);
715 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
716 		} else {
717 			return -EINVAL;
718 		}
719 		writel(doorbell.word0, hq->db_regaddr);
720 	}
721 	return hq_put_index;
722 }
723 
724 /*
725  * lpfc_sli4_rq_release - Updates internal hba index for RQ
726  *
727  * This routine will update the HBA index of a queue to reflect consumption of
728  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
729  * consumed an entry the host calls this function to update the queue's
730  * internal pointers. This routine returns the number of entries that were
731  * consumed by the HBA.
732  **/
733 static uint32_t
734 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
735 {
736 	/* sanity check on queue memory */
737 	if (unlikely(!hq) || unlikely(!dq))
738 		return 0;
739 
740 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
741 		return 0;
742 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
743 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
744 	return 1;
745 }
746 
747 /**
748  * lpfc_cmd_iocb - Get next command iocb entry in the ring
749  * @phba: Pointer to HBA context object.
750  * @pring: Pointer to driver SLI ring object.
751  *
752  * This function returns pointer to next command iocb entry
753  * in the command ring. The caller must hold hbalock to prevent
754  * other threads consume the next command iocb.
755  * SLI-2/SLI-3 provide different sized iocbs.
756  **/
757 static inline IOCB_t *
758 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
759 {
760 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
761 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
762 }
763 
764 /**
765  * lpfc_resp_iocb - Get next response iocb entry in the ring
766  * @phba: Pointer to HBA context object.
767  * @pring: Pointer to driver SLI ring object.
768  *
769  * This function returns pointer to next response iocb entry
770  * in the response ring. The caller must hold hbalock to make sure
771  * that no other thread consume the next response iocb.
772  * SLI-2/SLI-3 provide different sized iocbs.
773  **/
774 static inline IOCB_t *
775 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
776 {
777 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
778 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
779 }
780 
781 /**
782  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
783  * @phba: Pointer to HBA context object.
784  *
785  * This function is called with hbalock held. This function
786  * allocates a new driver iocb object from the iocb pool. If the
787  * allocation is successful, it returns pointer to the newly
788  * allocated iocb object else it returns NULL.
789  **/
790 struct lpfc_iocbq *
791 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
792 {
793 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
794 	struct lpfc_iocbq * iocbq = NULL;
795 
796 	lockdep_assert_held(&phba->hbalock);
797 
798 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
799 	if (iocbq)
800 		phba->iocb_cnt++;
801 	if (phba->iocb_cnt > phba->iocb_max)
802 		phba->iocb_max = phba->iocb_cnt;
803 	return iocbq;
804 }
805 
806 /**
807  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
808  * @phba: Pointer to HBA context object.
809  * @xritag: XRI value.
810  *
811  * This function clears the sglq pointer from the array of acive
812  * sglq's. The xritag that is passed in is used to index into the
813  * array. Before the xritag can be used it needs to be adjusted
814  * by subtracting the xribase.
815  *
816  * Returns sglq ponter = success, NULL = Failure.
817  **/
818 struct lpfc_sglq *
819 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
820 {
821 	struct lpfc_sglq *sglq;
822 
823 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
824 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
825 	return sglq;
826 }
827 
828 /**
829  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
830  * @phba: Pointer to HBA context object.
831  * @xritag: XRI value.
832  *
833  * This function returns the sglq pointer from the array of acive
834  * sglq's. The xritag that is passed in is used to index into the
835  * array. Before the xritag can be used it needs to be adjusted
836  * by subtracting the xribase.
837  *
838  * Returns sglq ponter = success, NULL = Failure.
839  **/
840 struct lpfc_sglq *
841 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
842 {
843 	struct lpfc_sglq *sglq;
844 
845 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
846 	return sglq;
847 }
848 
849 /**
850  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
851  * @phba: Pointer to HBA context object.
852  * @xritag: xri used in this exchange.
853  * @rrq: The RRQ to be cleared.
854  *
855  **/
856 void
857 lpfc_clr_rrq_active(struct lpfc_hba *phba,
858 		    uint16_t xritag,
859 		    struct lpfc_node_rrq *rrq)
860 {
861 	struct lpfc_nodelist *ndlp = NULL;
862 
863 	if ((rrq->vport) && NLP_CHK_NODE_ACT(rrq->ndlp))
864 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
865 
866 	/* The target DID could have been swapped (cable swap)
867 	 * we should use the ndlp from the findnode if it is
868 	 * available.
869 	 */
870 	if ((!ndlp) && rrq->ndlp)
871 		ndlp = rrq->ndlp;
872 
873 	if (!ndlp)
874 		goto out;
875 
876 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
877 		rrq->send_rrq = 0;
878 		rrq->xritag = 0;
879 		rrq->rrq_stop_time = 0;
880 	}
881 out:
882 	mempool_free(rrq, phba->rrq_pool);
883 }
884 
885 /**
886  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
887  * @phba: Pointer to HBA context object.
888  *
889  * This function is called with hbalock held. This function
890  * Checks if stop_time (ratov from setting rrq active) has
891  * been reached, if it has and the send_rrq flag is set then
892  * it will call lpfc_send_rrq. If the send_rrq flag is not set
893  * then it will just call the routine to clear the rrq and
894  * free the rrq resource.
895  * The timer is set to the next rrq that is going to expire before
896  * leaving the routine.
897  *
898  **/
899 void
900 lpfc_handle_rrq_active(struct lpfc_hba *phba)
901 {
902 	struct lpfc_node_rrq *rrq;
903 	struct lpfc_node_rrq *nextrrq;
904 	unsigned long next_time;
905 	unsigned long iflags;
906 	LIST_HEAD(send_rrq);
907 
908 	spin_lock_irqsave(&phba->hbalock, iflags);
909 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
910 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
911 	list_for_each_entry_safe(rrq, nextrrq,
912 				 &phba->active_rrq_list, list) {
913 		if (time_after(jiffies, rrq->rrq_stop_time))
914 			list_move(&rrq->list, &send_rrq);
915 		else if (time_before(rrq->rrq_stop_time, next_time))
916 			next_time = rrq->rrq_stop_time;
917 	}
918 	spin_unlock_irqrestore(&phba->hbalock, iflags);
919 	if ((!list_empty(&phba->active_rrq_list)) &&
920 	    (!(phba->pport->load_flag & FC_UNLOADING)))
921 		mod_timer(&phba->rrq_tmr, next_time);
922 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
923 		list_del(&rrq->list);
924 		if (!rrq->send_rrq) {
925 			/* this call will free the rrq */
926 			lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
927 		} else if (lpfc_send_rrq(phba, rrq)) {
928 			/* if we send the rrq then the completion handler
929 			*  will clear the bit in the xribitmap.
930 			*/
931 			lpfc_clr_rrq_active(phba, rrq->xritag,
932 					    rrq);
933 		}
934 	}
935 }
936 
937 /**
938  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
939  * @vport: Pointer to vport context object.
940  * @xri: The xri used in the exchange.
941  * @did: The targets DID for this exchange.
942  *
943  * returns NULL = rrq not found in the phba->active_rrq_list.
944  *         rrq = rrq for this xri and target.
945  **/
946 struct lpfc_node_rrq *
947 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
948 {
949 	struct lpfc_hba *phba = vport->phba;
950 	struct lpfc_node_rrq *rrq;
951 	struct lpfc_node_rrq *nextrrq;
952 	unsigned long iflags;
953 
954 	if (phba->sli_rev != LPFC_SLI_REV4)
955 		return NULL;
956 	spin_lock_irqsave(&phba->hbalock, iflags);
957 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
958 		if (rrq->vport == vport && rrq->xritag == xri &&
959 				rrq->nlp_DID == did){
960 			list_del(&rrq->list);
961 			spin_unlock_irqrestore(&phba->hbalock, iflags);
962 			return rrq;
963 		}
964 	}
965 	spin_unlock_irqrestore(&phba->hbalock, iflags);
966 	return NULL;
967 }
968 
969 /**
970  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
971  * @vport: Pointer to vport context object.
972  * @ndlp: Pointer to the lpfc_node_list structure.
973  * If ndlp is NULL Remove all active RRQs for this vport from the
974  * phba->active_rrq_list and clear the rrq.
975  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
976  **/
977 void
978 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
979 
980 {
981 	struct lpfc_hba *phba = vport->phba;
982 	struct lpfc_node_rrq *rrq;
983 	struct lpfc_node_rrq *nextrrq;
984 	unsigned long iflags;
985 	LIST_HEAD(rrq_list);
986 
987 	if (phba->sli_rev != LPFC_SLI_REV4)
988 		return;
989 	if (!ndlp) {
990 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
991 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
992 	}
993 	spin_lock_irqsave(&phba->hbalock, iflags);
994 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list)
995 		if ((rrq->vport == vport) && (!ndlp  || rrq->ndlp == ndlp))
996 			list_move(&rrq->list, &rrq_list);
997 	spin_unlock_irqrestore(&phba->hbalock, iflags);
998 
999 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1000 		list_del(&rrq->list);
1001 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1002 	}
1003 }
1004 
1005 /**
1006  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1007  * @phba: Pointer to HBA context object.
1008  * @ndlp: Targets nodelist pointer for this exchange.
1009  * @xritag: the xri in the bitmap to test.
1010  *
1011  * This function returns:
1012  * 0 = rrq not active for this xri
1013  * 1 = rrq is valid for this xri.
1014  **/
1015 int
1016 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1017 			uint16_t  xritag)
1018 {
1019 	if (!ndlp)
1020 		return 0;
1021 	if (!ndlp->active_rrqs_xri_bitmap)
1022 		return 0;
1023 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1024 		return 1;
1025 	else
1026 		return 0;
1027 }
1028 
1029 /**
1030  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1031  * @phba: Pointer to HBA context object.
1032  * @ndlp: nodelist pointer for this target.
1033  * @xritag: xri used in this exchange.
1034  * @rxid: Remote Exchange ID.
1035  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1036  *
1037  * This function takes the hbalock.
1038  * The active bit is always set in the active rrq xri_bitmap even
1039  * if there is no slot avaiable for the other rrq information.
1040  *
1041  * returns 0 rrq actived for this xri
1042  *         < 0 No memory or invalid ndlp.
1043  **/
1044 int
1045 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1046 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1047 {
1048 	unsigned long iflags;
1049 	struct lpfc_node_rrq *rrq;
1050 	int empty;
1051 
1052 	if (!ndlp)
1053 		return -EINVAL;
1054 
1055 	if (!phba->cfg_enable_rrq)
1056 		return -EINVAL;
1057 
1058 	spin_lock_irqsave(&phba->hbalock, iflags);
1059 	if (phba->pport->load_flag & FC_UNLOADING) {
1060 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1061 		goto out;
1062 	}
1063 
1064 	/*
1065 	 * set the active bit even if there is no mem available.
1066 	 */
1067 	if (NLP_CHK_FREE_REQ(ndlp))
1068 		goto out;
1069 
1070 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
1071 		goto out;
1072 
1073 	if (!ndlp->active_rrqs_xri_bitmap)
1074 		goto out;
1075 
1076 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1077 		goto out;
1078 
1079 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1080 	rrq = mempool_alloc(phba->rrq_pool, GFP_ATOMIC);
1081 	if (!rrq) {
1082 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1083 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1084 				" DID:0x%x Send:%d\n",
1085 				xritag, rxid, ndlp->nlp_DID, send_rrq);
1086 		return -EINVAL;
1087 	}
1088 	if (phba->cfg_enable_rrq == 1)
1089 		rrq->send_rrq = send_rrq;
1090 	else
1091 		rrq->send_rrq = 0;
1092 	rrq->xritag = xritag;
1093 	rrq->rrq_stop_time = jiffies +
1094 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1095 	rrq->ndlp = ndlp;
1096 	rrq->nlp_DID = ndlp->nlp_DID;
1097 	rrq->vport = ndlp->vport;
1098 	rrq->rxid = rxid;
1099 	spin_lock_irqsave(&phba->hbalock, iflags);
1100 	empty = list_empty(&phba->active_rrq_list);
1101 	list_add_tail(&rrq->list, &phba->active_rrq_list);
1102 	phba->hba_flag |= HBA_RRQ_ACTIVE;
1103 	if (empty)
1104 		lpfc_worker_wake_up(phba);
1105 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1106 	return 0;
1107 out:
1108 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1109 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1110 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
1111 			" DID:0x%x Send:%d\n",
1112 			xritag, rxid, ndlp->nlp_DID, send_rrq);
1113 	return -EINVAL;
1114 }
1115 
1116 /**
1117  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1118  * @phba: Pointer to HBA context object.
1119  * @piocbq: Pointer to the iocbq.
1120  *
1121  * The driver calls this function with either the nvme ls ring lock
1122  * or the fc els ring lock held depending on the iocb usage.  This function
1123  * gets a new driver sglq object from the sglq list. If the list is not empty
1124  * then it is successful, it returns pointer to the newly allocated sglq
1125  * object else it returns NULL.
1126  **/
1127 static struct lpfc_sglq *
1128 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1129 {
1130 	struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1131 	struct lpfc_sglq *sglq = NULL;
1132 	struct lpfc_sglq *start_sglq = NULL;
1133 	struct lpfc_io_buf *lpfc_cmd;
1134 	struct lpfc_nodelist *ndlp;
1135 	struct lpfc_sli_ring *pring = NULL;
1136 	int found = 0;
1137 
1138 	if (piocbq->iocb_flag & LPFC_IO_NVME_LS)
1139 		pring =  phba->sli4_hba.nvmels_wq->pring;
1140 	else
1141 		pring = lpfc_phba_elsring(phba);
1142 
1143 	lockdep_assert_held(&pring->ring_lock);
1144 
1145 	if (piocbq->iocb_flag &  LPFC_IO_FCP) {
1146 		lpfc_cmd = (struct lpfc_io_buf *) piocbq->context1;
1147 		ndlp = lpfc_cmd->rdata->pnode;
1148 	} else  if ((piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) &&
1149 			!(piocbq->iocb_flag & LPFC_IO_LIBDFC)) {
1150 		ndlp = piocbq->context_un.ndlp;
1151 	} else  if (piocbq->iocb_flag & LPFC_IO_LIBDFC) {
1152 		if (piocbq->iocb_flag & LPFC_IO_LOOPBACK)
1153 			ndlp = NULL;
1154 		else
1155 			ndlp = piocbq->context_un.ndlp;
1156 	} else {
1157 		ndlp = piocbq->context1;
1158 	}
1159 
1160 	spin_lock(&phba->sli4_hba.sgl_list_lock);
1161 	list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1162 	start_sglq = sglq;
1163 	while (!found) {
1164 		if (!sglq)
1165 			break;
1166 		if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1167 		    test_bit(sglq->sli4_lxritag,
1168 		    ndlp->active_rrqs_xri_bitmap)) {
1169 			/* This xri has an rrq outstanding for this DID.
1170 			 * put it back in the list and get another xri.
1171 			 */
1172 			list_add_tail(&sglq->list, lpfc_els_sgl_list);
1173 			sglq = NULL;
1174 			list_remove_head(lpfc_els_sgl_list, sglq,
1175 						struct lpfc_sglq, list);
1176 			if (sglq == start_sglq) {
1177 				list_add_tail(&sglq->list, lpfc_els_sgl_list);
1178 				sglq = NULL;
1179 				break;
1180 			} else
1181 				continue;
1182 		}
1183 		sglq->ndlp = ndlp;
1184 		found = 1;
1185 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1186 		sglq->state = SGL_ALLOCATED;
1187 	}
1188 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
1189 	return sglq;
1190 }
1191 
1192 /**
1193  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1194  * @phba: Pointer to HBA context object.
1195  * @piocbq: Pointer to the iocbq.
1196  *
1197  * This function is called with the sgl_list lock held. This function
1198  * gets a new driver sglq object from the sglq list. If the
1199  * list is not empty then it is successful, it returns pointer to the newly
1200  * allocated sglq object else it returns NULL.
1201  **/
1202 struct lpfc_sglq *
1203 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1204 {
1205 	struct list_head *lpfc_nvmet_sgl_list;
1206 	struct lpfc_sglq *sglq = NULL;
1207 
1208 	lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1209 
1210 	lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1211 
1212 	list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1213 	if (!sglq)
1214 		return NULL;
1215 	phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1216 	sglq->state = SGL_ALLOCATED;
1217 	return sglq;
1218 }
1219 
1220 /**
1221  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1222  * @phba: Pointer to HBA context object.
1223  *
1224  * This function is called with no lock held. This function
1225  * allocates a new driver iocb object from the iocb pool. If the
1226  * allocation is successful, it returns pointer to the newly
1227  * allocated iocb object else it returns NULL.
1228  **/
1229 struct lpfc_iocbq *
1230 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1231 {
1232 	struct lpfc_iocbq * iocbq = NULL;
1233 	unsigned long iflags;
1234 
1235 	spin_lock_irqsave(&phba->hbalock, iflags);
1236 	iocbq = __lpfc_sli_get_iocbq(phba);
1237 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1238 	return iocbq;
1239 }
1240 
1241 /**
1242  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1243  * @phba: Pointer to HBA context object.
1244  * @iocbq: Pointer to driver iocb object.
1245  *
1246  * This function is called to release the driver iocb object
1247  * to the iocb pool. The iotag in the iocb object
1248  * does not change for each use of the iocb object. This function
1249  * clears all other fields of the iocb object when it is freed.
1250  * The sqlq structure that holds the xritag and phys and virtual
1251  * mappings for the scatter gather list is retrieved from the
1252  * active array of sglq. The get of the sglq pointer also clears
1253  * the entry in the array. If the status of the IO indiactes that
1254  * this IO was aborted then the sglq entry it put on the
1255  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1256  * IO has good status or fails for any other reason then the sglq
1257  * entry is added to the free list (lpfc_els_sgl_list). The hbalock is
1258  *  asserted held in the code path calling this routine.
1259  **/
1260 static void
1261 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1262 {
1263 	struct lpfc_sglq *sglq;
1264 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1265 	unsigned long iflag = 0;
1266 	struct lpfc_sli_ring *pring;
1267 
1268 	if (iocbq->sli4_xritag == NO_XRI)
1269 		sglq = NULL;
1270 	else
1271 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1272 
1273 
1274 	if (sglq)  {
1275 		if (iocbq->iocb_flag & LPFC_IO_NVMET) {
1276 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1277 					  iflag);
1278 			sglq->state = SGL_FREED;
1279 			sglq->ndlp = NULL;
1280 			list_add_tail(&sglq->list,
1281 				      &phba->sli4_hba.lpfc_nvmet_sgl_list);
1282 			spin_unlock_irqrestore(
1283 				&phba->sli4_hba.sgl_list_lock, iflag);
1284 			goto out;
1285 		}
1286 
1287 		pring = phba->sli4_hba.els_wq->pring;
1288 		if ((iocbq->iocb_flag & LPFC_EXCHANGE_BUSY) &&
1289 			(sglq->state != SGL_XRI_ABORTED)) {
1290 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1291 					  iflag);
1292 			list_add(&sglq->list,
1293 				 &phba->sli4_hba.lpfc_abts_els_sgl_list);
1294 			spin_unlock_irqrestore(
1295 				&phba->sli4_hba.sgl_list_lock, iflag);
1296 		} else {
1297 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1298 					  iflag);
1299 			sglq->state = SGL_FREED;
1300 			sglq->ndlp = NULL;
1301 			list_add_tail(&sglq->list,
1302 				      &phba->sli4_hba.lpfc_els_sgl_list);
1303 			spin_unlock_irqrestore(
1304 				&phba->sli4_hba.sgl_list_lock, iflag);
1305 
1306 			/* Check if TXQ queue needs to be serviced */
1307 			if (!list_empty(&pring->txq))
1308 				lpfc_worker_wake_up(phba);
1309 		}
1310 	}
1311 
1312 out:
1313 	/*
1314 	 * Clean all volatile data fields, preserve iotag and node struct.
1315 	 */
1316 	memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1317 	iocbq->sli4_lxritag = NO_XRI;
1318 	iocbq->sli4_xritag = NO_XRI;
1319 	iocbq->iocb_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET |
1320 			      LPFC_IO_NVME_LS);
1321 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1322 }
1323 
1324 
1325 /**
1326  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1327  * @phba: Pointer to HBA context object.
1328  * @iocbq: Pointer to driver iocb object.
1329  *
1330  * This function is called to release the driver iocb object to the
1331  * iocb pool. The iotag in the iocb object does not change for each
1332  * use of the iocb object. This function clears all other fields of
1333  * the iocb object when it is freed. The hbalock is asserted held in
1334  * the code path calling this routine.
1335  **/
1336 static void
1337 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1338 {
1339 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1340 
1341 	/*
1342 	 * Clean all volatile data fields, preserve iotag and node struct.
1343 	 */
1344 	memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1345 	iocbq->sli4_xritag = NO_XRI;
1346 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1347 }
1348 
1349 /**
1350  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1351  * @phba: Pointer to HBA context object.
1352  * @iocbq: Pointer to driver iocb object.
1353  *
1354  * This function is called with hbalock held to release driver
1355  * iocb object to the iocb pool. The iotag in the iocb object
1356  * does not change for each use of the iocb object. This function
1357  * clears all other fields of the iocb object when it is freed.
1358  **/
1359 static void
1360 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1361 {
1362 	lockdep_assert_held(&phba->hbalock);
1363 
1364 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1365 	phba->iocb_cnt--;
1366 }
1367 
1368 /**
1369  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1370  * @phba: Pointer to HBA context object.
1371  * @iocbq: Pointer to driver iocb object.
1372  *
1373  * This function is called with no lock held to release the iocb to
1374  * iocb pool.
1375  **/
1376 void
1377 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1378 {
1379 	unsigned long iflags;
1380 
1381 	/*
1382 	 * Clean all volatile data fields, preserve iotag and node struct.
1383 	 */
1384 	spin_lock_irqsave(&phba->hbalock, iflags);
1385 	__lpfc_sli_release_iocbq(phba, iocbq);
1386 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1387 }
1388 
1389 /**
1390  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1391  * @phba: Pointer to HBA context object.
1392  * @iocblist: List of IOCBs.
1393  * @ulpstatus: ULP status in IOCB command field.
1394  * @ulpWord4: ULP word-4 in IOCB command field.
1395  *
1396  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1397  * on the list by invoking the complete callback function associated with the
1398  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1399  * fields.
1400  **/
1401 void
1402 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1403 		      uint32_t ulpstatus, uint32_t ulpWord4)
1404 {
1405 	struct lpfc_iocbq *piocb;
1406 
1407 	while (!list_empty(iocblist)) {
1408 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1409 		if (!piocb->iocb_cmpl) {
1410 			if (piocb->iocb_flag & LPFC_IO_NVME)
1411 				lpfc_nvme_cancel_iocb(phba, piocb);
1412 			else
1413 				lpfc_sli_release_iocbq(phba, piocb);
1414 		} else {
1415 			piocb->iocb.ulpStatus = ulpstatus;
1416 			piocb->iocb.un.ulpWord[4] = ulpWord4;
1417 			(piocb->iocb_cmpl) (phba, piocb, piocb);
1418 		}
1419 	}
1420 	return;
1421 }
1422 
1423 /**
1424  * lpfc_sli_iocb_cmd_type - Get the iocb type
1425  * @iocb_cmnd: iocb command code.
1426  *
1427  * This function is called by ring event handler function to get the iocb type.
1428  * This function translates the iocb command to an iocb command type used to
1429  * decide the final disposition of each completed IOCB.
1430  * The function returns
1431  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1432  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1433  * LPFC_ABORT_IOCB   if it is an abort iocb
1434  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1435  *
1436  * The caller is not required to hold any lock.
1437  **/
1438 static lpfc_iocb_type
1439 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1440 {
1441 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1442 
1443 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1444 		return 0;
1445 
1446 	switch (iocb_cmnd) {
1447 	case CMD_XMIT_SEQUENCE_CR:
1448 	case CMD_XMIT_SEQUENCE_CX:
1449 	case CMD_XMIT_BCAST_CN:
1450 	case CMD_XMIT_BCAST_CX:
1451 	case CMD_ELS_REQUEST_CR:
1452 	case CMD_ELS_REQUEST_CX:
1453 	case CMD_CREATE_XRI_CR:
1454 	case CMD_CREATE_XRI_CX:
1455 	case CMD_GET_RPI_CN:
1456 	case CMD_XMIT_ELS_RSP_CX:
1457 	case CMD_GET_RPI_CR:
1458 	case CMD_FCP_IWRITE_CR:
1459 	case CMD_FCP_IWRITE_CX:
1460 	case CMD_FCP_IREAD_CR:
1461 	case CMD_FCP_IREAD_CX:
1462 	case CMD_FCP_ICMND_CR:
1463 	case CMD_FCP_ICMND_CX:
1464 	case CMD_FCP_TSEND_CX:
1465 	case CMD_FCP_TRSP_CX:
1466 	case CMD_FCP_TRECEIVE_CX:
1467 	case CMD_FCP_AUTO_TRSP_CX:
1468 	case CMD_ADAPTER_MSG:
1469 	case CMD_ADAPTER_DUMP:
1470 	case CMD_XMIT_SEQUENCE64_CR:
1471 	case CMD_XMIT_SEQUENCE64_CX:
1472 	case CMD_XMIT_BCAST64_CN:
1473 	case CMD_XMIT_BCAST64_CX:
1474 	case CMD_ELS_REQUEST64_CR:
1475 	case CMD_ELS_REQUEST64_CX:
1476 	case CMD_FCP_IWRITE64_CR:
1477 	case CMD_FCP_IWRITE64_CX:
1478 	case CMD_FCP_IREAD64_CR:
1479 	case CMD_FCP_IREAD64_CX:
1480 	case CMD_FCP_ICMND64_CR:
1481 	case CMD_FCP_ICMND64_CX:
1482 	case CMD_FCP_TSEND64_CX:
1483 	case CMD_FCP_TRSP64_CX:
1484 	case CMD_FCP_TRECEIVE64_CX:
1485 	case CMD_GEN_REQUEST64_CR:
1486 	case CMD_GEN_REQUEST64_CX:
1487 	case CMD_XMIT_ELS_RSP64_CX:
1488 	case DSSCMD_IWRITE64_CR:
1489 	case DSSCMD_IWRITE64_CX:
1490 	case DSSCMD_IREAD64_CR:
1491 	case DSSCMD_IREAD64_CX:
1492 	case CMD_SEND_FRAME:
1493 		type = LPFC_SOL_IOCB;
1494 		break;
1495 	case CMD_ABORT_XRI_CN:
1496 	case CMD_ABORT_XRI_CX:
1497 	case CMD_CLOSE_XRI_CN:
1498 	case CMD_CLOSE_XRI_CX:
1499 	case CMD_XRI_ABORTED_CX:
1500 	case CMD_ABORT_MXRI64_CN:
1501 	case CMD_XMIT_BLS_RSP64_CX:
1502 		type = LPFC_ABORT_IOCB;
1503 		break;
1504 	case CMD_RCV_SEQUENCE_CX:
1505 	case CMD_RCV_ELS_REQ_CX:
1506 	case CMD_RCV_SEQUENCE64_CX:
1507 	case CMD_RCV_ELS_REQ64_CX:
1508 	case CMD_ASYNC_STATUS:
1509 	case CMD_IOCB_RCV_SEQ64_CX:
1510 	case CMD_IOCB_RCV_ELS64_CX:
1511 	case CMD_IOCB_RCV_CONT64_CX:
1512 	case CMD_IOCB_RET_XRI64_CX:
1513 		type = LPFC_UNSOL_IOCB;
1514 		break;
1515 	case CMD_IOCB_XMIT_MSEQ64_CR:
1516 	case CMD_IOCB_XMIT_MSEQ64_CX:
1517 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1518 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1519 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1520 	case CMD_IOCB_ABORT_EXTENDED_CN:
1521 	case CMD_IOCB_RET_HBQE64_CN:
1522 	case CMD_IOCB_FCP_IBIDIR64_CR:
1523 	case CMD_IOCB_FCP_IBIDIR64_CX:
1524 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1525 	case CMD_IOCB_LOGENTRY_CN:
1526 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1527 		printk("%s - Unhandled SLI-3 Command x%x\n",
1528 				__func__, iocb_cmnd);
1529 		type = LPFC_UNKNOWN_IOCB;
1530 		break;
1531 	default:
1532 		type = LPFC_UNKNOWN_IOCB;
1533 		break;
1534 	}
1535 
1536 	return type;
1537 }
1538 
1539 /**
1540  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1541  * @phba: Pointer to HBA context object.
1542  *
1543  * This function is called from SLI initialization code
1544  * to configure every ring of the HBA's SLI interface. The
1545  * caller is not required to hold any lock. This function issues
1546  * a config_ring mailbox command for each ring.
1547  * This function returns zero if successful else returns a negative
1548  * error code.
1549  **/
1550 static int
1551 lpfc_sli_ring_map(struct lpfc_hba *phba)
1552 {
1553 	struct lpfc_sli *psli = &phba->sli;
1554 	LPFC_MBOXQ_t *pmb;
1555 	MAILBOX_t *pmbox;
1556 	int i, rc, ret = 0;
1557 
1558 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1559 	if (!pmb)
1560 		return -ENOMEM;
1561 	pmbox = &pmb->u.mb;
1562 	phba->link_state = LPFC_INIT_MBX_CMDS;
1563 	for (i = 0; i < psli->num_rings; i++) {
1564 		lpfc_config_ring(phba, i, pmb);
1565 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1566 		if (rc != MBX_SUCCESS) {
1567 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1568 					"0446 Adapter failed to init (%d), "
1569 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1570 					"ring %d\n",
1571 					rc, pmbox->mbxCommand,
1572 					pmbox->mbxStatus, i);
1573 			phba->link_state = LPFC_HBA_ERROR;
1574 			ret = -ENXIO;
1575 			break;
1576 		}
1577 	}
1578 	mempool_free(pmb, phba->mbox_mem_pool);
1579 	return ret;
1580 }
1581 
1582 /**
1583  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1584  * @phba: Pointer to HBA context object.
1585  * @pring: Pointer to driver SLI ring object.
1586  * @piocb: Pointer to the driver iocb object.
1587  *
1588  * The driver calls this function with the hbalock held for SLI3 ports or
1589  * the ring lock held for SLI4 ports. The function adds the
1590  * new iocb to txcmplq of the given ring. This function always returns
1591  * 0. If this function is called for ELS ring, this function checks if
1592  * there is a vport associated with the ELS command. This function also
1593  * starts els_tmofunc timer if this is an ELS command.
1594  **/
1595 static int
1596 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1597 			struct lpfc_iocbq *piocb)
1598 {
1599 	if (phba->sli_rev == LPFC_SLI_REV4)
1600 		lockdep_assert_held(&pring->ring_lock);
1601 	else
1602 		lockdep_assert_held(&phba->hbalock);
1603 
1604 	BUG_ON(!piocb);
1605 
1606 	list_add_tail(&piocb->list, &pring->txcmplq);
1607 	piocb->iocb_flag |= LPFC_IO_ON_TXCMPLQ;
1608 	pring->txcmplq_cnt++;
1609 
1610 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1611 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
1612 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
1613 		BUG_ON(!piocb->vport);
1614 		if (!(piocb->vport->load_flag & FC_UNLOADING))
1615 			mod_timer(&piocb->vport->els_tmofunc,
1616 				  jiffies +
1617 				  msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1618 	}
1619 
1620 	return 0;
1621 }
1622 
1623 /**
1624  * lpfc_sli_ringtx_get - Get first element of the txq
1625  * @phba: Pointer to HBA context object.
1626  * @pring: Pointer to driver SLI ring object.
1627  *
1628  * This function is called with hbalock held to get next
1629  * iocb in txq of the given ring. If there is any iocb in
1630  * the txq, the function returns first iocb in the list after
1631  * removing the iocb from the list, else it returns NULL.
1632  **/
1633 struct lpfc_iocbq *
1634 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1635 {
1636 	struct lpfc_iocbq *cmd_iocb;
1637 
1638 	lockdep_assert_held(&phba->hbalock);
1639 
1640 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1641 	return cmd_iocb;
1642 }
1643 
1644 /**
1645  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
1646  * @phba: Pointer to HBA context object.
1647  * @pring: Pointer to driver SLI ring object.
1648  *
1649  * This function is called with hbalock held and the caller must post the
1650  * iocb without releasing the lock. If the caller releases the lock,
1651  * iocb slot returned by the function is not guaranteed to be available.
1652  * The function returns pointer to the next available iocb slot if there
1653  * is available slot in the ring, else it returns NULL.
1654  * If the get index of the ring is ahead of the put index, the function
1655  * will post an error attention event to the worker thread to take the
1656  * HBA to offline state.
1657  **/
1658 static IOCB_t *
1659 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1660 {
1661 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
1662 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
1663 
1664 	lockdep_assert_held(&phba->hbalock);
1665 
1666 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
1667 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
1668 		pring->sli.sli3.next_cmdidx = 0;
1669 
1670 	if (unlikely(pring->sli.sli3.local_getidx ==
1671 		pring->sli.sli3.next_cmdidx)) {
1672 
1673 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
1674 
1675 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
1676 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1677 					"0315 Ring %d issue: portCmdGet %d "
1678 					"is bigger than cmd ring %d\n",
1679 					pring->ringno,
1680 					pring->sli.sli3.local_getidx,
1681 					max_cmd_idx);
1682 
1683 			phba->link_state = LPFC_HBA_ERROR;
1684 			/*
1685 			 * All error attention handlers are posted to
1686 			 * worker thread
1687 			 */
1688 			phba->work_ha |= HA_ERATT;
1689 			phba->work_hs = HS_FFER3;
1690 
1691 			lpfc_worker_wake_up(phba);
1692 
1693 			return NULL;
1694 		}
1695 
1696 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
1697 			return NULL;
1698 	}
1699 
1700 	return lpfc_cmd_iocb(phba, pring);
1701 }
1702 
1703 /**
1704  * lpfc_sli_next_iotag - Get an iotag for the iocb
1705  * @phba: Pointer to HBA context object.
1706  * @iocbq: Pointer to driver iocb object.
1707  *
1708  * This function gets an iotag for the iocb. If there is no unused iotag and
1709  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
1710  * array and assigns a new iotag.
1711  * The function returns the allocated iotag if successful, else returns zero.
1712  * Zero is not a valid iotag.
1713  * The caller is not required to hold any lock.
1714  **/
1715 uint16_t
1716 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1717 {
1718 	struct lpfc_iocbq **new_arr;
1719 	struct lpfc_iocbq **old_arr;
1720 	size_t new_len;
1721 	struct lpfc_sli *psli = &phba->sli;
1722 	uint16_t iotag;
1723 
1724 	spin_lock_irq(&phba->hbalock);
1725 	iotag = psli->last_iotag;
1726 	if(++iotag < psli->iocbq_lookup_len) {
1727 		psli->last_iotag = iotag;
1728 		psli->iocbq_lookup[iotag] = iocbq;
1729 		spin_unlock_irq(&phba->hbalock);
1730 		iocbq->iotag = iotag;
1731 		return iotag;
1732 	} else if (psli->iocbq_lookup_len < (0xffff
1733 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
1734 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
1735 		spin_unlock_irq(&phba->hbalock);
1736 		new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
1737 				  GFP_KERNEL);
1738 		if (new_arr) {
1739 			spin_lock_irq(&phba->hbalock);
1740 			old_arr = psli->iocbq_lookup;
1741 			if (new_len <= psli->iocbq_lookup_len) {
1742 				/* highly unprobable case */
1743 				kfree(new_arr);
1744 				iotag = psli->last_iotag;
1745 				if(++iotag < psli->iocbq_lookup_len) {
1746 					psli->last_iotag = iotag;
1747 					psli->iocbq_lookup[iotag] = iocbq;
1748 					spin_unlock_irq(&phba->hbalock);
1749 					iocbq->iotag = iotag;
1750 					return iotag;
1751 				}
1752 				spin_unlock_irq(&phba->hbalock);
1753 				return 0;
1754 			}
1755 			if (psli->iocbq_lookup)
1756 				memcpy(new_arr, old_arr,
1757 				       ((psli->last_iotag  + 1) *
1758 					sizeof (struct lpfc_iocbq *)));
1759 			psli->iocbq_lookup = new_arr;
1760 			psli->iocbq_lookup_len = new_len;
1761 			psli->last_iotag = iotag;
1762 			psli->iocbq_lookup[iotag] = iocbq;
1763 			spin_unlock_irq(&phba->hbalock);
1764 			iocbq->iotag = iotag;
1765 			kfree(old_arr);
1766 			return iotag;
1767 		}
1768 	} else
1769 		spin_unlock_irq(&phba->hbalock);
1770 
1771 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
1772 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
1773 			psli->last_iotag);
1774 
1775 	return 0;
1776 }
1777 
1778 /**
1779  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
1780  * @phba: Pointer to HBA context object.
1781  * @pring: Pointer to driver SLI ring object.
1782  * @iocb: Pointer to iocb slot in the ring.
1783  * @nextiocb: Pointer to driver iocb object which need to be
1784  *            posted to firmware.
1785  *
1786  * This function is called to post a new iocb to the firmware. This
1787  * function copies the new iocb to ring iocb slot and updates the
1788  * ring pointers. It adds the new iocb to txcmplq if there is
1789  * a completion call back for this iocb else the function will free the
1790  * iocb object.  The hbalock is asserted held in the code path calling
1791  * this routine.
1792  **/
1793 static void
1794 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1795 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
1796 {
1797 	/*
1798 	 * Set up an iotag
1799 	 */
1800 	nextiocb->iocb.ulpIoTag = (nextiocb->iocb_cmpl) ? nextiocb->iotag : 0;
1801 
1802 
1803 	if (pring->ringno == LPFC_ELS_RING) {
1804 		lpfc_debugfs_slow_ring_trc(phba,
1805 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
1806 			*(((uint32_t *) &nextiocb->iocb) + 4),
1807 			*(((uint32_t *) &nextiocb->iocb) + 6),
1808 			*(((uint32_t *) &nextiocb->iocb) + 7));
1809 	}
1810 
1811 	/*
1812 	 * Issue iocb command to adapter
1813 	 */
1814 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
1815 	wmb();
1816 	pring->stats.iocb_cmd++;
1817 
1818 	/*
1819 	 * If there is no completion routine to call, we can release the
1820 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
1821 	 * that have no rsp ring completion, iocb_cmpl MUST be NULL.
1822 	 */
1823 	if (nextiocb->iocb_cmpl)
1824 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
1825 	else
1826 		__lpfc_sli_release_iocbq(phba, nextiocb);
1827 
1828 	/*
1829 	 * Let the HBA know what IOCB slot will be the next one the
1830 	 * driver will put a command into.
1831 	 */
1832 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
1833 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
1834 }
1835 
1836 /**
1837  * lpfc_sli_update_full_ring - Update the chip attention register
1838  * @phba: Pointer to HBA context object.
1839  * @pring: Pointer to driver SLI ring object.
1840  *
1841  * The caller is not required to hold any lock for calling this function.
1842  * This function updates the chip attention bits for the ring to inform firmware
1843  * that there are pending work to be done for this ring and requests an
1844  * interrupt when there is space available in the ring. This function is
1845  * called when the driver is unable to post more iocbs to the ring due
1846  * to unavailability of space in the ring.
1847  **/
1848 static void
1849 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1850 {
1851 	int ringno = pring->ringno;
1852 
1853 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
1854 
1855 	wmb();
1856 
1857 	/*
1858 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
1859 	 * The HBA will tell us when an IOCB entry is available.
1860 	 */
1861 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
1862 	readl(phba->CAregaddr); /* flush */
1863 
1864 	pring->stats.iocb_cmd_full++;
1865 }
1866 
1867 /**
1868  * lpfc_sli_update_ring - Update chip attention register
1869  * @phba: Pointer to HBA context object.
1870  * @pring: Pointer to driver SLI ring object.
1871  *
1872  * This function updates the chip attention register bit for the
1873  * given ring to inform HBA that there is more work to be done
1874  * in this ring. The caller is not required to hold any lock.
1875  **/
1876 static void
1877 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1878 {
1879 	int ringno = pring->ringno;
1880 
1881 	/*
1882 	 * Tell the HBA that there is work to do in this ring.
1883 	 */
1884 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
1885 		wmb();
1886 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
1887 		readl(phba->CAregaddr); /* flush */
1888 	}
1889 }
1890 
1891 /**
1892  * lpfc_sli_resume_iocb - Process iocbs in the txq
1893  * @phba: Pointer to HBA context object.
1894  * @pring: Pointer to driver SLI ring object.
1895  *
1896  * This function is called with hbalock held to post pending iocbs
1897  * in the txq to the firmware. This function is called when driver
1898  * detects space available in the ring.
1899  **/
1900 static void
1901 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1902 {
1903 	IOCB_t *iocb;
1904 	struct lpfc_iocbq *nextiocb;
1905 
1906 	lockdep_assert_held(&phba->hbalock);
1907 
1908 	/*
1909 	 * Check to see if:
1910 	 *  (a) there is anything on the txq to send
1911 	 *  (b) link is up
1912 	 *  (c) link attention events can be processed (fcp ring only)
1913 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
1914 	 */
1915 
1916 	if (lpfc_is_link_up(phba) &&
1917 	    (!list_empty(&pring->txq)) &&
1918 	    (pring->ringno != LPFC_FCP_RING ||
1919 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
1920 
1921 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
1922 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
1923 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
1924 
1925 		if (iocb)
1926 			lpfc_sli_update_ring(phba, pring);
1927 		else
1928 			lpfc_sli_update_full_ring(phba, pring);
1929 	}
1930 
1931 	return;
1932 }
1933 
1934 /**
1935  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
1936  * @phba: Pointer to HBA context object.
1937  * @hbqno: HBQ number.
1938  *
1939  * This function is called with hbalock held to get the next
1940  * available slot for the given HBQ. If there is free slot
1941  * available for the HBQ it will return pointer to the next available
1942  * HBQ entry else it will return NULL.
1943  **/
1944 static struct lpfc_hbq_entry *
1945 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
1946 {
1947 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
1948 
1949 	lockdep_assert_held(&phba->hbalock);
1950 
1951 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
1952 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
1953 		hbqp->next_hbqPutIdx = 0;
1954 
1955 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
1956 		uint32_t raw_index = phba->hbq_get[hbqno];
1957 		uint32_t getidx = le32_to_cpu(raw_index);
1958 
1959 		hbqp->local_hbqGetIdx = getidx;
1960 
1961 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
1962 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1963 					"1802 HBQ %d: local_hbqGetIdx "
1964 					"%u is > than hbqp->entry_count %u\n",
1965 					hbqno, hbqp->local_hbqGetIdx,
1966 					hbqp->entry_count);
1967 
1968 			phba->link_state = LPFC_HBA_ERROR;
1969 			return NULL;
1970 		}
1971 
1972 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
1973 			return NULL;
1974 	}
1975 
1976 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
1977 			hbqp->hbqPutIdx;
1978 }
1979 
1980 /**
1981  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
1982  * @phba: Pointer to HBA context object.
1983  *
1984  * This function is called with no lock held to free all the
1985  * hbq buffers while uninitializing the SLI interface. It also
1986  * frees the HBQ buffers returned by the firmware but not yet
1987  * processed by the upper layers.
1988  **/
1989 void
1990 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
1991 {
1992 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
1993 	struct hbq_dmabuf *hbq_buf;
1994 	unsigned long flags;
1995 	int i, hbq_count;
1996 
1997 	hbq_count = lpfc_sli_hbq_count();
1998 	/* Return all memory used by all HBQs */
1999 	spin_lock_irqsave(&phba->hbalock, flags);
2000 	for (i = 0; i < hbq_count; ++i) {
2001 		list_for_each_entry_safe(dmabuf, next_dmabuf,
2002 				&phba->hbqs[i].hbq_buffer_list, list) {
2003 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2004 			list_del(&hbq_buf->dbuf.list);
2005 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2006 		}
2007 		phba->hbqs[i].buffer_count = 0;
2008 	}
2009 
2010 	/* Mark the HBQs not in use */
2011 	phba->hbq_in_use = 0;
2012 	spin_unlock_irqrestore(&phba->hbalock, flags);
2013 }
2014 
2015 /**
2016  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2017  * @phba: Pointer to HBA context object.
2018  * @hbqno: HBQ number.
2019  * @hbq_buf: Pointer to HBQ buffer.
2020  *
2021  * This function is called with the hbalock held to post a
2022  * hbq buffer to the firmware. If the function finds an empty
2023  * slot in the HBQ, it will post the buffer. The function will return
2024  * pointer to the hbq entry if it successfully post the buffer
2025  * else it will return NULL.
2026  **/
2027 static int
2028 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2029 			 struct hbq_dmabuf *hbq_buf)
2030 {
2031 	lockdep_assert_held(&phba->hbalock);
2032 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2033 }
2034 
2035 /**
2036  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2037  * @phba: Pointer to HBA context object.
2038  * @hbqno: HBQ number.
2039  * @hbq_buf: Pointer to HBQ buffer.
2040  *
2041  * This function is called with the hbalock held to post a hbq buffer to the
2042  * firmware. If the function finds an empty slot in the HBQ, it will post the
2043  * buffer and place it on the hbq_buffer_list. The function will return zero if
2044  * it successfully post the buffer else it will return an error.
2045  **/
2046 static int
2047 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2048 			    struct hbq_dmabuf *hbq_buf)
2049 {
2050 	struct lpfc_hbq_entry *hbqe;
2051 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
2052 
2053 	lockdep_assert_held(&phba->hbalock);
2054 	/* Get next HBQ entry slot to use */
2055 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2056 	if (hbqe) {
2057 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
2058 
2059 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2060 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2061 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2062 		hbqe->bde.tus.f.bdeFlags = 0;
2063 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2064 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2065 				/* Sync SLIM */
2066 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2067 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2068 				/* flush */
2069 		readl(phba->hbq_put + hbqno);
2070 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2071 		return 0;
2072 	} else
2073 		return -ENOMEM;
2074 }
2075 
2076 /**
2077  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2078  * @phba: Pointer to HBA context object.
2079  * @hbqno: HBQ number.
2080  * @hbq_buf: Pointer to HBQ buffer.
2081  *
2082  * This function is called with the hbalock held to post an RQE to the SLI4
2083  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2084  * the hbq_buffer_list and return zero, otherwise it will return an error.
2085  **/
2086 static int
2087 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2088 			    struct hbq_dmabuf *hbq_buf)
2089 {
2090 	int rc;
2091 	struct lpfc_rqe hrqe;
2092 	struct lpfc_rqe drqe;
2093 	struct lpfc_queue *hrq;
2094 	struct lpfc_queue *drq;
2095 
2096 	if (hbqno != LPFC_ELS_HBQ)
2097 		return 1;
2098 	hrq = phba->sli4_hba.hdr_rq;
2099 	drq = phba->sli4_hba.dat_rq;
2100 
2101 	lockdep_assert_held(&phba->hbalock);
2102 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2103 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2104 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2105 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2106 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2107 	if (rc < 0)
2108 		return rc;
2109 	hbq_buf->tag = (rc | (hbqno << 16));
2110 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2111 	return 0;
2112 }
2113 
2114 /* HBQ for ELS and CT traffic. */
2115 static struct lpfc_hbq_init lpfc_els_hbq = {
2116 	.rn = 1,
2117 	.entry_count = 256,
2118 	.mask_count = 0,
2119 	.profile = 0,
2120 	.ring_mask = (1 << LPFC_ELS_RING),
2121 	.buffer_count = 0,
2122 	.init_count = 40,
2123 	.add_count = 40,
2124 };
2125 
2126 /* Array of HBQs */
2127 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2128 	&lpfc_els_hbq,
2129 };
2130 
2131 /**
2132  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2133  * @phba: Pointer to HBA context object.
2134  * @hbqno: HBQ number.
2135  * @count: Number of HBQ buffers to be posted.
2136  *
2137  * This function is called with no lock held to post more hbq buffers to the
2138  * given HBQ. The function returns the number of HBQ buffers successfully
2139  * posted.
2140  **/
2141 static int
2142 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2143 {
2144 	uint32_t i, posted = 0;
2145 	unsigned long flags;
2146 	struct hbq_dmabuf *hbq_buffer;
2147 	LIST_HEAD(hbq_buf_list);
2148 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2149 		return 0;
2150 
2151 	if ((phba->hbqs[hbqno].buffer_count + count) >
2152 	    lpfc_hbq_defs[hbqno]->entry_count)
2153 		count = lpfc_hbq_defs[hbqno]->entry_count -
2154 					phba->hbqs[hbqno].buffer_count;
2155 	if (!count)
2156 		return 0;
2157 	/* Allocate HBQ entries */
2158 	for (i = 0; i < count; i++) {
2159 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2160 		if (!hbq_buffer)
2161 			break;
2162 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2163 	}
2164 	/* Check whether HBQ is still in use */
2165 	spin_lock_irqsave(&phba->hbalock, flags);
2166 	if (!phba->hbq_in_use)
2167 		goto err;
2168 	while (!list_empty(&hbq_buf_list)) {
2169 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2170 				 dbuf.list);
2171 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2172 				      (hbqno << 16));
2173 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2174 			phba->hbqs[hbqno].buffer_count++;
2175 			posted++;
2176 		} else
2177 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2178 	}
2179 	spin_unlock_irqrestore(&phba->hbalock, flags);
2180 	return posted;
2181 err:
2182 	spin_unlock_irqrestore(&phba->hbalock, flags);
2183 	while (!list_empty(&hbq_buf_list)) {
2184 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2185 				 dbuf.list);
2186 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2187 	}
2188 	return 0;
2189 }
2190 
2191 /**
2192  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2193  * @phba: Pointer to HBA context object.
2194  * @qno: HBQ number.
2195  *
2196  * This function posts more buffers to the HBQ. This function
2197  * is called with no lock held. The function returns the number of HBQ entries
2198  * successfully allocated.
2199  **/
2200 int
2201 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2202 {
2203 	if (phba->sli_rev == LPFC_SLI_REV4)
2204 		return 0;
2205 	else
2206 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2207 					 lpfc_hbq_defs[qno]->add_count);
2208 }
2209 
2210 /**
2211  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2212  * @phba: Pointer to HBA context object.
2213  * @qno:  HBQ queue number.
2214  *
2215  * This function is called from SLI initialization code path with
2216  * no lock held to post initial HBQ buffers to firmware. The
2217  * function returns the number of HBQ entries successfully allocated.
2218  **/
2219 static int
2220 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2221 {
2222 	if (phba->sli_rev == LPFC_SLI_REV4)
2223 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2224 					lpfc_hbq_defs[qno]->entry_count);
2225 	else
2226 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2227 					 lpfc_hbq_defs[qno]->init_count);
2228 }
2229 
2230 /*
2231  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2232  *
2233  * This function removes the first hbq buffer on an hbq list and returns a
2234  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2235  **/
2236 static struct hbq_dmabuf *
2237 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2238 {
2239 	struct lpfc_dmabuf *d_buf;
2240 
2241 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2242 	if (!d_buf)
2243 		return NULL;
2244 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2245 }
2246 
2247 /**
2248  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2249  * @phba: Pointer to HBA context object.
2250  * @hrq: HBQ number.
2251  *
2252  * This function removes the first RQ buffer on an RQ buffer list and returns a
2253  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2254  **/
2255 static struct rqb_dmabuf *
2256 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2257 {
2258 	struct lpfc_dmabuf *h_buf;
2259 	struct lpfc_rqb *rqbp;
2260 
2261 	rqbp = hrq->rqbp;
2262 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2263 			 struct lpfc_dmabuf, list);
2264 	if (!h_buf)
2265 		return NULL;
2266 	rqbp->buffer_count--;
2267 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2268 }
2269 
2270 /**
2271  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2272  * @phba: Pointer to HBA context object.
2273  * @tag: Tag of the hbq buffer.
2274  *
2275  * This function searches for the hbq buffer associated with the given tag in
2276  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2277  * otherwise it returns NULL.
2278  **/
2279 static struct hbq_dmabuf *
2280 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2281 {
2282 	struct lpfc_dmabuf *d_buf;
2283 	struct hbq_dmabuf *hbq_buf;
2284 	uint32_t hbqno;
2285 
2286 	hbqno = tag >> 16;
2287 	if (hbqno >= LPFC_MAX_HBQS)
2288 		return NULL;
2289 
2290 	spin_lock_irq(&phba->hbalock);
2291 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2292 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2293 		if (hbq_buf->tag == tag) {
2294 			spin_unlock_irq(&phba->hbalock);
2295 			return hbq_buf;
2296 		}
2297 	}
2298 	spin_unlock_irq(&phba->hbalock);
2299 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2300 			"1803 Bad hbq tag. Data: x%x x%x\n",
2301 			tag, phba->hbqs[tag >> 16].buffer_count);
2302 	return NULL;
2303 }
2304 
2305 /**
2306  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2307  * @phba: Pointer to HBA context object.
2308  * @hbq_buffer: Pointer to HBQ buffer.
2309  *
2310  * This function is called with hbalock. This function gives back
2311  * the hbq buffer to firmware. If the HBQ does not have space to
2312  * post the buffer, it will free the buffer.
2313  **/
2314 void
2315 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2316 {
2317 	uint32_t hbqno;
2318 
2319 	if (hbq_buffer) {
2320 		hbqno = hbq_buffer->tag >> 16;
2321 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2322 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2323 	}
2324 }
2325 
2326 /**
2327  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2328  * @mbxCommand: mailbox command code.
2329  *
2330  * This function is called by the mailbox event handler function to verify
2331  * that the completed mailbox command is a legitimate mailbox command. If the
2332  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2333  * and the mailbox event handler will take the HBA offline.
2334  **/
2335 static int
2336 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2337 {
2338 	uint8_t ret;
2339 
2340 	switch (mbxCommand) {
2341 	case MBX_LOAD_SM:
2342 	case MBX_READ_NV:
2343 	case MBX_WRITE_NV:
2344 	case MBX_WRITE_VPARMS:
2345 	case MBX_RUN_BIU_DIAG:
2346 	case MBX_INIT_LINK:
2347 	case MBX_DOWN_LINK:
2348 	case MBX_CONFIG_LINK:
2349 	case MBX_CONFIG_RING:
2350 	case MBX_RESET_RING:
2351 	case MBX_READ_CONFIG:
2352 	case MBX_READ_RCONFIG:
2353 	case MBX_READ_SPARM:
2354 	case MBX_READ_STATUS:
2355 	case MBX_READ_RPI:
2356 	case MBX_READ_XRI:
2357 	case MBX_READ_REV:
2358 	case MBX_READ_LNK_STAT:
2359 	case MBX_REG_LOGIN:
2360 	case MBX_UNREG_LOGIN:
2361 	case MBX_CLEAR_LA:
2362 	case MBX_DUMP_MEMORY:
2363 	case MBX_DUMP_CONTEXT:
2364 	case MBX_RUN_DIAGS:
2365 	case MBX_RESTART:
2366 	case MBX_UPDATE_CFG:
2367 	case MBX_DOWN_LOAD:
2368 	case MBX_DEL_LD_ENTRY:
2369 	case MBX_RUN_PROGRAM:
2370 	case MBX_SET_MASK:
2371 	case MBX_SET_VARIABLE:
2372 	case MBX_UNREG_D_ID:
2373 	case MBX_KILL_BOARD:
2374 	case MBX_CONFIG_FARP:
2375 	case MBX_BEACON:
2376 	case MBX_LOAD_AREA:
2377 	case MBX_RUN_BIU_DIAG64:
2378 	case MBX_CONFIG_PORT:
2379 	case MBX_READ_SPARM64:
2380 	case MBX_READ_RPI64:
2381 	case MBX_REG_LOGIN64:
2382 	case MBX_READ_TOPOLOGY:
2383 	case MBX_WRITE_WWN:
2384 	case MBX_SET_DEBUG:
2385 	case MBX_LOAD_EXP_ROM:
2386 	case MBX_ASYNCEVT_ENABLE:
2387 	case MBX_REG_VPI:
2388 	case MBX_UNREG_VPI:
2389 	case MBX_HEARTBEAT:
2390 	case MBX_PORT_CAPABILITIES:
2391 	case MBX_PORT_IOV_CONTROL:
2392 	case MBX_SLI4_CONFIG:
2393 	case MBX_SLI4_REQ_FTRS:
2394 	case MBX_REG_FCFI:
2395 	case MBX_UNREG_FCFI:
2396 	case MBX_REG_VFI:
2397 	case MBX_UNREG_VFI:
2398 	case MBX_INIT_VPI:
2399 	case MBX_INIT_VFI:
2400 	case MBX_RESUME_RPI:
2401 	case MBX_READ_EVENT_LOG_STATUS:
2402 	case MBX_READ_EVENT_LOG:
2403 	case MBX_SECURITY_MGMT:
2404 	case MBX_AUTH_PORT:
2405 	case MBX_ACCESS_VDATA:
2406 		ret = mbxCommand;
2407 		break;
2408 	default:
2409 		ret = MBX_SHUTDOWN;
2410 		break;
2411 	}
2412 	return ret;
2413 }
2414 
2415 /**
2416  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2417  * @phba: Pointer to HBA context object.
2418  * @pmboxq: Pointer to mailbox command.
2419  *
2420  * This is completion handler function for mailbox commands issued from
2421  * lpfc_sli_issue_mbox_wait function. This function is called by the
2422  * mailbox event handler function with no lock held. This function
2423  * will wake up thread waiting on the wait queue pointed by context1
2424  * of the mailbox.
2425  **/
2426 void
2427 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2428 {
2429 	unsigned long drvr_flag;
2430 	struct completion *pmbox_done;
2431 
2432 	/*
2433 	 * If pmbox_done is empty, the driver thread gave up waiting and
2434 	 * continued running.
2435 	 */
2436 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2437 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2438 	pmbox_done = (struct completion *)pmboxq->context3;
2439 	if (pmbox_done)
2440 		complete(pmbox_done);
2441 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2442 	return;
2443 }
2444 
2445 static void
2446 __lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2447 {
2448 	unsigned long iflags;
2449 
2450 	if (ndlp->nlp_flag & NLP_RELEASE_RPI) {
2451 		lpfc_sli4_free_rpi(vport->phba, ndlp->nlp_rpi);
2452 		spin_lock_irqsave(&vport->phba->ndlp_lock, iflags);
2453 		ndlp->nlp_flag &= ~NLP_RELEASE_RPI;
2454 		ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
2455 		spin_unlock_irqrestore(&vport->phba->ndlp_lock, iflags);
2456 	}
2457 	ndlp->nlp_flag &= ~NLP_UNREG_INP;
2458 }
2459 
2460 /**
2461  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2462  * @phba: Pointer to HBA context object.
2463  * @pmb: Pointer to mailbox object.
2464  *
2465  * This function is the default mailbox completion handler. It
2466  * frees the memory resources associated with the completed mailbox
2467  * command. If the completed command is a REG_LOGIN mailbox command,
2468  * this function will issue a UREG_LOGIN to re-claim the RPI.
2469  **/
2470 void
2471 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2472 {
2473 	struct lpfc_vport  *vport = pmb->vport;
2474 	struct lpfc_dmabuf *mp;
2475 	struct lpfc_nodelist *ndlp;
2476 	struct Scsi_Host *shost;
2477 	uint16_t rpi, vpi;
2478 	int rc;
2479 
2480 	mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
2481 
2482 	if (mp) {
2483 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
2484 		kfree(mp);
2485 	}
2486 
2487 	/*
2488 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2489 	 * is in re-discovery driver need to cleanup the RPI.
2490 	 */
2491 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2492 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2493 	    !pmb->u.mb.mbxStatus) {
2494 		rpi = pmb->u.mb.un.varWords[0];
2495 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2496 		if (phba->sli_rev == LPFC_SLI_REV4)
2497 			vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2498 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2499 		pmb->vport = vport;
2500 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2501 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2502 		if (rc != MBX_NOT_FINISHED)
2503 			return;
2504 	}
2505 
2506 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2507 		!(phba->pport->load_flag & FC_UNLOADING) &&
2508 		!pmb->u.mb.mbxStatus) {
2509 		shost = lpfc_shost_from_vport(vport);
2510 		spin_lock_irq(shost->host_lock);
2511 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2512 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2513 		spin_unlock_irq(shost->host_lock);
2514 	}
2515 
2516 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2517 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2518 		lpfc_nlp_put(ndlp);
2519 		pmb->ctx_buf = NULL;
2520 		pmb->ctx_ndlp = NULL;
2521 	}
2522 
2523 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2524 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2525 
2526 		/* Check to see if there are any deferred events to process */
2527 		if (ndlp) {
2528 			lpfc_printf_vlog(
2529 				vport,
2530 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2531 				"1438 UNREG cmpl deferred mbox x%x "
2532 				"on NPort x%x Data: x%x x%x %px\n",
2533 				ndlp->nlp_rpi, ndlp->nlp_DID,
2534 				ndlp->nlp_flag, ndlp->nlp_defer_did, ndlp);
2535 
2536 			if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2537 			    (ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING)) {
2538 				ndlp->nlp_flag &= ~NLP_UNREG_INP;
2539 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2540 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2541 			} else {
2542 				__lpfc_sli_rpi_release(vport, ndlp);
2543 			}
2544 			if (vport->load_flag & FC_UNLOADING)
2545 				lpfc_nlp_put(ndlp);
2546 			pmb->ctx_ndlp = NULL;
2547 		}
2548 	}
2549 
2550 	/* Check security permission status on INIT_LINK mailbox command */
2551 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2552 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2553 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2554 				"2860 SLI authentication is required "
2555 				"for INIT_LINK but has not done yet\n");
2556 
2557 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2558 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2559 	else
2560 		mempool_free(pmb, phba->mbox_mem_pool);
2561 }
2562  /**
2563  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2564  * @phba: Pointer to HBA context object.
2565  * @pmb: Pointer to mailbox object.
2566  *
2567  * This function is the unreg rpi mailbox completion handler. It
2568  * frees the memory resources associated with the completed mailbox
2569  * command. An additional refrenece is put on the ndlp to prevent
2570  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2571  * the unreg mailbox command completes, this routine puts the
2572  * reference back.
2573  *
2574  **/
2575 void
2576 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2577 {
2578 	struct lpfc_vport  *vport = pmb->vport;
2579 	struct lpfc_nodelist *ndlp;
2580 
2581 	ndlp = pmb->ctx_ndlp;
2582 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2583 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2584 		    (bf_get(lpfc_sli_intf_if_type,
2585 		     &phba->sli4_hba.sli_intf) >=
2586 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2587 			if (ndlp) {
2588 				lpfc_printf_vlog(
2589 					vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2590 					 "0010 UNREG_LOGIN vpi:%x "
2591 					 "rpi:%x DID:%x defer x%x flg x%x "
2592 					 "map:%x %px\n",
2593 					 vport->vpi, ndlp->nlp_rpi,
2594 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
2595 					 ndlp->nlp_flag,
2596 					 ndlp->nlp_usg_map, ndlp);
2597 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2598 				lpfc_nlp_put(ndlp);
2599 
2600 				/* Check to see if there are any deferred
2601 				 * events to process
2602 				 */
2603 				if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2604 				    (ndlp->nlp_defer_did !=
2605 				    NLP_EVT_NOTHING_PENDING)) {
2606 					lpfc_printf_vlog(
2607 						vport, KERN_INFO, LOG_DISCOVERY,
2608 						"4111 UNREG cmpl deferred "
2609 						"clr x%x on "
2610 						"NPort x%x Data: x%x x%px\n",
2611 						ndlp->nlp_rpi, ndlp->nlp_DID,
2612 						ndlp->nlp_defer_did, ndlp);
2613 					ndlp->nlp_flag &= ~NLP_UNREG_INP;
2614 					ndlp->nlp_defer_did =
2615 						NLP_EVT_NOTHING_PENDING;
2616 					lpfc_issue_els_plogi(
2617 						vport, ndlp->nlp_DID, 0);
2618 				} else {
2619 					__lpfc_sli_rpi_release(vport, ndlp);
2620 				}
2621 			}
2622 		}
2623 	}
2624 
2625 	mempool_free(pmb, phba->mbox_mem_pool);
2626 }
2627 
2628 /**
2629  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
2630  * @phba: Pointer to HBA context object.
2631  *
2632  * This function is called with no lock held. This function processes all
2633  * the completed mailbox commands and gives it to upper layers. The interrupt
2634  * service routine processes mailbox completion interrupt and adds completed
2635  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
2636  * Worker thread call lpfc_sli_handle_mb_event, which will return the
2637  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
2638  * function returns the mailbox commands to the upper layer by calling the
2639  * completion handler function of each mailbox.
2640  **/
2641 int
2642 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
2643 {
2644 	MAILBOX_t *pmbox;
2645 	LPFC_MBOXQ_t *pmb;
2646 	int rc;
2647 	LIST_HEAD(cmplq);
2648 
2649 	phba->sli.slistat.mbox_event++;
2650 
2651 	/* Get all completed mailboxe buffers into the cmplq */
2652 	spin_lock_irq(&phba->hbalock);
2653 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
2654 	spin_unlock_irq(&phba->hbalock);
2655 
2656 	/* Get a Mailbox buffer to setup mailbox commands for callback */
2657 	do {
2658 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
2659 		if (pmb == NULL)
2660 			break;
2661 
2662 		pmbox = &pmb->u.mb;
2663 
2664 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
2665 			if (pmb->vport) {
2666 				lpfc_debugfs_disc_trc(pmb->vport,
2667 					LPFC_DISC_TRC_MBOX_VPORT,
2668 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
2669 					(uint32_t)pmbox->mbxCommand,
2670 					pmbox->un.varWords[0],
2671 					pmbox->un.varWords[1]);
2672 			}
2673 			else {
2674 				lpfc_debugfs_disc_trc(phba->pport,
2675 					LPFC_DISC_TRC_MBOX,
2676 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
2677 					(uint32_t)pmbox->mbxCommand,
2678 					pmbox->un.varWords[0],
2679 					pmbox->un.varWords[1]);
2680 			}
2681 		}
2682 
2683 		/*
2684 		 * It is a fatal error if unknown mbox command completion.
2685 		 */
2686 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
2687 		    MBX_SHUTDOWN) {
2688 			/* Unknown mailbox command compl */
2689 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2690 					"(%d):0323 Unknown Mailbox command "
2691 					"x%x (x%x/x%x) Cmpl\n",
2692 					pmb->vport ? pmb->vport->vpi :
2693 					LPFC_VPORT_UNKNOWN,
2694 					pmbox->mbxCommand,
2695 					lpfc_sli_config_mbox_subsys_get(phba,
2696 									pmb),
2697 					lpfc_sli_config_mbox_opcode_get(phba,
2698 									pmb));
2699 			phba->link_state = LPFC_HBA_ERROR;
2700 			phba->work_hs = HS_FFER3;
2701 			lpfc_handle_eratt(phba);
2702 			continue;
2703 		}
2704 
2705 		if (pmbox->mbxStatus) {
2706 			phba->sli.slistat.mbox_stat_err++;
2707 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
2708 				/* Mbox cmd cmpl error - RETRYing */
2709 				lpfc_printf_log(phba, KERN_INFO,
2710 					LOG_MBOX | LOG_SLI,
2711 					"(%d):0305 Mbox cmd cmpl "
2712 					"error - RETRYing Data: x%x "
2713 					"(x%x/x%x) x%x x%x x%x\n",
2714 					pmb->vport ? pmb->vport->vpi :
2715 					LPFC_VPORT_UNKNOWN,
2716 					pmbox->mbxCommand,
2717 					lpfc_sli_config_mbox_subsys_get(phba,
2718 									pmb),
2719 					lpfc_sli_config_mbox_opcode_get(phba,
2720 									pmb),
2721 					pmbox->mbxStatus,
2722 					pmbox->un.varWords[0],
2723 					pmb->vport ? pmb->vport->port_state :
2724 					LPFC_VPORT_UNKNOWN);
2725 				pmbox->mbxStatus = 0;
2726 				pmbox->mbxOwner = OWN_HOST;
2727 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2728 				if (rc != MBX_NOT_FINISHED)
2729 					continue;
2730 			}
2731 		}
2732 
2733 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
2734 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
2735 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
2736 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
2737 				"x%x x%x x%x\n",
2738 				pmb->vport ? pmb->vport->vpi : 0,
2739 				pmbox->mbxCommand,
2740 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
2741 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
2742 				pmb->mbox_cmpl,
2743 				*((uint32_t *) pmbox),
2744 				pmbox->un.varWords[0],
2745 				pmbox->un.varWords[1],
2746 				pmbox->un.varWords[2],
2747 				pmbox->un.varWords[3],
2748 				pmbox->un.varWords[4],
2749 				pmbox->un.varWords[5],
2750 				pmbox->un.varWords[6],
2751 				pmbox->un.varWords[7],
2752 				pmbox->un.varWords[8],
2753 				pmbox->un.varWords[9],
2754 				pmbox->un.varWords[10]);
2755 
2756 		if (pmb->mbox_cmpl)
2757 			pmb->mbox_cmpl(phba,pmb);
2758 	} while (1);
2759 	return 0;
2760 }
2761 
2762 /**
2763  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
2764  * @phba: Pointer to HBA context object.
2765  * @pring: Pointer to driver SLI ring object.
2766  * @tag: buffer tag.
2767  *
2768  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
2769  * is set in the tag the buffer is posted for a particular exchange,
2770  * the function will return the buffer without replacing the buffer.
2771  * If the buffer is for unsolicited ELS or CT traffic, this function
2772  * returns the buffer and also posts another buffer to the firmware.
2773  **/
2774 static struct lpfc_dmabuf *
2775 lpfc_sli_get_buff(struct lpfc_hba *phba,
2776 		  struct lpfc_sli_ring *pring,
2777 		  uint32_t tag)
2778 {
2779 	struct hbq_dmabuf *hbq_entry;
2780 
2781 	if (tag & QUE_BUFTAG_BIT)
2782 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
2783 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
2784 	if (!hbq_entry)
2785 		return NULL;
2786 	return &hbq_entry->dbuf;
2787 }
2788 
2789 /**
2790  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
2791  *                              containing a NVME LS request.
2792  * @phba: pointer to lpfc hba data structure.
2793  * @piocb: pointer to the iocbq struct representing the sequence starting
2794  *        frame.
2795  *
2796  * This routine initially validates the NVME LS, validates there is a login
2797  * with the port that sent the LS, and then calls the appropriate nvme host
2798  * or target LS request handler.
2799  **/
2800 static void
2801 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
2802 {
2803 	struct lpfc_nodelist *ndlp;
2804 	struct lpfc_dmabuf *d_buf;
2805 	struct hbq_dmabuf *nvmebuf;
2806 	struct fc_frame_header *fc_hdr;
2807 	struct lpfc_async_xchg_ctx *axchg = NULL;
2808 	char *failwhy = NULL;
2809 	uint32_t oxid, sid, did, fctl, size;
2810 	int ret = 1;
2811 
2812 	d_buf = piocb->context2;
2813 
2814 	nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2815 	fc_hdr = nvmebuf->hbuf.virt;
2816 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
2817 	sid = sli4_sid_from_fc_hdr(fc_hdr);
2818 	did = sli4_did_from_fc_hdr(fc_hdr);
2819 	fctl = (fc_hdr->fh_f_ctl[0] << 16 |
2820 		fc_hdr->fh_f_ctl[1] << 8 |
2821 		fc_hdr->fh_f_ctl[2]);
2822 	size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
2823 
2824 	lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
2825 			 oxid, size, sid);
2826 
2827 	if (phba->pport->load_flag & FC_UNLOADING) {
2828 		failwhy = "Driver Unloading";
2829 	} else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
2830 		failwhy = "NVME FC4 Disabled";
2831 	} else if (!phba->nvmet_support && !phba->pport->localport) {
2832 		failwhy = "No Localport";
2833 	} else if (phba->nvmet_support && !phba->targetport) {
2834 		failwhy = "No Targetport";
2835 	} else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
2836 		failwhy = "Bad NVME LS R_CTL";
2837 	} else if (unlikely((fctl & 0x00FF0000) !=
2838 			(FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
2839 		failwhy = "Bad NVME LS F_CTL";
2840 	} else {
2841 		axchg = kzalloc(sizeof(*axchg), GFP_ATOMIC);
2842 		if (!axchg)
2843 			failwhy = "No CTX memory";
2844 	}
2845 
2846 	if (unlikely(failwhy)) {
2847 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2848 				"6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
2849 				sid, oxid, failwhy);
2850 		goto out_fail;
2851 	}
2852 
2853 	/* validate the source of the LS is logged in */
2854 	ndlp = lpfc_findnode_did(phba->pport, sid);
2855 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp) ||
2856 	    ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
2857 	     (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
2858 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
2859 				"6216 NVME Unsol rcv: No ndlp: "
2860 				"NPort_ID x%x oxid x%x\n",
2861 				sid, oxid);
2862 		goto out_fail;
2863 	}
2864 
2865 	axchg->phba = phba;
2866 	axchg->ndlp = ndlp;
2867 	axchg->size = size;
2868 	axchg->oxid = oxid;
2869 	axchg->sid = sid;
2870 	axchg->wqeq = NULL;
2871 	axchg->state = LPFC_NVME_STE_LS_RCV;
2872 	axchg->entry_cnt = 1;
2873 	axchg->rqb_buffer = (void *)nvmebuf;
2874 	axchg->hdwq = &phba->sli4_hba.hdwq[0];
2875 	axchg->payload = nvmebuf->dbuf.virt;
2876 	INIT_LIST_HEAD(&axchg->list);
2877 
2878 	if (phba->nvmet_support)
2879 		ret = lpfc_nvmet_handle_lsreq(phba, axchg);
2880 	else
2881 		ret = lpfc_nvme_handle_lsreq(phba, axchg);
2882 
2883 	/* if zero, LS was successfully handled. If non-zero, LS not handled */
2884 	if (!ret)
2885 		return;
2886 
2887 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2888 			"6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
2889 			"NVMe%s handler failed %d\n",
2890 			did, sid, oxid,
2891 			(phba->nvmet_support) ? "T" : "I", ret);
2892 
2893 out_fail:
2894 
2895 	/* recycle receive buffer */
2896 	lpfc_in_buf_free(phba, &nvmebuf->dbuf);
2897 
2898 	/* If start of new exchange, abort it */
2899 	if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
2900 		ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
2901 
2902 	if (ret)
2903 		kfree(axchg);
2904 }
2905 
2906 /**
2907  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
2908  * @phba: Pointer to HBA context object.
2909  * @pring: Pointer to driver SLI ring object.
2910  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
2911  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
2912  * @fch_type: the type for the first frame of the sequence.
2913  *
2914  * This function is called with no lock held. This function uses the r_ctl and
2915  * type of the received sequence to find the correct callback function to call
2916  * to process the sequence.
2917  **/
2918 static int
2919 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2920 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
2921 			 uint32_t fch_type)
2922 {
2923 	int i;
2924 
2925 	switch (fch_type) {
2926 	case FC_TYPE_NVME:
2927 		lpfc_nvme_unsol_ls_handler(phba, saveq);
2928 		return 1;
2929 	default:
2930 		break;
2931 	}
2932 
2933 	/* unSolicited Responses */
2934 	if (pring->prt[0].profile) {
2935 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
2936 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
2937 									saveq);
2938 		return 1;
2939 	}
2940 	/* We must search, based on rctl / type
2941 	   for the right routine */
2942 	for (i = 0; i < pring->num_mask; i++) {
2943 		if ((pring->prt[i].rctl == fch_r_ctl) &&
2944 		    (pring->prt[i].type == fch_type)) {
2945 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
2946 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
2947 						(phba, pring, saveq);
2948 			return 1;
2949 		}
2950 	}
2951 	return 0;
2952 }
2953 
2954 /**
2955  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
2956  * @phba: Pointer to HBA context object.
2957  * @pring: Pointer to driver SLI ring object.
2958  * @saveq: Pointer to the unsolicited iocb.
2959  *
2960  * This function is called with no lock held by the ring event handler
2961  * when there is an unsolicited iocb posted to the response ring by the
2962  * firmware. This function gets the buffer associated with the iocbs
2963  * and calls the event handler for the ring. This function handles both
2964  * qring buffers and hbq buffers.
2965  * When the function returns 1 the caller can free the iocb object otherwise
2966  * upper layer functions will free the iocb objects.
2967  **/
2968 static int
2969 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2970 			    struct lpfc_iocbq *saveq)
2971 {
2972 	IOCB_t           * irsp;
2973 	WORD5            * w5p;
2974 	uint32_t           Rctl, Type;
2975 	struct lpfc_iocbq *iocbq;
2976 	struct lpfc_dmabuf *dmzbuf;
2977 
2978 	irsp = &(saveq->iocb);
2979 
2980 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
2981 		if (pring->lpfc_sli_rcv_async_status)
2982 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
2983 		else
2984 			lpfc_printf_log(phba,
2985 					KERN_WARNING,
2986 					LOG_SLI,
2987 					"0316 Ring %d handler: unexpected "
2988 					"ASYNC_STATUS iocb received evt_code "
2989 					"0x%x\n",
2990 					pring->ringno,
2991 					irsp->un.asyncstat.evt_code);
2992 		return 1;
2993 	}
2994 
2995 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
2996 		(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
2997 		if (irsp->ulpBdeCount > 0) {
2998 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2999 					irsp->un.ulpWord[3]);
3000 			lpfc_in_buf_free(phba, dmzbuf);
3001 		}
3002 
3003 		if (irsp->ulpBdeCount > 1) {
3004 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3005 					irsp->unsli3.sli3Words[3]);
3006 			lpfc_in_buf_free(phba, dmzbuf);
3007 		}
3008 
3009 		if (irsp->ulpBdeCount > 2) {
3010 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3011 				irsp->unsli3.sli3Words[7]);
3012 			lpfc_in_buf_free(phba, dmzbuf);
3013 		}
3014 
3015 		return 1;
3016 	}
3017 
3018 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3019 		if (irsp->ulpBdeCount != 0) {
3020 			saveq->context2 = lpfc_sli_get_buff(phba, pring,
3021 						irsp->un.ulpWord[3]);
3022 			if (!saveq->context2)
3023 				lpfc_printf_log(phba,
3024 					KERN_ERR,
3025 					LOG_SLI,
3026 					"0341 Ring %d Cannot find buffer for "
3027 					"an unsolicited iocb. tag 0x%x\n",
3028 					pring->ringno,
3029 					irsp->un.ulpWord[3]);
3030 		}
3031 		if (irsp->ulpBdeCount == 2) {
3032 			saveq->context3 = lpfc_sli_get_buff(phba, pring,
3033 						irsp->unsli3.sli3Words[7]);
3034 			if (!saveq->context3)
3035 				lpfc_printf_log(phba,
3036 					KERN_ERR,
3037 					LOG_SLI,
3038 					"0342 Ring %d Cannot find buffer for an"
3039 					" unsolicited iocb. tag 0x%x\n",
3040 					pring->ringno,
3041 					irsp->unsli3.sli3Words[7]);
3042 		}
3043 		list_for_each_entry(iocbq, &saveq->list, list) {
3044 			irsp = &(iocbq->iocb);
3045 			if (irsp->ulpBdeCount != 0) {
3046 				iocbq->context2 = lpfc_sli_get_buff(phba, pring,
3047 							irsp->un.ulpWord[3]);
3048 				if (!iocbq->context2)
3049 					lpfc_printf_log(phba,
3050 						KERN_ERR,
3051 						LOG_SLI,
3052 						"0343 Ring %d Cannot find "
3053 						"buffer for an unsolicited iocb"
3054 						". tag 0x%x\n", pring->ringno,
3055 						irsp->un.ulpWord[3]);
3056 			}
3057 			if (irsp->ulpBdeCount == 2) {
3058 				iocbq->context3 = lpfc_sli_get_buff(phba, pring,
3059 						irsp->unsli3.sli3Words[7]);
3060 				if (!iocbq->context3)
3061 					lpfc_printf_log(phba,
3062 						KERN_ERR,
3063 						LOG_SLI,
3064 						"0344 Ring %d Cannot find "
3065 						"buffer for an unsolicited "
3066 						"iocb. tag 0x%x\n",
3067 						pring->ringno,
3068 						irsp->unsli3.sli3Words[7]);
3069 			}
3070 		}
3071 	}
3072 	if (irsp->ulpBdeCount != 0 &&
3073 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3074 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3075 		int found = 0;
3076 
3077 		/* search continue save q for same XRI */
3078 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3079 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3080 				saveq->iocb.unsli3.rcvsli3.ox_id) {
3081 				list_add_tail(&saveq->list, &iocbq->list);
3082 				found = 1;
3083 				break;
3084 			}
3085 		}
3086 		if (!found)
3087 			list_add_tail(&saveq->clist,
3088 				      &pring->iocb_continue_saveq);
3089 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3090 			list_del_init(&iocbq->clist);
3091 			saveq = iocbq;
3092 			irsp = &(saveq->iocb);
3093 		} else
3094 			return 0;
3095 	}
3096 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3097 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3098 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3099 		Rctl = FC_RCTL_ELS_REQ;
3100 		Type = FC_TYPE_ELS;
3101 	} else {
3102 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3103 		Rctl = w5p->hcsw.Rctl;
3104 		Type = w5p->hcsw.Type;
3105 
3106 		/* Firmware Workaround */
3107 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3108 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3109 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3110 			Rctl = FC_RCTL_ELS_REQ;
3111 			Type = FC_TYPE_ELS;
3112 			w5p->hcsw.Rctl = Rctl;
3113 			w5p->hcsw.Type = Type;
3114 		}
3115 	}
3116 
3117 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3118 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3119 				"0313 Ring %d handler: unexpected Rctl x%x "
3120 				"Type x%x received\n",
3121 				pring->ringno, Rctl, Type);
3122 
3123 	return 1;
3124 }
3125 
3126 /**
3127  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3128  * @phba: Pointer to HBA context object.
3129  * @pring: Pointer to driver SLI ring object.
3130  * @prspiocb: Pointer to response iocb object.
3131  *
3132  * This function looks up the iocb_lookup table to get the command iocb
3133  * corresponding to the given response iocb using the iotag of the
3134  * response iocb. The driver calls this function with the hbalock held
3135  * for SLI3 ports or the ring lock held for SLI4 ports.
3136  * This function returns the command iocb object if it finds the command
3137  * iocb else returns NULL.
3138  **/
3139 static struct lpfc_iocbq *
3140 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3141 		      struct lpfc_sli_ring *pring,
3142 		      struct lpfc_iocbq *prspiocb)
3143 {
3144 	struct lpfc_iocbq *cmd_iocb = NULL;
3145 	uint16_t iotag;
3146 	spinlock_t *temp_lock = NULL;
3147 	unsigned long iflag = 0;
3148 
3149 	if (phba->sli_rev == LPFC_SLI_REV4)
3150 		temp_lock = &pring->ring_lock;
3151 	else
3152 		temp_lock = &phba->hbalock;
3153 
3154 	spin_lock_irqsave(temp_lock, iflag);
3155 	iotag = prspiocb->iocb.ulpIoTag;
3156 
3157 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3158 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3159 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3160 			/* remove from txcmpl queue list */
3161 			list_del_init(&cmd_iocb->list);
3162 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3163 			pring->txcmplq_cnt--;
3164 			spin_unlock_irqrestore(temp_lock, iflag);
3165 			return cmd_iocb;
3166 		}
3167 	}
3168 
3169 	spin_unlock_irqrestore(temp_lock, iflag);
3170 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3171 			"0317 iotag x%x is out of "
3172 			"range: max iotag x%x wd0 x%x\n",
3173 			iotag, phba->sli.last_iotag,
3174 			*(((uint32_t *) &prspiocb->iocb) + 7));
3175 	return NULL;
3176 }
3177 
3178 /**
3179  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3180  * @phba: Pointer to HBA context object.
3181  * @pring: Pointer to driver SLI ring object.
3182  * @iotag: IOCB tag.
3183  *
3184  * This function looks up the iocb_lookup table to get the command iocb
3185  * corresponding to the given iotag. The driver calls this function with
3186  * the ring lock held because this function is an SLI4 port only helper.
3187  * This function returns the command iocb object if it finds the command
3188  * iocb else returns NULL.
3189  **/
3190 static struct lpfc_iocbq *
3191 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3192 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3193 {
3194 	struct lpfc_iocbq *cmd_iocb = NULL;
3195 	spinlock_t *temp_lock = NULL;
3196 	unsigned long iflag = 0;
3197 
3198 	if (phba->sli_rev == LPFC_SLI_REV4)
3199 		temp_lock = &pring->ring_lock;
3200 	else
3201 		temp_lock = &phba->hbalock;
3202 
3203 	spin_lock_irqsave(temp_lock, iflag);
3204 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3205 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3206 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3207 			/* remove from txcmpl queue list */
3208 			list_del_init(&cmd_iocb->list);
3209 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3210 			pring->txcmplq_cnt--;
3211 			spin_unlock_irqrestore(temp_lock, iflag);
3212 			return cmd_iocb;
3213 		}
3214 	}
3215 
3216 	spin_unlock_irqrestore(temp_lock, iflag);
3217 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3218 			"0372 iotag x%x lookup error: max iotag (x%x) "
3219 			"iocb_flag x%x\n",
3220 			iotag, phba->sli.last_iotag,
3221 			cmd_iocb ? cmd_iocb->iocb_flag : 0xffff);
3222 	return NULL;
3223 }
3224 
3225 /**
3226  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3227  * @phba: Pointer to HBA context object.
3228  * @pring: Pointer to driver SLI ring object.
3229  * @saveq: Pointer to the response iocb to be processed.
3230  *
3231  * This function is called by the ring event handler for non-fcp
3232  * rings when there is a new response iocb in the response ring.
3233  * The caller is not required to hold any locks. This function
3234  * gets the command iocb associated with the response iocb and
3235  * calls the completion handler for the command iocb. If there
3236  * is no completion handler, the function will free the resources
3237  * associated with command iocb. If the response iocb is for
3238  * an already aborted command iocb, the status of the completion
3239  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3240  * This function always returns 1.
3241  **/
3242 static int
3243 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3244 			  struct lpfc_iocbq *saveq)
3245 {
3246 	struct lpfc_iocbq *cmdiocbp;
3247 	int rc = 1;
3248 	unsigned long iflag;
3249 
3250 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3251 	if (cmdiocbp) {
3252 		if (cmdiocbp->iocb_cmpl) {
3253 			/*
3254 			 * If an ELS command failed send an event to mgmt
3255 			 * application.
3256 			 */
3257 			if (saveq->iocb.ulpStatus &&
3258 			     (pring->ringno == LPFC_ELS_RING) &&
3259 			     (cmdiocbp->iocb.ulpCommand ==
3260 				CMD_ELS_REQUEST64_CR))
3261 				lpfc_send_els_failure_event(phba,
3262 					cmdiocbp, saveq);
3263 
3264 			/*
3265 			 * Post all ELS completions to the worker thread.
3266 			 * All other are passed to the completion callback.
3267 			 */
3268 			if (pring->ringno == LPFC_ELS_RING) {
3269 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3270 				    (cmdiocbp->iocb_flag &
3271 							LPFC_DRIVER_ABORTED)) {
3272 					spin_lock_irqsave(&phba->hbalock,
3273 							  iflag);
3274 					cmdiocbp->iocb_flag &=
3275 						~LPFC_DRIVER_ABORTED;
3276 					spin_unlock_irqrestore(&phba->hbalock,
3277 							       iflag);
3278 					saveq->iocb.ulpStatus =
3279 						IOSTAT_LOCAL_REJECT;
3280 					saveq->iocb.un.ulpWord[4] =
3281 						IOERR_SLI_ABORTED;
3282 
3283 					/* Firmware could still be in progress
3284 					 * of DMAing payload, so don't free data
3285 					 * buffer till after a hbeat.
3286 					 */
3287 					spin_lock_irqsave(&phba->hbalock,
3288 							  iflag);
3289 					saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
3290 					spin_unlock_irqrestore(&phba->hbalock,
3291 							       iflag);
3292 				}
3293 				if (phba->sli_rev == LPFC_SLI_REV4) {
3294 					if (saveq->iocb_flag &
3295 					    LPFC_EXCHANGE_BUSY) {
3296 						/* Set cmdiocb flag for the
3297 						 * exchange busy so sgl (xri)
3298 						 * will not be released until
3299 						 * the abort xri is received
3300 						 * from hba.
3301 						 */
3302 						spin_lock_irqsave(
3303 							&phba->hbalock, iflag);
3304 						cmdiocbp->iocb_flag |=
3305 							LPFC_EXCHANGE_BUSY;
3306 						spin_unlock_irqrestore(
3307 							&phba->hbalock, iflag);
3308 					}
3309 					if (cmdiocbp->iocb_flag &
3310 					    LPFC_DRIVER_ABORTED) {
3311 						/*
3312 						 * Clear LPFC_DRIVER_ABORTED
3313 						 * bit in case it was driver
3314 						 * initiated abort.
3315 						 */
3316 						spin_lock_irqsave(
3317 							&phba->hbalock, iflag);
3318 						cmdiocbp->iocb_flag &=
3319 							~LPFC_DRIVER_ABORTED;
3320 						spin_unlock_irqrestore(
3321 							&phba->hbalock, iflag);
3322 						cmdiocbp->iocb.ulpStatus =
3323 							IOSTAT_LOCAL_REJECT;
3324 						cmdiocbp->iocb.un.ulpWord[4] =
3325 							IOERR_ABORT_REQUESTED;
3326 						/*
3327 						 * For SLI4, irsiocb contains
3328 						 * NO_XRI in sli_xritag, it
3329 						 * shall not affect releasing
3330 						 * sgl (xri) process.
3331 						 */
3332 						saveq->iocb.ulpStatus =
3333 							IOSTAT_LOCAL_REJECT;
3334 						saveq->iocb.un.ulpWord[4] =
3335 							IOERR_SLI_ABORTED;
3336 						spin_lock_irqsave(
3337 							&phba->hbalock, iflag);
3338 						saveq->iocb_flag |=
3339 							LPFC_DELAY_MEM_FREE;
3340 						spin_unlock_irqrestore(
3341 							&phba->hbalock, iflag);
3342 					}
3343 				}
3344 			}
3345 			(cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
3346 		} else
3347 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3348 	} else {
3349 		/*
3350 		 * Unknown initiating command based on the response iotag.
3351 		 * This could be the case on the ELS ring because of
3352 		 * lpfc_els_abort().
3353 		 */
3354 		if (pring->ringno != LPFC_ELS_RING) {
3355 			/*
3356 			 * Ring <ringno> handler: unexpected completion IoTag
3357 			 * <IoTag>
3358 			 */
3359 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3360 					 "0322 Ring %d handler: "
3361 					 "unexpected completion IoTag x%x "
3362 					 "Data: x%x x%x x%x x%x\n",
3363 					 pring->ringno,
3364 					 saveq->iocb.ulpIoTag,
3365 					 saveq->iocb.ulpStatus,
3366 					 saveq->iocb.un.ulpWord[4],
3367 					 saveq->iocb.ulpCommand,
3368 					 saveq->iocb.ulpContext);
3369 		}
3370 	}
3371 
3372 	return rc;
3373 }
3374 
3375 /**
3376  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3377  * @phba: Pointer to HBA context object.
3378  * @pring: Pointer to driver SLI ring object.
3379  *
3380  * This function is called from the iocb ring event handlers when
3381  * put pointer is ahead of the get pointer for a ring. This function signal
3382  * an error attention condition to the worker thread and the worker
3383  * thread will transition the HBA to offline state.
3384  **/
3385 static void
3386 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3387 {
3388 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3389 	/*
3390 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3391 	 * rsp ring <portRspMax>
3392 	 */
3393 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3394 			"0312 Ring %d handler: portRspPut %d "
3395 			"is bigger than rsp ring %d\n",
3396 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3397 			pring->sli.sli3.numRiocb);
3398 
3399 	phba->link_state = LPFC_HBA_ERROR;
3400 
3401 	/*
3402 	 * All error attention handlers are posted to
3403 	 * worker thread
3404 	 */
3405 	phba->work_ha |= HA_ERATT;
3406 	phba->work_hs = HS_FFER3;
3407 
3408 	lpfc_worker_wake_up(phba);
3409 
3410 	return;
3411 }
3412 
3413 /**
3414  * lpfc_poll_eratt - Error attention polling timer timeout handler
3415  * @t: Context to fetch pointer to address of HBA context object from.
3416  *
3417  * This function is invoked by the Error Attention polling timer when the
3418  * timer times out. It will check the SLI Error Attention register for
3419  * possible attention events. If so, it will post an Error Attention event
3420  * and wake up worker thread to process it. Otherwise, it will set up the
3421  * Error Attention polling timer for the next poll.
3422  **/
3423 void lpfc_poll_eratt(struct timer_list *t)
3424 {
3425 	struct lpfc_hba *phba;
3426 	uint32_t eratt = 0;
3427 	uint64_t sli_intr, cnt;
3428 
3429 	phba = from_timer(phba, t, eratt_poll);
3430 
3431 	/* Here we will also keep track of interrupts per sec of the hba */
3432 	sli_intr = phba->sli.slistat.sli_intr;
3433 
3434 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3435 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3436 			sli_intr);
3437 	else
3438 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3439 
3440 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3441 	do_div(cnt, phba->eratt_poll_interval);
3442 	phba->sli.slistat.sli_ips = cnt;
3443 
3444 	phba->sli.slistat.sli_prev_intr = sli_intr;
3445 
3446 	/* Check chip HA register for error event */
3447 	eratt = lpfc_sli_check_eratt(phba);
3448 
3449 	if (eratt)
3450 		/* Tell the worker thread there is work to do */
3451 		lpfc_worker_wake_up(phba);
3452 	else
3453 		/* Restart the timer for next eratt poll */
3454 		mod_timer(&phba->eratt_poll,
3455 			  jiffies +
3456 			  msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3457 	return;
3458 }
3459 
3460 
3461 /**
3462  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3463  * @phba: Pointer to HBA context object.
3464  * @pring: Pointer to driver SLI ring object.
3465  * @mask: Host attention register mask for this ring.
3466  *
3467  * This function is called from the interrupt context when there is a ring
3468  * event for the fcp ring. The caller does not hold any lock.
3469  * The function processes each response iocb in the response ring until it
3470  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3471  * LE bit set. The function will call the completion handler of the command iocb
3472  * if the response iocb indicates a completion for a command iocb or it is
3473  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3474  * function if this is an unsolicited iocb.
3475  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3476  * to check it explicitly.
3477  */
3478 int
3479 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3480 				struct lpfc_sli_ring *pring, uint32_t mask)
3481 {
3482 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3483 	IOCB_t *irsp = NULL;
3484 	IOCB_t *entry = NULL;
3485 	struct lpfc_iocbq *cmdiocbq = NULL;
3486 	struct lpfc_iocbq rspiocbq;
3487 	uint32_t status;
3488 	uint32_t portRspPut, portRspMax;
3489 	int rc = 1;
3490 	lpfc_iocb_type type;
3491 	unsigned long iflag;
3492 	uint32_t rsp_cmpl = 0;
3493 
3494 	spin_lock_irqsave(&phba->hbalock, iflag);
3495 	pring->stats.iocb_event++;
3496 
3497 	/*
3498 	 * The next available response entry should never exceed the maximum
3499 	 * entries.  If it does, treat it as an adapter hardware error.
3500 	 */
3501 	portRspMax = pring->sli.sli3.numRiocb;
3502 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3503 	if (unlikely(portRspPut >= portRspMax)) {
3504 		lpfc_sli_rsp_pointers_error(phba, pring);
3505 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3506 		return 1;
3507 	}
3508 	if (phba->fcp_ring_in_use) {
3509 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3510 		return 1;
3511 	} else
3512 		phba->fcp_ring_in_use = 1;
3513 
3514 	rmb();
3515 	while (pring->sli.sli3.rspidx != portRspPut) {
3516 		/*
3517 		 * Fetch an entry off the ring and copy it into a local data
3518 		 * structure.  The copy involves a byte-swap since the
3519 		 * network byte order and pci byte orders are different.
3520 		 */
3521 		entry = lpfc_resp_iocb(phba, pring);
3522 		phba->last_completion_time = jiffies;
3523 
3524 		if (++pring->sli.sli3.rspidx >= portRspMax)
3525 			pring->sli.sli3.rspidx = 0;
3526 
3527 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3528 				      (uint32_t *) &rspiocbq.iocb,
3529 				      phba->iocb_rsp_size);
3530 		INIT_LIST_HEAD(&(rspiocbq.list));
3531 		irsp = &rspiocbq.iocb;
3532 
3533 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3534 		pring->stats.iocb_rsp++;
3535 		rsp_cmpl++;
3536 
3537 		if (unlikely(irsp->ulpStatus)) {
3538 			/*
3539 			 * If resource errors reported from HBA, reduce
3540 			 * queuedepths of the SCSI device.
3541 			 */
3542 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3543 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3544 			     IOERR_NO_RESOURCES)) {
3545 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3546 				phba->lpfc_rampdown_queue_depth(phba);
3547 				spin_lock_irqsave(&phba->hbalock, iflag);
3548 			}
3549 
3550 			/* Rsp ring <ringno> error: IOCB */
3551 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3552 					"0336 Rsp Ring %d error: IOCB Data: "
3553 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
3554 					pring->ringno,
3555 					irsp->un.ulpWord[0],
3556 					irsp->un.ulpWord[1],
3557 					irsp->un.ulpWord[2],
3558 					irsp->un.ulpWord[3],
3559 					irsp->un.ulpWord[4],
3560 					irsp->un.ulpWord[5],
3561 					*(uint32_t *)&irsp->un1,
3562 					*((uint32_t *)&irsp->un1 + 1));
3563 		}
3564 
3565 		switch (type) {
3566 		case LPFC_ABORT_IOCB:
3567 		case LPFC_SOL_IOCB:
3568 			/*
3569 			 * Idle exchange closed via ABTS from port.  No iocb
3570 			 * resources need to be recovered.
3571 			 */
3572 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3573 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3574 						"0333 IOCB cmd 0x%x"
3575 						" processed. Skipping"
3576 						" completion\n",
3577 						irsp->ulpCommand);
3578 				break;
3579 			}
3580 
3581 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3582 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3583 							 &rspiocbq);
3584 			spin_lock_irqsave(&phba->hbalock, iflag);
3585 			if (unlikely(!cmdiocbq))
3586 				break;
3587 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3588 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3589 			if (cmdiocbq->iocb_cmpl) {
3590 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3591 				(cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
3592 						      &rspiocbq);
3593 				spin_lock_irqsave(&phba->hbalock, iflag);
3594 			}
3595 			break;
3596 		case LPFC_UNSOL_IOCB:
3597 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3598 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
3599 			spin_lock_irqsave(&phba->hbalock, iflag);
3600 			break;
3601 		default:
3602 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3603 				char adaptermsg[LPFC_MAX_ADPTMSG];
3604 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3605 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
3606 				       MAX_MSG_DATA);
3607 				dev_warn(&((phba->pcidev)->dev),
3608 					 "lpfc%d: %s\n",
3609 					 phba->brd_no, adaptermsg);
3610 			} else {
3611 				/* Unknown IOCB command */
3612 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3613 						"0334 Unknown IOCB command "
3614 						"Data: x%x, x%x x%x x%x x%x\n",
3615 						type, irsp->ulpCommand,
3616 						irsp->ulpStatus,
3617 						irsp->ulpIoTag,
3618 						irsp->ulpContext);
3619 			}
3620 			break;
3621 		}
3622 
3623 		/*
3624 		 * The response IOCB has been processed.  Update the ring
3625 		 * pointer in SLIM.  If the port response put pointer has not
3626 		 * been updated, sync the pgp->rspPutInx and fetch the new port
3627 		 * response put pointer.
3628 		 */
3629 		writel(pring->sli.sli3.rspidx,
3630 			&phba->host_gp[pring->ringno].rspGetInx);
3631 
3632 		if (pring->sli.sli3.rspidx == portRspPut)
3633 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3634 	}
3635 
3636 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
3637 		pring->stats.iocb_rsp_full++;
3638 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3639 		writel(status, phba->CAregaddr);
3640 		readl(phba->CAregaddr);
3641 	}
3642 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3643 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3644 		pring->stats.iocb_cmd_empty++;
3645 
3646 		/* Force update of the local copy of cmdGetInx */
3647 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3648 		lpfc_sli_resume_iocb(phba, pring);
3649 
3650 		if ((pring->lpfc_sli_cmd_available))
3651 			(pring->lpfc_sli_cmd_available) (phba, pring);
3652 
3653 	}
3654 
3655 	phba->fcp_ring_in_use = 0;
3656 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3657 	return rc;
3658 }
3659 
3660 /**
3661  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
3662  * @phba: Pointer to HBA context object.
3663  * @pring: Pointer to driver SLI ring object.
3664  * @rspiocbp: Pointer to driver response IOCB object.
3665  *
3666  * This function is called from the worker thread when there is a slow-path
3667  * response IOCB to process. This function chains all the response iocbs until
3668  * seeing the iocb with the LE bit set. The function will call
3669  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
3670  * completion of a command iocb. The function will call the
3671  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
3672  * The function frees the resources or calls the completion handler if this
3673  * iocb is an abort completion. The function returns NULL when the response
3674  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
3675  * this function shall chain the iocb on to the iocb_continueq and return the
3676  * response iocb passed in.
3677  **/
3678 static struct lpfc_iocbq *
3679 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3680 			struct lpfc_iocbq *rspiocbp)
3681 {
3682 	struct lpfc_iocbq *saveq;
3683 	struct lpfc_iocbq *cmdiocbp;
3684 	struct lpfc_iocbq *next_iocb;
3685 	IOCB_t *irsp = NULL;
3686 	uint32_t free_saveq;
3687 	uint8_t iocb_cmd_type;
3688 	lpfc_iocb_type type;
3689 	unsigned long iflag;
3690 	int rc;
3691 
3692 	spin_lock_irqsave(&phba->hbalock, iflag);
3693 	/* First add the response iocb to the countinueq list */
3694 	list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
3695 	pring->iocb_continueq_cnt++;
3696 
3697 	/* Now, determine whether the list is completed for processing */
3698 	irsp = &rspiocbp->iocb;
3699 	if (irsp->ulpLe) {
3700 		/*
3701 		 * By default, the driver expects to free all resources
3702 		 * associated with this iocb completion.
3703 		 */
3704 		free_saveq = 1;
3705 		saveq = list_get_first(&pring->iocb_continueq,
3706 				       struct lpfc_iocbq, list);
3707 		irsp = &(saveq->iocb);
3708 		list_del_init(&pring->iocb_continueq);
3709 		pring->iocb_continueq_cnt = 0;
3710 
3711 		pring->stats.iocb_rsp++;
3712 
3713 		/*
3714 		 * If resource errors reported from HBA, reduce
3715 		 * queuedepths of the SCSI device.
3716 		 */
3717 		if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3718 		    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3719 		     IOERR_NO_RESOURCES)) {
3720 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3721 			phba->lpfc_rampdown_queue_depth(phba);
3722 			spin_lock_irqsave(&phba->hbalock, iflag);
3723 		}
3724 
3725 		if (irsp->ulpStatus) {
3726 			/* Rsp ring <ringno> error: IOCB */
3727 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3728 					"0328 Rsp Ring %d error: "
3729 					"IOCB Data: "
3730 					"x%x x%x x%x x%x "
3731 					"x%x x%x x%x x%x "
3732 					"x%x x%x x%x x%x "
3733 					"x%x x%x x%x x%x\n",
3734 					pring->ringno,
3735 					irsp->un.ulpWord[0],
3736 					irsp->un.ulpWord[1],
3737 					irsp->un.ulpWord[2],
3738 					irsp->un.ulpWord[3],
3739 					irsp->un.ulpWord[4],
3740 					irsp->un.ulpWord[5],
3741 					*(((uint32_t *) irsp) + 6),
3742 					*(((uint32_t *) irsp) + 7),
3743 					*(((uint32_t *) irsp) + 8),
3744 					*(((uint32_t *) irsp) + 9),
3745 					*(((uint32_t *) irsp) + 10),
3746 					*(((uint32_t *) irsp) + 11),
3747 					*(((uint32_t *) irsp) + 12),
3748 					*(((uint32_t *) irsp) + 13),
3749 					*(((uint32_t *) irsp) + 14),
3750 					*(((uint32_t *) irsp) + 15));
3751 		}
3752 
3753 		/*
3754 		 * Fetch the IOCB command type and call the correct completion
3755 		 * routine. Solicited and Unsolicited IOCBs on the ELS ring
3756 		 * get freed back to the lpfc_iocb_list by the discovery
3757 		 * kernel thread.
3758 		 */
3759 		iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
3760 		type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
3761 		switch (type) {
3762 		case LPFC_SOL_IOCB:
3763 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3764 			rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
3765 			spin_lock_irqsave(&phba->hbalock, iflag);
3766 			break;
3767 
3768 		case LPFC_UNSOL_IOCB:
3769 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3770 			rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
3771 			spin_lock_irqsave(&phba->hbalock, iflag);
3772 			if (!rc)
3773 				free_saveq = 0;
3774 			break;
3775 
3776 		case LPFC_ABORT_IOCB:
3777 			cmdiocbp = NULL;
3778 			if (irsp->ulpCommand != CMD_XRI_ABORTED_CX) {
3779 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3780 				cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
3781 								 saveq);
3782 				spin_lock_irqsave(&phba->hbalock, iflag);
3783 			}
3784 			if (cmdiocbp) {
3785 				/* Call the specified completion routine */
3786 				if (cmdiocbp->iocb_cmpl) {
3787 					spin_unlock_irqrestore(&phba->hbalock,
3788 							       iflag);
3789 					(cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
3790 							      saveq);
3791 					spin_lock_irqsave(&phba->hbalock,
3792 							  iflag);
3793 				} else
3794 					__lpfc_sli_release_iocbq(phba,
3795 								 cmdiocbp);
3796 			}
3797 			break;
3798 
3799 		case LPFC_UNKNOWN_IOCB:
3800 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3801 				char adaptermsg[LPFC_MAX_ADPTMSG];
3802 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3803 				memcpy(&adaptermsg[0], (uint8_t *)irsp,
3804 				       MAX_MSG_DATA);
3805 				dev_warn(&((phba->pcidev)->dev),
3806 					 "lpfc%d: %s\n",
3807 					 phba->brd_no, adaptermsg);
3808 			} else {
3809 				/* Unknown IOCB command */
3810 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3811 						"0335 Unknown IOCB "
3812 						"command Data: x%x "
3813 						"x%x x%x x%x\n",
3814 						irsp->ulpCommand,
3815 						irsp->ulpStatus,
3816 						irsp->ulpIoTag,
3817 						irsp->ulpContext);
3818 			}
3819 			break;
3820 		}
3821 
3822 		if (free_saveq) {
3823 			list_for_each_entry_safe(rspiocbp, next_iocb,
3824 						 &saveq->list, list) {
3825 				list_del_init(&rspiocbp->list);
3826 				__lpfc_sli_release_iocbq(phba, rspiocbp);
3827 			}
3828 			__lpfc_sli_release_iocbq(phba, saveq);
3829 		}
3830 		rspiocbp = NULL;
3831 	}
3832 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3833 	return rspiocbp;
3834 }
3835 
3836 /**
3837  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
3838  * @phba: Pointer to HBA context object.
3839  * @pring: Pointer to driver SLI ring object.
3840  * @mask: Host attention register mask for this ring.
3841  *
3842  * This routine wraps the actual slow_ring event process routine from the
3843  * API jump table function pointer from the lpfc_hba struct.
3844  **/
3845 void
3846 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
3847 				struct lpfc_sli_ring *pring, uint32_t mask)
3848 {
3849 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
3850 }
3851 
3852 /**
3853  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
3854  * @phba: Pointer to HBA context object.
3855  * @pring: Pointer to driver SLI ring object.
3856  * @mask: Host attention register mask for this ring.
3857  *
3858  * This function is called from the worker thread when there is a ring event
3859  * for non-fcp rings. The caller does not hold any lock. The function will
3860  * remove each response iocb in the response ring and calls the handle
3861  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3862  **/
3863 static void
3864 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
3865 				   struct lpfc_sli_ring *pring, uint32_t mask)
3866 {
3867 	struct lpfc_pgp *pgp;
3868 	IOCB_t *entry;
3869 	IOCB_t *irsp = NULL;
3870 	struct lpfc_iocbq *rspiocbp = NULL;
3871 	uint32_t portRspPut, portRspMax;
3872 	unsigned long iflag;
3873 	uint32_t status;
3874 
3875 	pgp = &phba->port_gp[pring->ringno];
3876 	spin_lock_irqsave(&phba->hbalock, iflag);
3877 	pring->stats.iocb_event++;
3878 
3879 	/*
3880 	 * The next available response entry should never exceed the maximum
3881 	 * entries.  If it does, treat it as an adapter hardware error.
3882 	 */
3883 	portRspMax = pring->sli.sli3.numRiocb;
3884 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3885 	if (portRspPut >= portRspMax) {
3886 		/*
3887 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3888 		 * rsp ring <portRspMax>
3889 		 */
3890 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3891 				"0303 Ring %d handler: portRspPut %d "
3892 				"is bigger than rsp ring %d\n",
3893 				pring->ringno, portRspPut, portRspMax);
3894 
3895 		phba->link_state = LPFC_HBA_ERROR;
3896 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3897 
3898 		phba->work_hs = HS_FFER3;
3899 		lpfc_handle_eratt(phba);
3900 
3901 		return;
3902 	}
3903 
3904 	rmb();
3905 	while (pring->sli.sli3.rspidx != portRspPut) {
3906 		/*
3907 		 * Build a completion list and call the appropriate handler.
3908 		 * The process is to get the next available response iocb, get
3909 		 * a free iocb from the list, copy the response data into the
3910 		 * free iocb, insert to the continuation list, and update the
3911 		 * next response index to slim.  This process makes response
3912 		 * iocb's in the ring available to DMA as fast as possible but
3913 		 * pays a penalty for a copy operation.  Since the iocb is
3914 		 * only 32 bytes, this penalty is considered small relative to
3915 		 * the PCI reads for register values and a slim write.  When
3916 		 * the ulpLe field is set, the entire Command has been
3917 		 * received.
3918 		 */
3919 		entry = lpfc_resp_iocb(phba, pring);
3920 
3921 		phba->last_completion_time = jiffies;
3922 		rspiocbp = __lpfc_sli_get_iocbq(phba);
3923 		if (rspiocbp == NULL) {
3924 			printk(KERN_ERR "%s: out of buffers! Failing "
3925 			       "completion.\n", __func__);
3926 			break;
3927 		}
3928 
3929 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
3930 				      phba->iocb_rsp_size);
3931 		irsp = &rspiocbp->iocb;
3932 
3933 		if (++pring->sli.sli3.rspidx >= portRspMax)
3934 			pring->sli.sli3.rspidx = 0;
3935 
3936 		if (pring->ringno == LPFC_ELS_RING) {
3937 			lpfc_debugfs_slow_ring_trc(phba,
3938 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
3939 				*(((uint32_t *) irsp) + 4),
3940 				*(((uint32_t *) irsp) + 6),
3941 				*(((uint32_t *) irsp) + 7));
3942 		}
3943 
3944 		writel(pring->sli.sli3.rspidx,
3945 			&phba->host_gp[pring->ringno].rspGetInx);
3946 
3947 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3948 		/* Handle the response IOCB */
3949 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
3950 		spin_lock_irqsave(&phba->hbalock, iflag);
3951 
3952 		/*
3953 		 * If the port response put pointer has not been updated, sync
3954 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
3955 		 * response put pointer.
3956 		 */
3957 		if (pring->sli.sli3.rspidx == portRspPut) {
3958 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3959 		}
3960 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
3961 
3962 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
3963 		/* At least one response entry has been freed */
3964 		pring->stats.iocb_rsp_full++;
3965 		/* SET RxRE_RSP in Chip Att register */
3966 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3967 		writel(status, phba->CAregaddr);
3968 		readl(phba->CAregaddr); /* flush */
3969 	}
3970 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3971 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3972 		pring->stats.iocb_cmd_empty++;
3973 
3974 		/* Force update of the local copy of cmdGetInx */
3975 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3976 		lpfc_sli_resume_iocb(phba, pring);
3977 
3978 		if ((pring->lpfc_sli_cmd_available))
3979 			(pring->lpfc_sli_cmd_available) (phba, pring);
3980 
3981 	}
3982 
3983 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3984 	return;
3985 }
3986 
3987 /**
3988  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
3989  * @phba: Pointer to HBA context object.
3990  * @pring: Pointer to driver SLI ring object.
3991  * @mask: Host attention register mask for this ring.
3992  *
3993  * This function is called from the worker thread when there is a pending
3994  * ELS response iocb on the driver internal slow-path response iocb worker
3995  * queue. The caller does not hold any lock. The function will remove each
3996  * response iocb from the response worker queue and calls the handle
3997  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3998  **/
3999 static void
4000 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4001 				   struct lpfc_sli_ring *pring, uint32_t mask)
4002 {
4003 	struct lpfc_iocbq *irspiocbq;
4004 	struct hbq_dmabuf *dmabuf;
4005 	struct lpfc_cq_event *cq_event;
4006 	unsigned long iflag;
4007 	int count = 0;
4008 
4009 	spin_lock_irqsave(&phba->hbalock, iflag);
4010 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
4011 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4012 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4013 		/* Get the response iocb from the head of work queue */
4014 		spin_lock_irqsave(&phba->hbalock, iflag);
4015 		list_remove_head(&phba->sli4_hba.sp_queue_event,
4016 				 cq_event, struct lpfc_cq_event, list);
4017 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4018 
4019 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4020 		case CQE_CODE_COMPL_WQE:
4021 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4022 						 cq_event);
4023 			/* Translate ELS WCQE to response IOCBQ */
4024 			irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
4025 								   irspiocbq);
4026 			if (irspiocbq)
4027 				lpfc_sli_sp_handle_rspiocb(phba, pring,
4028 							   irspiocbq);
4029 			count++;
4030 			break;
4031 		case CQE_CODE_RECEIVE:
4032 		case CQE_CODE_RECEIVE_V1:
4033 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
4034 					      cq_event);
4035 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
4036 			count++;
4037 			break;
4038 		default:
4039 			break;
4040 		}
4041 
4042 		/* Limit the number of events to 64 to avoid soft lockups */
4043 		if (count == 64)
4044 			break;
4045 	}
4046 }
4047 
4048 /**
4049  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4050  * @phba: Pointer to HBA context object.
4051  * @pring: Pointer to driver SLI ring object.
4052  *
4053  * This function aborts all iocbs in the given ring and frees all the iocb
4054  * objects in txq. This function issues an abort iocb for all the iocb commands
4055  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4056  * the return of this function. The caller is not required to hold any locks.
4057  **/
4058 void
4059 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4060 {
4061 	LIST_HEAD(completions);
4062 	struct lpfc_iocbq *iocb, *next_iocb;
4063 
4064 	if (pring->ringno == LPFC_ELS_RING) {
4065 		lpfc_fabric_abort_hba(phba);
4066 	}
4067 
4068 	/* Error everything on txq and txcmplq
4069 	 * First do the txq.
4070 	 */
4071 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4072 		spin_lock_irq(&pring->ring_lock);
4073 		list_splice_init(&pring->txq, &completions);
4074 		pring->txq_cnt = 0;
4075 		spin_unlock_irq(&pring->ring_lock);
4076 
4077 		spin_lock_irq(&phba->hbalock);
4078 		/* Next issue ABTS for everything on the txcmplq */
4079 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4080 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
4081 		spin_unlock_irq(&phba->hbalock);
4082 	} else {
4083 		spin_lock_irq(&phba->hbalock);
4084 		list_splice_init(&pring->txq, &completions);
4085 		pring->txq_cnt = 0;
4086 
4087 		/* Next issue ABTS for everything on the txcmplq */
4088 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4089 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
4090 		spin_unlock_irq(&phba->hbalock);
4091 	}
4092 
4093 	/* Cancel all the IOCBs from the completions list */
4094 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
4095 			      IOERR_SLI_ABORTED);
4096 }
4097 
4098 /**
4099  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4100  * @phba: Pointer to HBA context object.
4101  *
4102  * This function aborts all iocbs in FCP rings and frees all the iocb
4103  * objects in txq. This function issues an abort iocb for all the iocb commands
4104  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4105  * the return of this function. The caller is not required to hold any locks.
4106  **/
4107 void
4108 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4109 {
4110 	struct lpfc_sli *psli = &phba->sli;
4111 	struct lpfc_sli_ring  *pring;
4112 	uint32_t i;
4113 
4114 	/* Look on all the FCP Rings for the iotag */
4115 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4116 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4117 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4118 			lpfc_sli_abort_iocb_ring(phba, pring);
4119 		}
4120 	} else {
4121 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4122 		lpfc_sli_abort_iocb_ring(phba, pring);
4123 	}
4124 }
4125 
4126 /**
4127  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4128  * @phba: Pointer to HBA context object.
4129  *
4130  * This function flushes all iocbs in the IO ring and frees all the iocb
4131  * objects in txq and txcmplq. This function will not issue abort iocbs
4132  * for all the iocb commands in txcmplq, they will just be returned with
4133  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4134  * slot has been permanently disabled.
4135  **/
4136 void
4137 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4138 {
4139 	LIST_HEAD(txq);
4140 	LIST_HEAD(txcmplq);
4141 	struct lpfc_sli *psli = &phba->sli;
4142 	struct lpfc_sli_ring  *pring;
4143 	uint32_t i;
4144 	struct lpfc_iocbq *piocb, *next_iocb;
4145 
4146 	spin_lock_irq(&phba->hbalock);
4147 	if (phba->hba_flag & HBA_IOQ_FLUSH ||
4148 	    !phba->sli4_hba.hdwq) {
4149 		spin_unlock_irq(&phba->hbalock);
4150 		return;
4151 	}
4152 	/* Indicate the I/O queues are flushed */
4153 	phba->hba_flag |= HBA_IOQ_FLUSH;
4154 	spin_unlock_irq(&phba->hbalock);
4155 
4156 	/* Look on all the FCP Rings for the iotag */
4157 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4158 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4159 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4160 
4161 			spin_lock_irq(&pring->ring_lock);
4162 			/* Retrieve everything on txq */
4163 			list_splice_init(&pring->txq, &txq);
4164 			list_for_each_entry_safe(piocb, next_iocb,
4165 						 &pring->txcmplq, list)
4166 				piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4167 			/* Retrieve everything on the txcmplq */
4168 			list_splice_init(&pring->txcmplq, &txcmplq);
4169 			pring->txq_cnt = 0;
4170 			pring->txcmplq_cnt = 0;
4171 			spin_unlock_irq(&pring->ring_lock);
4172 
4173 			/* Flush the txq */
4174 			lpfc_sli_cancel_iocbs(phba, &txq,
4175 					      IOSTAT_LOCAL_REJECT,
4176 					      IOERR_SLI_DOWN);
4177 			/* Flush the txcmpq */
4178 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4179 					      IOSTAT_LOCAL_REJECT,
4180 					      IOERR_SLI_DOWN);
4181 		}
4182 	} else {
4183 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4184 
4185 		spin_lock_irq(&phba->hbalock);
4186 		/* Retrieve everything on txq */
4187 		list_splice_init(&pring->txq, &txq);
4188 		list_for_each_entry_safe(piocb, next_iocb,
4189 					 &pring->txcmplq, list)
4190 			piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4191 		/* Retrieve everything on the txcmplq */
4192 		list_splice_init(&pring->txcmplq, &txcmplq);
4193 		pring->txq_cnt = 0;
4194 		pring->txcmplq_cnt = 0;
4195 		spin_unlock_irq(&phba->hbalock);
4196 
4197 		/* Flush the txq */
4198 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4199 				      IOERR_SLI_DOWN);
4200 		/* Flush the txcmpq */
4201 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4202 				      IOERR_SLI_DOWN);
4203 	}
4204 }
4205 
4206 /**
4207  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4208  * @phba: Pointer to HBA context object.
4209  * @mask: Bit mask to be checked.
4210  *
4211  * This function reads the host status register and compares
4212  * with the provided bit mask to check if HBA completed
4213  * the restart. This function will wait in a loop for the
4214  * HBA to complete restart. If the HBA does not restart within
4215  * 15 iterations, the function will reset the HBA again. The
4216  * function returns 1 when HBA fail to restart otherwise returns
4217  * zero.
4218  **/
4219 static int
4220 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4221 {
4222 	uint32_t status;
4223 	int i = 0;
4224 	int retval = 0;
4225 
4226 	/* Read the HBA Host Status Register */
4227 	if (lpfc_readl(phba->HSregaddr, &status))
4228 		return 1;
4229 
4230 	/*
4231 	 * Check status register every 100ms for 5 retries, then every
4232 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4233 	 * every 2.5 sec for 4.
4234 	 * Break our of the loop if errors occurred during init.
4235 	 */
4236 	while (((status & mask) != mask) &&
4237 	       !(status & HS_FFERM) &&
4238 	       i++ < 20) {
4239 
4240 		if (i <= 5)
4241 			msleep(10);
4242 		else if (i <= 10)
4243 			msleep(500);
4244 		else
4245 			msleep(2500);
4246 
4247 		if (i == 15) {
4248 				/* Do post */
4249 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4250 			lpfc_sli_brdrestart(phba);
4251 		}
4252 		/* Read the HBA Host Status Register */
4253 		if (lpfc_readl(phba->HSregaddr, &status)) {
4254 			retval = 1;
4255 			break;
4256 		}
4257 	}
4258 
4259 	/* Check to see if any errors occurred during init */
4260 	if ((status & HS_FFERM) || (i >= 20)) {
4261 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4262 				"2751 Adapter failed to restart, "
4263 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4264 				status,
4265 				readl(phba->MBslimaddr + 0xa8),
4266 				readl(phba->MBslimaddr + 0xac));
4267 		phba->link_state = LPFC_HBA_ERROR;
4268 		retval = 1;
4269 	}
4270 
4271 	return retval;
4272 }
4273 
4274 /**
4275  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4276  * @phba: Pointer to HBA context object.
4277  * @mask: Bit mask to be checked.
4278  *
4279  * This function checks the host status register to check if HBA is
4280  * ready. This function will wait in a loop for the HBA to be ready
4281  * If the HBA is not ready , the function will will reset the HBA PCI
4282  * function again. The function returns 1 when HBA fail to be ready
4283  * otherwise returns zero.
4284  **/
4285 static int
4286 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4287 {
4288 	uint32_t status;
4289 	int retval = 0;
4290 
4291 	/* Read the HBA Host Status Register */
4292 	status = lpfc_sli4_post_status_check(phba);
4293 
4294 	if (status) {
4295 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4296 		lpfc_sli_brdrestart(phba);
4297 		status = lpfc_sli4_post_status_check(phba);
4298 	}
4299 
4300 	/* Check to see if any errors occurred during init */
4301 	if (status) {
4302 		phba->link_state = LPFC_HBA_ERROR;
4303 		retval = 1;
4304 	} else
4305 		phba->sli4_hba.intr_enable = 0;
4306 
4307 	return retval;
4308 }
4309 
4310 /**
4311  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4312  * @phba: Pointer to HBA context object.
4313  * @mask: Bit mask to be checked.
4314  *
4315  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4316  * from the API jump table function pointer from the lpfc_hba struct.
4317  **/
4318 int
4319 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4320 {
4321 	return phba->lpfc_sli_brdready(phba, mask);
4322 }
4323 
4324 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4325 
4326 /**
4327  * lpfc_reset_barrier - Make HBA ready for HBA reset
4328  * @phba: Pointer to HBA context object.
4329  *
4330  * This function is called before resetting an HBA. This function is called
4331  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4332  **/
4333 void lpfc_reset_barrier(struct lpfc_hba *phba)
4334 {
4335 	uint32_t __iomem *resp_buf;
4336 	uint32_t __iomem *mbox_buf;
4337 	volatile uint32_t mbox;
4338 	uint32_t hc_copy, ha_copy, resp_data;
4339 	int  i;
4340 	uint8_t hdrtype;
4341 
4342 	lockdep_assert_held(&phba->hbalock);
4343 
4344 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4345 	if (hdrtype != 0x80 ||
4346 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4347 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4348 		return;
4349 
4350 	/*
4351 	 * Tell the other part of the chip to suspend temporarily all
4352 	 * its DMA activity.
4353 	 */
4354 	resp_buf = phba->MBslimaddr;
4355 
4356 	/* Disable the error attention */
4357 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4358 		return;
4359 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4360 	readl(phba->HCregaddr); /* flush */
4361 	phba->link_flag |= LS_IGNORE_ERATT;
4362 
4363 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4364 		return;
4365 	if (ha_copy & HA_ERATT) {
4366 		/* Clear Chip error bit */
4367 		writel(HA_ERATT, phba->HAregaddr);
4368 		phba->pport->stopped = 1;
4369 	}
4370 
4371 	mbox = 0;
4372 	((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
4373 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
4374 
4375 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4376 	mbox_buf = phba->MBslimaddr;
4377 	writel(mbox, mbox_buf);
4378 
4379 	for (i = 0; i < 50; i++) {
4380 		if (lpfc_readl((resp_buf + 1), &resp_data))
4381 			return;
4382 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4383 			mdelay(1);
4384 		else
4385 			break;
4386 	}
4387 	resp_data = 0;
4388 	if (lpfc_readl((resp_buf + 1), &resp_data))
4389 		return;
4390 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4391 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4392 		    phba->pport->stopped)
4393 			goto restore_hc;
4394 		else
4395 			goto clear_errat;
4396 	}
4397 
4398 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
4399 	resp_data = 0;
4400 	for (i = 0; i < 500; i++) {
4401 		if (lpfc_readl(resp_buf, &resp_data))
4402 			return;
4403 		if (resp_data != mbox)
4404 			mdelay(1);
4405 		else
4406 			break;
4407 	}
4408 
4409 clear_errat:
4410 
4411 	while (++i < 500) {
4412 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4413 			return;
4414 		if (!(ha_copy & HA_ERATT))
4415 			mdelay(1);
4416 		else
4417 			break;
4418 	}
4419 
4420 	if (readl(phba->HAregaddr) & HA_ERATT) {
4421 		writel(HA_ERATT, phba->HAregaddr);
4422 		phba->pport->stopped = 1;
4423 	}
4424 
4425 restore_hc:
4426 	phba->link_flag &= ~LS_IGNORE_ERATT;
4427 	writel(hc_copy, phba->HCregaddr);
4428 	readl(phba->HCregaddr); /* flush */
4429 }
4430 
4431 /**
4432  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4433  * @phba: Pointer to HBA context object.
4434  *
4435  * This function issues a kill_board mailbox command and waits for
4436  * the error attention interrupt. This function is called for stopping
4437  * the firmware processing. The caller is not required to hold any
4438  * locks. This function calls lpfc_hba_down_post function to free
4439  * any pending commands after the kill. The function will return 1 when it
4440  * fails to kill the board else will return 0.
4441  **/
4442 int
4443 lpfc_sli_brdkill(struct lpfc_hba *phba)
4444 {
4445 	struct lpfc_sli *psli;
4446 	LPFC_MBOXQ_t *pmb;
4447 	uint32_t status;
4448 	uint32_t ha_copy;
4449 	int retval;
4450 	int i = 0;
4451 
4452 	psli = &phba->sli;
4453 
4454 	/* Kill HBA */
4455 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4456 			"0329 Kill HBA Data: x%x x%x\n",
4457 			phba->pport->port_state, psli->sli_flag);
4458 
4459 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4460 	if (!pmb)
4461 		return 1;
4462 
4463 	/* Disable the error attention */
4464 	spin_lock_irq(&phba->hbalock);
4465 	if (lpfc_readl(phba->HCregaddr, &status)) {
4466 		spin_unlock_irq(&phba->hbalock);
4467 		mempool_free(pmb, phba->mbox_mem_pool);
4468 		return 1;
4469 	}
4470 	status &= ~HC_ERINT_ENA;
4471 	writel(status, phba->HCregaddr);
4472 	readl(phba->HCregaddr); /* flush */
4473 	phba->link_flag |= LS_IGNORE_ERATT;
4474 	spin_unlock_irq(&phba->hbalock);
4475 
4476 	lpfc_kill_board(phba, pmb);
4477 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4478 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4479 
4480 	if (retval != MBX_SUCCESS) {
4481 		if (retval != MBX_BUSY)
4482 			mempool_free(pmb, phba->mbox_mem_pool);
4483 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4484 				"2752 KILL_BOARD command failed retval %d\n",
4485 				retval);
4486 		spin_lock_irq(&phba->hbalock);
4487 		phba->link_flag &= ~LS_IGNORE_ERATT;
4488 		spin_unlock_irq(&phba->hbalock);
4489 		return 1;
4490 	}
4491 
4492 	spin_lock_irq(&phba->hbalock);
4493 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
4494 	spin_unlock_irq(&phba->hbalock);
4495 
4496 	mempool_free(pmb, phba->mbox_mem_pool);
4497 
4498 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
4499 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
4500 	 * 3 seconds we still set HBA_ERROR state because the status of the
4501 	 * board is now undefined.
4502 	 */
4503 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4504 		return 1;
4505 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
4506 		mdelay(100);
4507 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4508 			return 1;
4509 	}
4510 
4511 	del_timer_sync(&psli->mbox_tmo);
4512 	if (ha_copy & HA_ERATT) {
4513 		writel(HA_ERATT, phba->HAregaddr);
4514 		phba->pport->stopped = 1;
4515 	}
4516 	spin_lock_irq(&phba->hbalock);
4517 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4518 	psli->mbox_active = NULL;
4519 	phba->link_flag &= ~LS_IGNORE_ERATT;
4520 	spin_unlock_irq(&phba->hbalock);
4521 
4522 	lpfc_hba_down_post(phba);
4523 	phba->link_state = LPFC_HBA_ERROR;
4524 
4525 	return ha_copy & HA_ERATT ? 0 : 1;
4526 }
4527 
4528 /**
4529  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
4530  * @phba: Pointer to HBA context object.
4531  *
4532  * This function resets the HBA by writing HC_INITFF to the control
4533  * register. After the HBA resets, this function resets all the iocb ring
4534  * indices. This function disables PCI layer parity checking during
4535  * the reset.
4536  * This function returns 0 always.
4537  * The caller is not required to hold any locks.
4538  **/
4539 int
4540 lpfc_sli_brdreset(struct lpfc_hba *phba)
4541 {
4542 	struct lpfc_sli *psli;
4543 	struct lpfc_sli_ring *pring;
4544 	uint16_t cfg_value;
4545 	int i;
4546 
4547 	psli = &phba->sli;
4548 
4549 	/* Reset HBA */
4550 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4551 			"0325 Reset HBA Data: x%x x%x\n",
4552 			(phba->pport) ? phba->pport->port_state : 0,
4553 			psli->sli_flag);
4554 
4555 	/* perform board reset */
4556 	phba->fc_eventTag = 0;
4557 	phba->link_events = 0;
4558 	if (phba->pport) {
4559 		phba->pport->fc_myDID = 0;
4560 		phba->pport->fc_prevDID = 0;
4561 	}
4562 
4563 	/* Turn off parity checking and serr during the physical reset */
4564 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
4565 		return -EIO;
4566 
4567 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
4568 			      (cfg_value &
4569 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4570 
4571 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4572 
4573 	/* Now toggle INITFF bit in the Host Control Register */
4574 	writel(HC_INITFF, phba->HCregaddr);
4575 	mdelay(1);
4576 	readl(phba->HCregaddr); /* flush */
4577 	writel(0, phba->HCregaddr);
4578 	readl(phba->HCregaddr); /* flush */
4579 
4580 	/* Restore PCI cmd register */
4581 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4582 
4583 	/* Initialize relevant SLI info */
4584 	for (i = 0; i < psli->num_rings; i++) {
4585 		pring = &psli->sli3_ring[i];
4586 		pring->flag = 0;
4587 		pring->sli.sli3.rspidx = 0;
4588 		pring->sli.sli3.next_cmdidx  = 0;
4589 		pring->sli.sli3.local_getidx = 0;
4590 		pring->sli.sli3.cmdidx = 0;
4591 		pring->missbufcnt = 0;
4592 	}
4593 
4594 	phba->link_state = LPFC_WARM_START;
4595 	return 0;
4596 }
4597 
4598 /**
4599  * lpfc_sli4_brdreset - Reset a sli-4 HBA
4600  * @phba: Pointer to HBA context object.
4601  *
4602  * This function resets a SLI4 HBA. This function disables PCI layer parity
4603  * checking during resets the device. The caller is not required to hold
4604  * any locks.
4605  *
4606  * This function returns 0 on success else returns negative error code.
4607  **/
4608 int
4609 lpfc_sli4_brdreset(struct lpfc_hba *phba)
4610 {
4611 	struct lpfc_sli *psli = &phba->sli;
4612 	uint16_t cfg_value;
4613 	int rc = 0;
4614 
4615 	/* Reset HBA */
4616 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4617 			"0295 Reset HBA Data: x%x x%x x%x\n",
4618 			phba->pport->port_state, psli->sli_flag,
4619 			phba->hba_flag);
4620 
4621 	/* perform board reset */
4622 	phba->fc_eventTag = 0;
4623 	phba->link_events = 0;
4624 	phba->pport->fc_myDID = 0;
4625 	phba->pport->fc_prevDID = 0;
4626 
4627 	spin_lock_irq(&phba->hbalock);
4628 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
4629 	phba->fcf.fcf_flag = 0;
4630 	spin_unlock_irq(&phba->hbalock);
4631 
4632 	/* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
4633 	if (phba->hba_flag & HBA_FW_DUMP_OP) {
4634 		phba->hba_flag &= ~HBA_FW_DUMP_OP;
4635 		return rc;
4636 	}
4637 
4638 	/* Now physically reset the device */
4639 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4640 			"0389 Performing PCI function reset!\n");
4641 
4642 	/* Turn off parity checking and serr during the physical reset */
4643 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
4644 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4645 				"3205 PCI read Config failed\n");
4646 		return -EIO;
4647 	}
4648 
4649 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
4650 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4651 
4652 	/* Perform FCoE PCI function reset before freeing queue memory */
4653 	rc = lpfc_pci_function_reset(phba);
4654 
4655 	/* Restore PCI cmd register */
4656 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4657 
4658 	return rc;
4659 }
4660 
4661 /**
4662  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
4663  * @phba: Pointer to HBA context object.
4664  *
4665  * This function is called in the SLI initialization code path to
4666  * restart the HBA. The caller is not required to hold any lock.
4667  * This function writes MBX_RESTART mailbox command to the SLIM and
4668  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
4669  * function to free any pending commands. The function enables
4670  * POST only during the first initialization. The function returns zero.
4671  * The function does not guarantee completion of MBX_RESTART mailbox
4672  * command before the return of this function.
4673  **/
4674 static int
4675 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
4676 {
4677 	MAILBOX_t *mb;
4678 	struct lpfc_sli *psli;
4679 	volatile uint32_t word0;
4680 	void __iomem *to_slim;
4681 	uint32_t hba_aer_enabled;
4682 
4683 	spin_lock_irq(&phba->hbalock);
4684 
4685 	/* Take PCIe device Advanced Error Reporting (AER) state */
4686 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4687 
4688 	psli = &phba->sli;
4689 
4690 	/* Restart HBA */
4691 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4692 			"0337 Restart HBA Data: x%x x%x\n",
4693 			(phba->pport) ? phba->pport->port_state : 0,
4694 			psli->sli_flag);
4695 
4696 	word0 = 0;
4697 	mb = (MAILBOX_t *) &word0;
4698 	mb->mbxCommand = MBX_RESTART;
4699 	mb->mbxHc = 1;
4700 
4701 	lpfc_reset_barrier(phba);
4702 
4703 	to_slim = phba->MBslimaddr;
4704 	writel(*(uint32_t *) mb, to_slim);
4705 	readl(to_slim); /* flush */
4706 
4707 	/* Only skip post after fc_ffinit is completed */
4708 	if (phba->pport && phba->pport->port_state)
4709 		word0 = 1;	/* This is really setting up word1 */
4710 	else
4711 		word0 = 0;	/* This is really setting up word1 */
4712 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
4713 	writel(*(uint32_t *) mb, to_slim);
4714 	readl(to_slim); /* flush */
4715 
4716 	lpfc_sli_brdreset(phba);
4717 	if (phba->pport)
4718 		phba->pport->stopped = 0;
4719 	phba->link_state = LPFC_INIT_START;
4720 	phba->hba_flag = 0;
4721 	spin_unlock_irq(&phba->hbalock);
4722 
4723 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4724 	psli->stats_start = ktime_get_seconds();
4725 
4726 	/* Give the INITFF and Post time to settle. */
4727 	mdelay(100);
4728 
4729 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4730 	if (hba_aer_enabled)
4731 		pci_disable_pcie_error_reporting(phba->pcidev);
4732 
4733 	lpfc_hba_down_post(phba);
4734 
4735 	return 0;
4736 }
4737 
4738 /**
4739  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
4740  * @phba: Pointer to HBA context object.
4741  *
4742  * This function is called in the SLI initialization code path to restart
4743  * a SLI4 HBA. The caller is not required to hold any lock.
4744  * At the end of the function, it calls lpfc_hba_down_post function to
4745  * free any pending commands.
4746  **/
4747 static int
4748 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
4749 {
4750 	struct lpfc_sli *psli = &phba->sli;
4751 	uint32_t hba_aer_enabled;
4752 	int rc;
4753 
4754 	/* Restart HBA */
4755 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4756 			"0296 Restart HBA Data: x%x x%x\n",
4757 			phba->pport->port_state, psli->sli_flag);
4758 
4759 	/* Take PCIe device Advanced Error Reporting (AER) state */
4760 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4761 
4762 	rc = lpfc_sli4_brdreset(phba);
4763 	if (rc) {
4764 		phba->link_state = LPFC_HBA_ERROR;
4765 		goto hba_down_queue;
4766 	}
4767 
4768 	spin_lock_irq(&phba->hbalock);
4769 	phba->pport->stopped = 0;
4770 	phba->link_state = LPFC_INIT_START;
4771 	phba->hba_flag = 0;
4772 	spin_unlock_irq(&phba->hbalock);
4773 
4774 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4775 	psli->stats_start = ktime_get_seconds();
4776 
4777 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4778 	if (hba_aer_enabled)
4779 		pci_disable_pcie_error_reporting(phba->pcidev);
4780 
4781 hba_down_queue:
4782 	lpfc_hba_down_post(phba);
4783 	lpfc_sli4_queue_destroy(phba);
4784 
4785 	return rc;
4786 }
4787 
4788 /**
4789  * lpfc_sli_brdrestart - Wrapper func for restarting hba
4790  * @phba: Pointer to HBA context object.
4791  *
4792  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
4793  * API jump table function pointer from the lpfc_hba struct.
4794 **/
4795 int
4796 lpfc_sli_brdrestart(struct lpfc_hba *phba)
4797 {
4798 	return phba->lpfc_sli_brdrestart(phba);
4799 }
4800 
4801 /**
4802  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
4803  * @phba: Pointer to HBA context object.
4804  *
4805  * This function is called after a HBA restart to wait for successful
4806  * restart of the HBA. Successful restart of the HBA is indicated by
4807  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
4808  * iteration, the function will restart the HBA again. The function returns
4809  * zero if HBA successfully restarted else returns negative error code.
4810  **/
4811 int
4812 lpfc_sli_chipset_init(struct lpfc_hba *phba)
4813 {
4814 	uint32_t status, i = 0;
4815 
4816 	/* Read the HBA Host Status Register */
4817 	if (lpfc_readl(phba->HSregaddr, &status))
4818 		return -EIO;
4819 
4820 	/* Check status register to see what current state is */
4821 	i = 0;
4822 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
4823 
4824 		/* Check every 10ms for 10 retries, then every 100ms for 90
4825 		 * retries, then every 1 sec for 50 retires for a total of
4826 		 * ~60 seconds before reset the board again and check every
4827 		 * 1 sec for 50 retries. The up to 60 seconds before the
4828 		 * board ready is required by the Falcon FIPS zeroization
4829 		 * complete, and any reset the board in between shall cause
4830 		 * restart of zeroization, further delay the board ready.
4831 		 */
4832 		if (i++ >= 200) {
4833 			/* Adapter failed to init, timeout, status reg
4834 			   <status> */
4835 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4836 					"0436 Adapter failed to init, "
4837 					"timeout, status reg x%x, "
4838 					"FW Data: A8 x%x AC x%x\n", status,
4839 					readl(phba->MBslimaddr + 0xa8),
4840 					readl(phba->MBslimaddr + 0xac));
4841 			phba->link_state = LPFC_HBA_ERROR;
4842 			return -ETIMEDOUT;
4843 		}
4844 
4845 		/* Check to see if any errors occurred during init */
4846 		if (status & HS_FFERM) {
4847 			/* ERROR: During chipset initialization */
4848 			/* Adapter failed to init, chipset, status reg
4849 			   <status> */
4850 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4851 					"0437 Adapter failed to init, "
4852 					"chipset, status reg x%x, "
4853 					"FW Data: A8 x%x AC x%x\n", status,
4854 					readl(phba->MBslimaddr + 0xa8),
4855 					readl(phba->MBslimaddr + 0xac));
4856 			phba->link_state = LPFC_HBA_ERROR;
4857 			return -EIO;
4858 		}
4859 
4860 		if (i <= 10)
4861 			msleep(10);
4862 		else if (i <= 100)
4863 			msleep(100);
4864 		else
4865 			msleep(1000);
4866 
4867 		if (i == 150) {
4868 			/* Do post */
4869 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4870 			lpfc_sli_brdrestart(phba);
4871 		}
4872 		/* Read the HBA Host Status Register */
4873 		if (lpfc_readl(phba->HSregaddr, &status))
4874 			return -EIO;
4875 	}
4876 
4877 	/* Check to see if any errors occurred during init */
4878 	if (status & HS_FFERM) {
4879 		/* ERROR: During chipset initialization */
4880 		/* Adapter failed to init, chipset, status reg <status> */
4881 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4882 				"0438 Adapter failed to init, chipset, "
4883 				"status reg x%x, "
4884 				"FW Data: A8 x%x AC x%x\n", status,
4885 				readl(phba->MBslimaddr + 0xa8),
4886 				readl(phba->MBslimaddr + 0xac));
4887 		phba->link_state = LPFC_HBA_ERROR;
4888 		return -EIO;
4889 	}
4890 
4891 	/* Clear all interrupt enable conditions */
4892 	writel(0, phba->HCregaddr);
4893 	readl(phba->HCregaddr); /* flush */
4894 
4895 	/* setup host attn register */
4896 	writel(0xffffffff, phba->HAregaddr);
4897 	readl(phba->HAregaddr); /* flush */
4898 	return 0;
4899 }
4900 
4901 /**
4902  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
4903  *
4904  * This function calculates and returns the number of HBQs required to be
4905  * configured.
4906  **/
4907 int
4908 lpfc_sli_hbq_count(void)
4909 {
4910 	return ARRAY_SIZE(lpfc_hbq_defs);
4911 }
4912 
4913 /**
4914  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
4915  *
4916  * This function adds the number of hbq entries in every HBQ to get
4917  * the total number of hbq entries required for the HBA and returns
4918  * the total count.
4919  **/
4920 static int
4921 lpfc_sli_hbq_entry_count(void)
4922 {
4923 	int  hbq_count = lpfc_sli_hbq_count();
4924 	int  count = 0;
4925 	int  i;
4926 
4927 	for (i = 0; i < hbq_count; ++i)
4928 		count += lpfc_hbq_defs[i]->entry_count;
4929 	return count;
4930 }
4931 
4932 /**
4933  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
4934  *
4935  * This function calculates amount of memory required for all hbq entries
4936  * to be configured and returns the total memory required.
4937  **/
4938 int
4939 lpfc_sli_hbq_size(void)
4940 {
4941 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
4942 }
4943 
4944 /**
4945  * lpfc_sli_hbq_setup - configure and initialize HBQs
4946  * @phba: Pointer to HBA context object.
4947  *
4948  * This function is called during the SLI initialization to configure
4949  * all the HBQs and post buffers to the HBQ. The caller is not
4950  * required to hold any locks. This function will return zero if successful
4951  * else it will return negative error code.
4952  **/
4953 static int
4954 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
4955 {
4956 	int  hbq_count = lpfc_sli_hbq_count();
4957 	LPFC_MBOXQ_t *pmb;
4958 	MAILBOX_t *pmbox;
4959 	uint32_t hbqno;
4960 	uint32_t hbq_entry_index;
4961 
4962 				/* Get a Mailbox buffer to setup mailbox
4963 				 * commands for HBA initialization
4964 				 */
4965 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4966 
4967 	if (!pmb)
4968 		return -ENOMEM;
4969 
4970 	pmbox = &pmb->u.mb;
4971 
4972 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
4973 	phba->link_state = LPFC_INIT_MBX_CMDS;
4974 	phba->hbq_in_use = 1;
4975 
4976 	hbq_entry_index = 0;
4977 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
4978 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
4979 		phba->hbqs[hbqno].hbqPutIdx      = 0;
4980 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
4981 		phba->hbqs[hbqno].entry_count =
4982 			lpfc_hbq_defs[hbqno]->entry_count;
4983 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
4984 			hbq_entry_index, pmb);
4985 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
4986 
4987 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
4988 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
4989 			   mbxStatus <status>, ring <num> */
4990 
4991 			lpfc_printf_log(phba, KERN_ERR,
4992 					LOG_SLI | LOG_VPORT,
4993 					"1805 Adapter failed to init. "
4994 					"Data: x%x x%x x%x\n",
4995 					pmbox->mbxCommand,
4996 					pmbox->mbxStatus, hbqno);
4997 
4998 			phba->link_state = LPFC_HBA_ERROR;
4999 			mempool_free(pmb, phba->mbox_mem_pool);
5000 			return -ENXIO;
5001 		}
5002 	}
5003 	phba->hbq_count = hbq_count;
5004 
5005 	mempool_free(pmb, phba->mbox_mem_pool);
5006 
5007 	/* Initially populate or replenish the HBQs */
5008 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5009 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5010 	return 0;
5011 }
5012 
5013 /**
5014  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5015  * @phba: Pointer to HBA context object.
5016  *
5017  * This function is called during the SLI initialization to configure
5018  * all the HBQs and post buffers to the HBQ. The caller is not
5019  * required to hold any locks. This function will return zero if successful
5020  * else it will return negative error code.
5021  **/
5022 static int
5023 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5024 {
5025 	phba->hbq_in_use = 1;
5026 	/**
5027 	 * Specific case when the MDS diagnostics is enabled and supported.
5028 	 * The receive buffer count is truncated to manage the incoming
5029 	 * traffic.
5030 	 **/
5031 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5032 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5033 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5034 	else
5035 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5036 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5037 	phba->hbq_count = 1;
5038 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5039 	/* Initially populate or replenish the HBQs */
5040 	return 0;
5041 }
5042 
5043 /**
5044  * lpfc_sli_config_port - Issue config port mailbox command
5045  * @phba: Pointer to HBA context object.
5046  * @sli_mode: sli mode - 2/3
5047  *
5048  * This function is called by the sli initialization code path
5049  * to issue config_port mailbox command. This function restarts the
5050  * HBA firmware and issues a config_port mailbox command to configure
5051  * the SLI interface in the sli mode specified by sli_mode
5052  * variable. The caller is not required to hold any locks.
5053  * The function returns 0 if successful, else returns negative error
5054  * code.
5055  **/
5056 int
5057 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5058 {
5059 	LPFC_MBOXQ_t *pmb;
5060 	uint32_t resetcount = 0, rc = 0, done = 0;
5061 
5062 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5063 	if (!pmb) {
5064 		phba->link_state = LPFC_HBA_ERROR;
5065 		return -ENOMEM;
5066 	}
5067 
5068 	phba->sli_rev = sli_mode;
5069 	while (resetcount < 2 && !done) {
5070 		spin_lock_irq(&phba->hbalock);
5071 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5072 		spin_unlock_irq(&phba->hbalock);
5073 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5074 		lpfc_sli_brdrestart(phba);
5075 		rc = lpfc_sli_chipset_init(phba);
5076 		if (rc)
5077 			break;
5078 
5079 		spin_lock_irq(&phba->hbalock);
5080 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5081 		spin_unlock_irq(&phba->hbalock);
5082 		resetcount++;
5083 
5084 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5085 		 * value of 0 means the call was successful.  Any other
5086 		 * nonzero value is a failure, but if ERESTART is returned,
5087 		 * the driver may reset the HBA and try again.
5088 		 */
5089 		rc = lpfc_config_port_prep(phba);
5090 		if (rc == -ERESTART) {
5091 			phba->link_state = LPFC_LINK_UNKNOWN;
5092 			continue;
5093 		} else if (rc)
5094 			break;
5095 
5096 		phba->link_state = LPFC_INIT_MBX_CMDS;
5097 		lpfc_config_port(phba, pmb);
5098 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5099 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5100 					LPFC_SLI3_HBQ_ENABLED |
5101 					LPFC_SLI3_CRP_ENABLED |
5102 					LPFC_SLI3_DSS_ENABLED);
5103 		if (rc != MBX_SUCCESS) {
5104 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5105 				"0442 Adapter failed to init, mbxCmd x%x "
5106 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5107 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5108 			spin_lock_irq(&phba->hbalock);
5109 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5110 			spin_unlock_irq(&phba->hbalock);
5111 			rc = -ENXIO;
5112 		} else {
5113 			/* Allow asynchronous mailbox command to go through */
5114 			spin_lock_irq(&phba->hbalock);
5115 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5116 			spin_unlock_irq(&phba->hbalock);
5117 			done = 1;
5118 
5119 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5120 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5121 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5122 					"3110 Port did not grant ASABT\n");
5123 		}
5124 	}
5125 	if (!done) {
5126 		rc = -EINVAL;
5127 		goto do_prep_failed;
5128 	}
5129 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5130 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5131 			rc = -ENXIO;
5132 			goto do_prep_failed;
5133 		}
5134 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5135 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5136 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5137 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5138 				phba->max_vpi : phba->max_vports;
5139 
5140 		} else
5141 			phba->max_vpi = 0;
5142 		if (pmb->u.mb.un.varCfgPort.gerbm)
5143 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5144 		if (pmb->u.mb.un.varCfgPort.gcrp)
5145 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5146 
5147 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5148 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5149 
5150 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5151 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5152 				phba->cfg_enable_bg = 0;
5153 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5154 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5155 						"0443 Adapter did not grant "
5156 						"BlockGuard\n");
5157 			}
5158 		}
5159 	} else {
5160 		phba->hbq_get = NULL;
5161 		phba->port_gp = phba->mbox->us.s2.port;
5162 		phba->max_vpi = 0;
5163 	}
5164 do_prep_failed:
5165 	mempool_free(pmb, phba->mbox_mem_pool);
5166 	return rc;
5167 }
5168 
5169 
5170 /**
5171  * lpfc_sli_hba_setup - SLI initialization function
5172  * @phba: Pointer to HBA context object.
5173  *
5174  * This function is the main SLI initialization function. This function
5175  * is called by the HBA initialization code, HBA reset code and HBA
5176  * error attention handler code. Caller is not required to hold any
5177  * locks. This function issues config_port mailbox command to configure
5178  * the SLI, setup iocb rings and HBQ rings. In the end the function
5179  * calls the config_port_post function to issue init_link mailbox
5180  * command and to start the discovery. The function will return zero
5181  * if successful, else it will return negative error code.
5182  **/
5183 int
5184 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5185 {
5186 	uint32_t rc;
5187 	int  mode = 3, i;
5188 	int longs;
5189 
5190 	switch (phba->cfg_sli_mode) {
5191 	case 2:
5192 		if (phba->cfg_enable_npiv) {
5193 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5194 				"1824 NPIV enabled: Override sli_mode "
5195 				"parameter (%d) to auto (0).\n",
5196 				phba->cfg_sli_mode);
5197 			break;
5198 		}
5199 		mode = 2;
5200 		break;
5201 	case 0:
5202 	case 3:
5203 		break;
5204 	default:
5205 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5206 				"1819 Unrecognized sli_mode parameter: %d.\n",
5207 				phba->cfg_sli_mode);
5208 
5209 		break;
5210 	}
5211 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5212 
5213 	rc = lpfc_sli_config_port(phba, mode);
5214 
5215 	if (rc && phba->cfg_sli_mode == 3)
5216 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5217 				"1820 Unable to select SLI-3.  "
5218 				"Not supported by adapter.\n");
5219 	if (rc && mode != 2)
5220 		rc = lpfc_sli_config_port(phba, 2);
5221 	else if (rc && mode == 2)
5222 		rc = lpfc_sli_config_port(phba, 3);
5223 	if (rc)
5224 		goto lpfc_sli_hba_setup_error;
5225 
5226 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
5227 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
5228 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
5229 		if (!rc) {
5230 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5231 					"2709 This device supports "
5232 					"Advanced Error Reporting (AER)\n");
5233 			spin_lock_irq(&phba->hbalock);
5234 			phba->hba_flag |= HBA_AER_ENABLED;
5235 			spin_unlock_irq(&phba->hbalock);
5236 		} else {
5237 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5238 					"2708 This device does not support "
5239 					"Advanced Error Reporting (AER): %d\n",
5240 					rc);
5241 			phba->cfg_aer_support = 0;
5242 		}
5243 	}
5244 
5245 	if (phba->sli_rev == 3) {
5246 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5247 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5248 	} else {
5249 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5250 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5251 		phba->sli3_options = 0;
5252 	}
5253 
5254 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5255 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5256 			phba->sli_rev, phba->max_vpi);
5257 	rc = lpfc_sli_ring_map(phba);
5258 
5259 	if (rc)
5260 		goto lpfc_sli_hba_setup_error;
5261 
5262 	/* Initialize VPIs. */
5263 	if (phba->sli_rev == LPFC_SLI_REV3) {
5264 		/*
5265 		 * The VPI bitmask and physical ID array are allocated
5266 		 * and initialized once only - at driver load.  A port
5267 		 * reset doesn't need to reinitialize this memory.
5268 		 */
5269 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5270 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5271 			phba->vpi_bmask = kcalloc(longs,
5272 						  sizeof(unsigned long),
5273 						  GFP_KERNEL);
5274 			if (!phba->vpi_bmask) {
5275 				rc = -ENOMEM;
5276 				goto lpfc_sli_hba_setup_error;
5277 			}
5278 
5279 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5280 						sizeof(uint16_t),
5281 						GFP_KERNEL);
5282 			if (!phba->vpi_ids) {
5283 				kfree(phba->vpi_bmask);
5284 				rc = -ENOMEM;
5285 				goto lpfc_sli_hba_setup_error;
5286 			}
5287 			for (i = 0; i < phba->max_vpi; i++)
5288 				phba->vpi_ids[i] = i;
5289 		}
5290 	}
5291 
5292 	/* Init HBQs */
5293 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5294 		rc = lpfc_sli_hbq_setup(phba);
5295 		if (rc)
5296 			goto lpfc_sli_hba_setup_error;
5297 	}
5298 	spin_lock_irq(&phba->hbalock);
5299 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5300 	spin_unlock_irq(&phba->hbalock);
5301 
5302 	rc = lpfc_config_port_post(phba);
5303 	if (rc)
5304 		goto lpfc_sli_hba_setup_error;
5305 
5306 	return rc;
5307 
5308 lpfc_sli_hba_setup_error:
5309 	phba->link_state = LPFC_HBA_ERROR;
5310 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5311 			"0445 Firmware initialization failed\n");
5312 	return rc;
5313 }
5314 
5315 /**
5316  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5317  * @phba: Pointer to HBA context object.
5318  *
5319  * This function issue a dump mailbox command to read config region
5320  * 23 and parse the records in the region and populate driver
5321  * data structure.
5322  **/
5323 static int
5324 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5325 {
5326 	LPFC_MBOXQ_t *mboxq;
5327 	struct lpfc_dmabuf *mp;
5328 	struct lpfc_mqe *mqe;
5329 	uint32_t data_length;
5330 	int rc;
5331 
5332 	/* Program the default value of vlan_id and fc_map */
5333 	phba->valid_vlan = 0;
5334 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5335 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5336 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5337 
5338 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5339 	if (!mboxq)
5340 		return -ENOMEM;
5341 
5342 	mqe = &mboxq->u.mqe;
5343 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5344 		rc = -ENOMEM;
5345 		goto out_free_mboxq;
5346 	}
5347 
5348 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5349 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5350 
5351 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5352 			"(%d):2571 Mailbox cmd x%x Status x%x "
5353 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5354 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5355 			"CQ: x%x x%x x%x x%x\n",
5356 			mboxq->vport ? mboxq->vport->vpi : 0,
5357 			bf_get(lpfc_mqe_command, mqe),
5358 			bf_get(lpfc_mqe_status, mqe),
5359 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5360 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5361 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5362 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5363 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5364 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5365 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5366 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5367 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5368 			mboxq->mcqe.word0,
5369 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5370 			mboxq->mcqe.trailer);
5371 
5372 	if (rc) {
5373 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5374 		kfree(mp);
5375 		rc = -EIO;
5376 		goto out_free_mboxq;
5377 	}
5378 	data_length = mqe->un.mb_words[5];
5379 	if (data_length > DMP_RGN23_SIZE) {
5380 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5381 		kfree(mp);
5382 		rc = -EIO;
5383 		goto out_free_mboxq;
5384 	}
5385 
5386 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5387 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
5388 	kfree(mp);
5389 	rc = 0;
5390 
5391 out_free_mboxq:
5392 	mempool_free(mboxq, phba->mbox_mem_pool);
5393 	return rc;
5394 }
5395 
5396 /**
5397  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5398  * @phba: pointer to lpfc hba data structure.
5399  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5400  * @vpd: pointer to the memory to hold resulting port vpd data.
5401  * @vpd_size: On input, the number of bytes allocated to @vpd.
5402  *	      On output, the number of data bytes in @vpd.
5403  *
5404  * This routine executes a READ_REV SLI4 mailbox command.  In
5405  * addition, this routine gets the port vpd data.
5406  *
5407  * Return codes
5408  * 	0 - successful
5409  * 	-ENOMEM - could not allocated memory.
5410  **/
5411 static int
5412 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5413 		    uint8_t *vpd, uint32_t *vpd_size)
5414 {
5415 	int rc = 0;
5416 	uint32_t dma_size;
5417 	struct lpfc_dmabuf *dmabuf;
5418 	struct lpfc_mqe *mqe;
5419 
5420 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5421 	if (!dmabuf)
5422 		return -ENOMEM;
5423 
5424 	/*
5425 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5426 	 * mailbox command.
5427 	 */
5428 	dma_size = *vpd_size;
5429 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5430 					  &dmabuf->phys, GFP_KERNEL);
5431 	if (!dmabuf->virt) {
5432 		kfree(dmabuf);
5433 		return -ENOMEM;
5434 	}
5435 
5436 	/*
5437 	 * The SLI4 implementation of READ_REV conflicts at word1,
5438 	 * bits 31:16 and SLI4 adds vpd functionality not present
5439 	 * in SLI3.  This code corrects the conflicts.
5440 	 */
5441 	lpfc_read_rev(phba, mboxq);
5442 	mqe = &mboxq->u.mqe;
5443 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5444 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5445 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5446 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5447 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5448 
5449 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5450 	if (rc) {
5451 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5452 				  dmabuf->virt, dmabuf->phys);
5453 		kfree(dmabuf);
5454 		return -EIO;
5455 	}
5456 
5457 	/*
5458 	 * The available vpd length cannot be bigger than the
5459 	 * DMA buffer passed to the port.  Catch the less than
5460 	 * case and update the caller's size.
5461 	 */
5462 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5463 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5464 
5465 	memcpy(vpd, dmabuf->virt, *vpd_size);
5466 
5467 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5468 			  dmabuf->virt, dmabuf->phys);
5469 	kfree(dmabuf);
5470 	return 0;
5471 }
5472 
5473 /**
5474  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5475  * @phba: pointer to lpfc hba data structure.
5476  *
5477  * This routine retrieves SLI4 device physical port name this PCI function
5478  * is attached to.
5479  *
5480  * Return codes
5481  *      0 - successful
5482  *      otherwise - failed to retrieve controller attributes
5483  **/
5484 static int
5485 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5486 {
5487 	LPFC_MBOXQ_t *mboxq;
5488 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5489 	struct lpfc_controller_attribute *cntl_attr;
5490 	void *virtaddr = NULL;
5491 	uint32_t alloclen, reqlen;
5492 	uint32_t shdr_status, shdr_add_status;
5493 	union lpfc_sli4_cfg_shdr *shdr;
5494 	int rc;
5495 
5496 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5497 	if (!mboxq)
5498 		return -ENOMEM;
5499 
5500 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5501 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5502 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5503 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5504 			LPFC_SLI4_MBX_NEMBED);
5505 
5506 	if (alloclen < reqlen) {
5507 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5508 				"3084 Allocated DMA memory size (%d) is "
5509 				"less than the requested DMA memory size "
5510 				"(%d)\n", alloclen, reqlen);
5511 		rc = -ENOMEM;
5512 		goto out_free_mboxq;
5513 	}
5514 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5515 	virtaddr = mboxq->sge_array->addr[0];
5516 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5517 	shdr = &mbx_cntl_attr->cfg_shdr;
5518 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5519 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5520 	if (shdr_status || shdr_add_status || rc) {
5521 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5522 				"3085 Mailbox x%x (x%x/x%x) failed, "
5523 				"rc:x%x, status:x%x, add_status:x%x\n",
5524 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5525 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5526 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5527 				rc, shdr_status, shdr_add_status);
5528 		rc = -ENXIO;
5529 		goto out_free_mboxq;
5530 	}
5531 
5532 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5533 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5534 	phba->sli4_hba.lnk_info.lnk_tp =
5535 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5536 	phba->sli4_hba.lnk_info.lnk_no =
5537 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5538 
5539 	memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
5540 	strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
5541 		sizeof(phba->BIOSVersion));
5542 
5543 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5544 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s\n",
5545 			phba->sli4_hba.lnk_info.lnk_tp,
5546 			phba->sli4_hba.lnk_info.lnk_no,
5547 			phba->BIOSVersion);
5548 out_free_mboxq:
5549 	if (rc != MBX_TIMEOUT) {
5550 		if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5551 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
5552 		else
5553 			mempool_free(mboxq, phba->mbox_mem_pool);
5554 	}
5555 	return rc;
5556 }
5557 
5558 /**
5559  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
5560  * @phba: pointer to lpfc hba data structure.
5561  *
5562  * This routine retrieves SLI4 device physical port name this PCI function
5563  * is attached to.
5564  *
5565  * Return codes
5566  *      0 - successful
5567  *      otherwise - failed to retrieve physical port name
5568  **/
5569 static int
5570 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
5571 {
5572 	LPFC_MBOXQ_t *mboxq;
5573 	struct lpfc_mbx_get_port_name *get_port_name;
5574 	uint32_t shdr_status, shdr_add_status;
5575 	union lpfc_sli4_cfg_shdr *shdr;
5576 	char cport_name = 0;
5577 	int rc;
5578 
5579 	/* We assume nothing at this point */
5580 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5581 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
5582 
5583 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5584 	if (!mboxq)
5585 		return -ENOMEM;
5586 	/* obtain link type and link number via READ_CONFIG */
5587 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5588 	lpfc_sli4_read_config(phba);
5589 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
5590 		goto retrieve_ppname;
5591 
5592 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
5593 	rc = lpfc_sli4_get_ctl_attr(phba);
5594 	if (rc)
5595 		goto out_free_mboxq;
5596 
5597 retrieve_ppname:
5598 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5599 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
5600 		sizeof(struct lpfc_mbx_get_port_name) -
5601 		sizeof(struct lpfc_sli4_cfg_mhdr),
5602 		LPFC_SLI4_MBX_EMBED);
5603 	get_port_name = &mboxq->u.mqe.un.get_port_name;
5604 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5605 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
5606 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
5607 		phba->sli4_hba.lnk_info.lnk_tp);
5608 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5609 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5610 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5611 	if (shdr_status || shdr_add_status || rc) {
5612 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5613 				"3087 Mailbox x%x (x%x/x%x) failed: "
5614 				"rc:x%x, status:x%x, add_status:x%x\n",
5615 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5616 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5617 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5618 				rc, shdr_status, shdr_add_status);
5619 		rc = -ENXIO;
5620 		goto out_free_mboxq;
5621 	}
5622 	switch (phba->sli4_hba.lnk_info.lnk_no) {
5623 	case LPFC_LINK_NUMBER_0:
5624 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
5625 				&get_port_name->u.response);
5626 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5627 		break;
5628 	case LPFC_LINK_NUMBER_1:
5629 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
5630 				&get_port_name->u.response);
5631 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5632 		break;
5633 	case LPFC_LINK_NUMBER_2:
5634 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
5635 				&get_port_name->u.response);
5636 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5637 		break;
5638 	case LPFC_LINK_NUMBER_3:
5639 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
5640 				&get_port_name->u.response);
5641 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5642 		break;
5643 	default:
5644 		break;
5645 	}
5646 
5647 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
5648 		phba->Port[0] = cport_name;
5649 		phba->Port[1] = '\0';
5650 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5651 				"3091 SLI get port name: %s\n", phba->Port);
5652 	}
5653 
5654 out_free_mboxq:
5655 	if (rc != MBX_TIMEOUT) {
5656 		if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5657 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
5658 		else
5659 			mempool_free(mboxq, phba->mbox_mem_pool);
5660 	}
5661 	return rc;
5662 }
5663 
5664 /**
5665  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
5666  * @phba: pointer to lpfc hba data structure.
5667  *
5668  * This routine is called to explicitly arm the SLI4 device's completion and
5669  * event queues
5670  **/
5671 static void
5672 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
5673 {
5674 	int qidx;
5675 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
5676 	struct lpfc_sli4_hdw_queue *qp;
5677 	struct lpfc_queue *eq;
5678 
5679 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
5680 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
5681 	if (sli4_hba->nvmels_cq)
5682 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
5683 					   LPFC_QUEUE_REARM);
5684 
5685 	if (sli4_hba->hdwq) {
5686 		/* Loop thru all Hardware Queues */
5687 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
5688 			qp = &sli4_hba->hdwq[qidx];
5689 			/* ARM the corresponding CQ */
5690 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
5691 						LPFC_QUEUE_REARM);
5692 		}
5693 
5694 		/* Loop thru all IRQ vectors */
5695 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
5696 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
5697 			/* ARM the corresponding EQ */
5698 			sli4_hba->sli4_write_eq_db(phba, eq,
5699 						   0, LPFC_QUEUE_REARM);
5700 		}
5701 	}
5702 
5703 	if (phba->nvmet_support) {
5704 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
5705 			sli4_hba->sli4_write_cq_db(phba,
5706 				sli4_hba->nvmet_cqset[qidx], 0,
5707 				LPFC_QUEUE_REARM);
5708 		}
5709 	}
5710 }
5711 
5712 /**
5713  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
5714  * @phba: Pointer to HBA context object.
5715  * @type: The resource extent type.
5716  * @extnt_count: buffer to hold port available extent count.
5717  * @extnt_size: buffer to hold element count per extent.
5718  *
5719  * This function calls the port and retrievs the number of available
5720  * extents and their size for a particular extent type.
5721  *
5722  * Returns: 0 if successful.  Nonzero otherwise.
5723  **/
5724 int
5725 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
5726 			       uint16_t *extnt_count, uint16_t *extnt_size)
5727 {
5728 	int rc = 0;
5729 	uint32_t length;
5730 	uint32_t mbox_tmo;
5731 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
5732 	LPFC_MBOXQ_t *mbox;
5733 
5734 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5735 	if (!mbox)
5736 		return -ENOMEM;
5737 
5738 	/* Find out how many extents are available for this resource type */
5739 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
5740 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5741 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5742 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
5743 			 length, LPFC_SLI4_MBX_EMBED);
5744 
5745 	/* Send an extents count of 0 - the GET doesn't use it. */
5746 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5747 					LPFC_SLI4_MBX_EMBED);
5748 	if (unlikely(rc)) {
5749 		rc = -EIO;
5750 		goto err_exit;
5751 	}
5752 
5753 	if (!phba->sli4_hba.intr_enable)
5754 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5755 	else {
5756 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5757 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5758 	}
5759 	if (unlikely(rc)) {
5760 		rc = -EIO;
5761 		goto err_exit;
5762 	}
5763 
5764 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
5765 	if (bf_get(lpfc_mbox_hdr_status,
5766 		   &rsrc_info->header.cfg_shdr.response)) {
5767 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5768 				"2930 Failed to get resource extents "
5769 				"Status 0x%x Add'l Status 0x%x\n",
5770 				bf_get(lpfc_mbox_hdr_status,
5771 				       &rsrc_info->header.cfg_shdr.response),
5772 				bf_get(lpfc_mbox_hdr_add_status,
5773 				       &rsrc_info->header.cfg_shdr.response));
5774 		rc = -EIO;
5775 		goto err_exit;
5776 	}
5777 
5778 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
5779 			      &rsrc_info->u.rsp);
5780 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
5781 			     &rsrc_info->u.rsp);
5782 
5783 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5784 			"3162 Retrieved extents type-%d from port: count:%d, "
5785 			"size:%d\n", type, *extnt_count, *extnt_size);
5786 
5787 err_exit:
5788 	mempool_free(mbox, phba->mbox_mem_pool);
5789 	return rc;
5790 }
5791 
5792 /**
5793  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
5794  * @phba: Pointer to HBA context object.
5795  * @type: The extent type to check.
5796  *
5797  * This function reads the current available extents from the port and checks
5798  * if the extent count or extent size has changed since the last access.
5799  * Callers use this routine post port reset to understand if there is a
5800  * extent reprovisioning requirement.
5801  *
5802  * Returns:
5803  *   -Error: error indicates problem.
5804  *   1: Extent count or size has changed.
5805  *   0: No changes.
5806  **/
5807 static int
5808 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
5809 {
5810 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
5811 	uint16_t size_diff, rsrc_ext_size;
5812 	int rc = 0;
5813 	struct lpfc_rsrc_blks *rsrc_entry;
5814 	struct list_head *rsrc_blk_list = NULL;
5815 
5816 	size_diff = 0;
5817 	curr_ext_cnt = 0;
5818 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5819 					    &rsrc_ext_cnt,
5820 					    &rsrc_ext_size);
5821 	if (unlikely(rc))
5822 		return -EIO;
5823 
5824 	switch (type) {
5825 	case LPFC_RSC_TYPE_FCOE_RPI:
5826 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5827 		break;
5828 	case LPFC_RSC_TYPE_FCOE_VPI:
5829 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
5830 		break;
5831 	case LPFC_RSC_TYPE_FCOE_XRI:
5832 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5833 		break;
5834 	case LPFC_RSC_TYPE_FCOE_VFI:
5835 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5836 		break;
5837 	default:
5838 		break;
5839 	}
5840 
5841 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
5842 		curr_ext_cnt++;
5843 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
5844 			size_diff++;
5845 	}
5846 
5847 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
5848 		rc = 1;
5849 
5850 	return rc;
5851 }
5852 
5853 /**
5854  * lpfc_sli4_cfg_post_extnts -
5855  * @phba: Pointer to HBA context object.
5856  * @extnt_cnt: number of available extents.
5857  * @type: the extent type (rpi, xri, vfi, vpi).
5858  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
5859  * @mbox: pointer to the caller's allocated mailbox structure.
5860  *
5861  * This function executes the extents allocation request.  It also
5862  * takes care of the amount of memory needed to allocate or get the
5863  * allocated extents. It is the caller's responsibility to evaluate
5864  * the response.
5865  *
5866  * Returns:
5867  *   -Error:  Error value describes the condition found.
5868  *   0: if successful
5869  **/
5870 static int
5871 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
5872 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
5873 {
5874 	int rc = 0;
5875 	uint32_t req_len;
5876 	uint32_t emb_len;
5877 	uint32_t alloc_len, mbox_tmo;
5878 
5879 	/* Calculate the total requested length of the dma memory */
5880 	req_len = extnt_cnt * sizeof(uint16_t);
5881 
5882 	/*
5883 	 * Calculate the size of an embedded mailbox.  The uint32_t
5884 	 * accounts for extents-specific word.
5885 	 */
5886 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
5887 		sizeof(uint32_t);
5888 
5889 	/*
5890 	 * Presume the allocation and response will fit into an embedded
5891 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
5892 	 */
5893 	*emb = LPFC_SLI4_MBX_EMBED;
5894 	if (req_len > emb_len) {
5895 		req_len = extnt_cnt * sizeof(uint16_t) +
5896 			sizeof(union lpfc_sli4_cfg_shdr) +
5897 			sizeof(uint32_t);
5898 		*emb = LPFC_SLI4_MBX_NEMBED;
5899 	}
5900 
5901 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5902 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
5903 				     req_len, *emb);
5904 	if (alloc_len < req_len) {
5905 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5906 			"2982 Allocated DMA memory size (x%x) is "
5907 			"less than the requested DMA memory "
5908 			"size (x%x)\n", alloc_len, req_len);
5909 		return -ENOMEM;
5910 	}
5911 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
5912 	if (unlikely(rc))
5913 		return -EIO;
5914 
5915 	if (!phba->sli4_hba.intr_enable)
5916 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5917 	else {
5918 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5919 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5920 	}
5921 
5922 	if (unlikely(rc))
5923 		rc = -EIO;
5924 	return rc;
5925 }
5926 
5927 /**
5928  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
5929  * @phba: Pointer to HBA context object.
5930  * @type:  The resource extent type to allocate.
5931  *
5932  * This function allocates the number of elements for the specified
5933  * resource type.
5934  **/
5935 static int
5936 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
5937 {
5938 	bool emb = false;
5939 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
5940 	uint16_t rsrc_id, rsrc_start, j, k;
5941 	uint16_t *ids;
5942 	int i, rc;
5943 	unsigned long longs;
5944 	unsigned long *bmask;
5945 	struct lpfc_rsrc_blks *rsrc_blks;
5946 	LPFC_MBOXQ_t *mbox;
5947 	uint32_t length;
5948 	struct lpfc_id_range *id_array = NULL;
5949 	void *virtaddr = NULL;
5950 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
5951 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
5952 	struct list_head *ext_blk_list;
5953 
5954 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5955 					    &rsrc_cnt,
5956 					    &rsrc_size);
5957 	if (unlikely(rc))
5958 		return -EIO;
5959 
5960 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
5961 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5962 			"3009 No available Resource Extents "
5963 			"for resource type 0x%x: Count: 0x%x, "
5964 			"Size 0x%x\n", type, rsrc_cnt,
5965 			rsrc_size);
5966 		return -ENOMEM;
5967 	}
5968 
5969 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
5970 			"2903 Post resource extents type-0x%x: "
5971 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
5972 
5973 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5974 	if (!mbox)
5975 		return -ENOMEM;
5976 
5977 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
5978 	if (unlikely(rc)) {
5979 		rc = -EIO;
5980 		goto err_exit;
5981 	}
5982 
5983 	/*
5984 	 * Figure out where the response is located.  Then get local pointers
5985 	 * to the response data.  The port does not guarantee to respond to
5986 	 * all extents counts request so update the local variable with the
5987 	 * allocated count from the port.
5988 	 */
5989 	if (emb == LPFC_SLI4_MBX_EMBED) {
5990 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
5991 		id_array = &rsrc_ext->u.rsp.id[0];
5992 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
5993 	} else {
5994 		virtaddr = mbox->sge_array->addr[0];
5995 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
5996 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
5997 		id_array = &n_rsrc->id;
5998 	}
5999 
6000 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6001 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6002 
6003 	/*
6004 	 * Based on the resource size and count, correct the base and max
6005 	 * resource values.
6006 	 */
6007 	length = sizeof(struct lpfc_rsrc_blks);
6008 	switch (type) {
6009 	case LPFC_RSC_TYPE_FCOE_RPI:
6010 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6011 						   sizeof(unsigned long),
6012 						   GFP_KERNEL);
6013 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6014 			rc = -ENOMEM;
6015 			goto err_exit;
6016 		}
6017 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6018 						 sizeof(uint16_t),
6019 						 GFP_KERNEL);
6020 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6021 			kfree(phba->sli4_hba.rpi_bmask);
6022 			rc = -ENOMEM;
6023 			goto err_exit;
6024 		}
6025 
6026 		/*
6027 		 * The next_rpi was initialized with the maximum available
6028 		 * count but the port may allocate a smaller number.  Catch
6029 		 * that case and update the next_rpi.
6030 		 */
6031 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6032 
6033 		/* Initialize local ptrs for common extent processing later. */
6034 		bmask = phba->sli4_hba.rpi_bmask;
6035 		ids = phba->sli4_hba.rpi_ids;
6036 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6037 		break;
6038 	case LPFC_RSC_TYPE_FCOE_VPI:
6039 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6040 					  GFP_KERNEL);
6041 		if (unlikely(!phba->vpi_bmask)) {
6042 			rc = -ENOMEM;
6043 			goto err_exit;
6044 		}
6045 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6046 					 GFP_KERNEL);
6047 		if (unlikely(!phba->vpi_ids)) {
6048 			kfree(phba->vpi_bmask);
6049 			rc = -ENOMEM;
6050 			goto err_exit;
6051 		}
6052 
6053 		/* Initialize local ptrs for common extent processing later. */
6054 		bmask = phba->vpi_bmask;
6055 		ids = phba->vpi_ids;
6056 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6057 		break;
6058 	case LPFC_RSC_TYPE_FCOE_XRI:
6059 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6060 						   sizeof(unsigned long),
6061 						   GFP_KERNEL);
6062 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6063 			rc = -ENOMEM;
6064 			goto err_exit;
6065 		}
6066 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6067 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6068 						 sizeof(uint16_t),
6069 						 GFP_KERNEL);
6070 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6071 			kfree(phba->sli4_hba.xri_bmask);
6072 			rc = -ENOMEM;
6073 			goto err_exit;
6074 		}
6075 
6076 		/* Initialize local ptrs for common extent processing later. */
6077 		bmask = phba->sli4_hba.xri_bmask;
6078 		ids = phba->sli4_hba.xri_ids;
6079 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6080 		break;
6081 	case LPFC_RSC_TYPE_FCOE_VFI:
6082 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6083 						   sizeof(unsigned long),
6084 						   GFP_KERNEL);
6085 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6086 			rc = -ENOMEM;
6087 			goto err_exit;
6088 		}
6089 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6090 						 sizeof(uint16_t),
6091 						 GFP_KERNEL);
6092 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6093 			kfree(phba->sli4_hba.vfi_bmask);
6094 			rc = -ENOMEM;
6095 			goto err_exit;
6096 		}
6097 
6098 		/* Initialize local ptrs for common extent processing later. */
6099 		bmask = phba->sli4_hba.vfi_bmask;
6100 		ids = phba->sli4_hba.vfi_ids;
6101 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6102 		break;
6103 	default:
6104 		/* Unsupported Opcode.  Fail call. */
6105 		id_array = NULL;
6106 		bmask = NULL;
6107 		ids = NULL;
6108 		ext_blk_list = NULL;
6109 		goto err_exit;
6110 	}
6111 
6112 	/*
6113 	 * Complete initializing the extent configuration with the
6114 	 * allocated ids assigned to this function.  The bitmask serves
6115 	 * as an index into the array and manages the available ids.  The
6116 	 * array just stores the ids communicated to the port via the wqes.
6117 	 */
6118 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6119 		if ((i % 2) == 0)
6120 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6121 					 &id_array[k]);
6122 		else
6123 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6124 					 &id_array[k]);
6125 
6126 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6127 		if (unlikely(!rsrc_blks)) {
6128 			rc = -ENOMEM;
6129 			kfree(bmask);
6130 			kfree(ids);
6131 			goto err_exit;
6132 		}
6133 		rsrc_blks->rsrc_start = rsrc_id;
6134 		rsrc_blks->rsrc_size = rsrc_size;
6135 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6136 		rsrc_start = rsrc_id;
6137 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6138 			phba->sli4_hba.io_xri_start = rsrc_start +
6139 				lpfc_sli4_get_iocb_cnt(phba);
6140 		}
6141 
6142 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6143 			ids[j] = rsrc_id;
6144 			rsrc_id++;
6145 			j++;
6146 		}
6147 		/* Entire word processed.  Get next word.*/
6148 		if ((i % 2) == 1)
6149 			k++;
6150 	}
6151  err_exit:
6152 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6153 	return rc;
6154 }
6155 
6156 
6157 
6158 /**
6159  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6160  * @phba: Pointer to HBA context object.
6161  * @type: the extent's type.
6162  *
6163  * This function deallocates all extents of a particular resource type.
6164  * SLI4 does not allow for deallocating a particular extent range.  It
6165  * is the caller's responsibility to release all kernel memory resources.
6166  **/
6167 static int
6168 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6169 {
6170 	int rc;
6171 	uint32_t length, mbox_tmo = 0;
6172 	LPFC_MBOXQ_t *mbox;
6173 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6174 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6175 
6176 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6177 	if (!mbox)
6178 		return -ENOMEM;
6179 
6180 	/*
6181 	 * This function sends an embedded mailbox because it only sends the
6182 	 * the resource type.  All extents of this type are released by the
6183 	 * port.
6184 	 */
6185 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6186 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6187 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6188 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6189 			 length, LPFC_SLI4_MBX_EMBED);
6190 
6191 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6192 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6193 					LPFC_SLI4_MBX_EMBED);
6194 	if (unlikely(rc)) {
6195 		rc = -EIO;
6196 		goto out_free_mbox;
6197 	}
6198 	if (!phba->sli4_hba.intr_enable)
6199 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6200 	else {
6201 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6202 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6203 	}
6204 	if (unlikely(rc)) {
6205 		rc = -EIO;
6206 		goto out_free_mbox;
6207 	}
6208 
6209 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6210 	if (bf_get(lpfc_mbox_hdr_status,
6211 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6212 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6213 				"2919 Failed to release resource extents "
6214 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6215 				"Resource memory not released.\n",
6216 				type,
6217 				bf_get(lpfc_mbox_hdr_status,
6218 				    &dealloc_rsrc->header.cfg_shdr.response),
6219 				bf_get(lpfc_mbox_hdr_add_status,
6220 				    &dealloc_rsrc->header.cfg_shdr.response));
6221 		rc = -EIO;
6222 		goto out_free_mbox;
6223 	}
6224 
6225 	/* Release kernel memory resources for the specific type. */
6226 	switch (type) {
6227 	case LPFC_RSC_TYPE_FCOE_VPI:
6228 		kfree(phba->vpi_bmask);
6229 		kfree(phba->vpi_ids);
6230 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6231 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6232 				    &phba->lpfc_vpi_blk_list, list) {
6233 			list_del_init(&rsrc_blk->list);
6234 			kfree(rsrc_blk);
6235 		}
6236 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6237 		break;
6238 	case LPFC_RSC_TYPE_FCOE_XRI:
6239 		kfree(phba->sli4_hba.xri_bmask);
6240 		kfree(phba->sli4_hba.xri_ids);
6241 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6242 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6243 			list_del_init(&rsrc_blk->list);
6244 			kfree(rsrc_blk);
6245 		}
6246 		break;
6247 	case LPFC_RSC_TYPE_FCOE_VFI:
6248 		kfree(phba->sli4_hba.vfi_bmask);
6249 		kfree(phba->sli4_hba.vfi_ids);
6250 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6251 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6252 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6253 			list_del_init(&rsrc_blk->list);
6254 			kfree(rsrc_blk);
6255 		}
6256 		break;
6257 	case LPFC_RSC_TYPE_FCOE_RPI:
6258 		/* RPI bitmask and physical id array are cleaned up earlier. */
6259 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6260 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6261 			list_del_init(&rsrc_blk->list);
6262 			kfree(rsrc_blk);
6263 		}
6264 		break;
6265 	default:
6266 		break;
6267 	}
6268 
6269 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6270 
6271  out_free_mbox:
6272 	mempool_free(mbox, phba->mbox_mem_pool);
6273 	return rc;
6274 }
6275 
6276 static void
6277 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6278 		  uint32_t feature)
6279 {
6280 	uint32_t len;
6281 
6282 	len = sizeof(struct lpfc_mbx_set_feature) -
6283 		sizeof(struct lpfc_sli4_cfg_mhdr);
6284 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6285 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6286 			 LPFC_SLI4_MBX_EMBED);
6287 
6288 	switch (feature) {
6289 	case LPFC_SET_UE_RECOVERY:
6290 		bf_set(lpfc_mbx_set_feature_UER,
6291 		       &mbox->u.mqe.un.set_feature, 1);
6292 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6293 		mbox->u.mqe.un.set_feature.param_len = 8;
6294 		break;
6295 	case LPFC_SET_MDS_DIAGS:
6296 		bf_set(lpfc_mbx_set_feature_mds,
6297 		       &mbox->u.mqe.un.set_feature, 1);
6298 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6299 		       &mbox->u.mqe.un.set_feature, 1);
6300 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6301 		mbox->u.mqe.un.set_feature.param_len = 8;
6302 		break;
6303 	case LPFC_SET_DUAL_DUMP:
6304 		bf_set(lpfc_mbx_set_feature_dd,
6305 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6306 		bf_set(lpfc_mbx_set_feature_ddquery,
6307 		       &mbox->u.mqe.un.set_feature, 0);
6308 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6309 		mbox->u.mqe.un.set_feature.param_len = 4;
6310 		break;
6311 	}
6312 
6313 	return;
6314 }
6315 
6316 /**
6317  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6318  * @phba: Pointer to HBA context object.
6319  *
6320  * Disable FW logging into host memory on the adapter. To
6321  * be done before reading logs from the host memory.
6322  **/
6323 void
6324 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6325 {
6326 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6327 
6328 	spin_lock_irq(&phba->hbalock);
6329 	ras_fwlog->state = INACTIVE;
6330 	spin_unlock_irq(&phba->hbalock);
6331 
6332 	/* Disable FW logging to host memory */
6333 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6334 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6335 
6336 	/* Wait 10ms for firmware to stop using DMA buffer */
6337 	usleep_range(10 * 1000, 20 * 1000);
6338 }
6339 
6340 /**
6341  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6342  * @phba: Pointer to HBA context object.
6343  *
6344  * This function is called to free memory allocated for RAS FW logging
6345  * support in the driver.
6346  **/
6347 void
6348 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6349 {
6350 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6351 	struct lpfc_dmabuf *dmabuf, *next;
6352 
6353 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6354 		list_for_each_entry_safe(dmabuf, next,
6355 				    &ras_fwlog->fwlog_buff_list,
6356 				    list) {
6357 			list_del(&dmabuf->list);
6358 			dma_free_coherent(&phba->pcidev->dev,
6359 					  LPFC_RAS_MAX_ENTRY_SIZE,
6360 					  dmabuf->virt, dmabuf->phys);
6361 			kfree(dmabuf);
6362 		}
6363 	}
6364 
6365 	if (ras_fwlog->lwpd.virt) {
6366 		dma_free_coherent(&phba->pcidev->dev,
6367 				  sizeof(uint32_t) * 2,
6368 				  ras_fwlog->lwpd.virt,
6369 				  ras_fwlog->lwpd.phys);
6370 		ras_fwlog->lwpd.virt = NULL;
6371 	}
6372 
6373 	spin_lock_irq(&phba->hbalock);
6374 	ras_fwlog->state = INACTIVE;
6375 	spin_unlock_irq(&phba->hbalock);
6376 }
6377 
6378 /**
6379  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6380  * @phba: Pointer to HBA context object.
6381  * @fwlog_buff_count: Count of buffers to be created.
6382  *
6383  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6384  * to update FW log is posted to the adapter.
6385  * Buffer count is calculated based on module param ras_fwlog_buffsize
6386  * Size of each buffer posted to FW is 64K.
6387  **/
6388 
6389 static int
6390 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6391 			uint32_t fwlog_buff_count)
6392 {
6393 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6394 	struct lpfc_dmabuf *dmabuf;
6395 	int rc = 0, i = 0;
6396 
6397 	/* Initialize List */
6398 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6399 
6400 	/* Allocate memory for the LWPD */
6401 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6402 					    sizeof(uint32_t) * 2,
6403 					    &ras_fwlog->lwpd.phys,
6404 					    GFP_KERNEL);
6405 	if (!ras_fwlog->lwpd.virt) {
6406 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6407 				"6185 LWPD Memory Alloc Failed\n");
6408 
6409 		return -ENOMEM;
6410 	}
6411 
6412 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6413 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6414 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6415 				 GFP_KERNEL);
6416 		if (!dmabuf) {
6417 			rc = -ENOMEM;
6418 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6419 					"6186 Memory Alloc failed FW logging");
6420 			goto free_mem;
6421 		}
6422 
6423 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6424 						  LPFC_RAS_MAX_ENTRY_SIZE,
6425 						  &dmabuf->phys, GFP_KERNEL);
6426 		if (!dmabuf->virt) {
6427 			kfree(dmabuf);
6428 			rc = -ENOMEM;
6429 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6430 					"6187 DMA Alloc Failed FW logging");
6431 			goto free_mem;
6432 		}
6433 		dmabuf->buffer_tag = i;
6434 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6435 	}
6436 
6437 free_mem:
6438 	if (rc)
6439 		lpfc_sli4_ras_dma_free(phba);
6440 
6441 	return rc;
6442 }
6443 
6444 /**
6445  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6446  * @phba: pointer to lpfc hba data structure.
6447  * @pmb: pointer to the driver internal queue element for mailbox command.
6448  *
6449  * Completion handler for driver's RAS MBX command to the device.
6450  **/
6451 static void
6452 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6453 {
6454 	MAILBOX_t *mb;
6455 	union lpfc_sli4_cfg_shdr *shdr;
6456 	uint32_t shdr_status, shdr_add_status;
6457 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6458 
6459 	mb = &pmb->u.mb;
6460 
6461 	shdr = (union lpfc_sli4_cfg_shdr *)
6462 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6463 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6464 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6465 
6466 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6467 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6468 				"6188 FW LOG mailbox "
6469 				"completed with status x%x add_status x%x,"
6470 				" mbx status x%x\n",
6471 				shdr_status, shdr_add_status, mb->mbxStatus);
6472 
6473 		ras_fwlog->ras_hwsupport = false;
6474 		goto disable_ras;
6475 	}
6476 
6477 	spin_lock_irq(&phba->hbalock);
6478 	ras_fwlog->state = ACTIVE;
6479 	spin_unlock_irq(&phba->hbalock);
6480 	mempool_free(pmb, phba->mbox_mem_pool);
6481 
6482 	return;
6483 
6484 disable_ras:
6485 	/* Free RAS DMA memory */
6486 	lpfc_sli4_ras_dma_free(phba);
6487 	mempool_free(pmb, phba->mbox_mem_pool);
6488 }
6489 
6490 /**
6491  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
6492  * @phba: pointer to lpfc hba data structure.
6493  * @fwlog_level: Logging verbosity level.
6494  * @fwlog_enable: Enable/Disable logging.
6495  *
6496  * Initialize memory and post mailbox command to enable FW logging in host
6497  * memory.
6498  **/
6499 int
6500 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
6501 			 uint32_t fwlog_level,
6502 			 uint32_t fwlog_enable)
6503 {
6504 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6505 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
6506 	struct lpfc_dmabuf *dmabuf;
6507 	LPFC_MBOXQ_t *mbox;
6508 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
6509 	int rc = 0;
6510 
6511 	spin_lock_irq(&phba->hbalock);
6512 	ras_fwlog->state = INACTIVE;
6513 	spin_unlock_irq(&phba->hbalock);
6514 
6515 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
6516 			  phba->cfg_ras_fwlog_buffsize);
6517 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
6518 
6519 	/*
6520 	 * If re-enabling FW logging support use earlier allocated
6521 	 * DMA buffers while posting MBX command.
6522 	 **/
6523 	if (!ras_fwlog->lwpd.virt) {
6524 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
6525 		if (rc) {
6526 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6527 					"6189 FW Log Memory Allocation Failed");
6528 			return rc;
6529 		}
6530 	}
6531 
6532 	/* Setup Mailbox command */
6533 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6534 	if (!mbox) {
6535 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6536 				"6190 RAS MBX Alloc Failed");
6537 		rc = -ENOMEM;
6538 		goto mem_free;
6539 	}
6540 
6541 	ras_fwlog->fw_loglevel = fwlog_level;
6542 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
6543 		sizeof(struct lpfc_sli4_cfg_mhdr));
6544 
6545 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
6546 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
6547 			 len, LPFC_SLI4_MBX_EMBED);
6548 
6549 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
6550 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
6551 	       fwlog_enable);
6552 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
6553 	       ras_fwlog->fw_loglevel);
6554 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
6555 	       ras_fwlog->fw_buffcount);
6556 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
6557 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
6558 
6559 	/* Update DMA buffer address */
6560 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
6561 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
6562 
6563 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
6564 			putPaddrLow(dmabuf->phys);
6565 
6566 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
6567 			putPaddrHigh(dmabuf->phys);
6568 	}
6569 
6570 	/* Update LPWD address */
6571 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
6572 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
6573 
6574 	spin_lock_irq(&phba->hbalock);
6575 	ras_fwlog->state = REG_INPROGRESS;
6576 	spin_unlock_irq(&phba->hbalock);
6577 	mbox->vport = phba->pport;
6578 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
6579 
6580 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
6581 
6582 	if (rc == MBX_NOT_FINISHED) {
6583 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6584 				"6191 FW-Log Mailbox failed. "
6585 				"status %d mbxStatus : x%x", rc,
6586 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
6587 		mempool_free(mbox, phba->mbox_mem_pool);
6588 		rc = -EIO;
6589 		goto mem_free;
6590 	} else
6591 		rc = 0;
6592 mem_free:
6593 	if (rc)
6594 		lpfc_sli4_ras_dma_free(phba);
6595 
6596 	return rc;
6597 }
6598 
6599 /**
6600  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
6601  * @phba: Pointer to HBA context object.
6602  *
6603  * Check if RAS is supported on the adapter and initialize it.
6604  **/
6605 void
6606 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
6607 {
6608 	/* Check RAS FW Log needs to be enabled or not */
6609 	if (lpfc_check_fwlog_support(phba))
6610 		return;
6611 
6612 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
6613 				 LPFC_RAS_ENABLE_LOGGING);
6614 }
6615 
6616 /**
6617  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
6618  * @phba: Pointer to HBA context object.
6619  *
6620  * This function allocates all SLI4 resource identifiers.
6621  **/
6622 int
6623 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
6624 {
6625 	int i, rc, error = 0;
6626 	uint16_t count, base;
6627 	unsigned long longs;
6628 
6629 	if (!phba->sli4_hba.rpi_hdrs_in_use)
6630 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
6631 	if (phba->sli4_hba.extents_in_use) {
6632 		/*
6633 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
6634 		 * resource extent count must be read and allocated before
6635 		 * provisioning the resource id arrays.
6636 		 */
6637 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6638 		    LPFC_IDX_RSRC_RDY) {
6639 			/*
6640 			 * Extent-based resources are set - the driver could
6641 			 * be in a port reset. Figure out if any corrective
6642 			 * actions need to be taken.
6643 			 */
6644 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6645 						 LPFC_RSC_TYPE_FCOE_VFI);
6646 			if (rc != 0)
6647 				error++;
6648 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6649 						 LPFC_RSC_TYPE_FCOE_VPI);
6650 			if (rc != 0)
6651 				error++;
6652 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6653 						 LPFC_RSC_TYPE_FCOE_XRI);
6654 			if (rc != 0)
6655 				error++;
6656 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6657 						 LPFC_RSC_TYPE_FCOE_RPI);
6658 			if (rc != 0)
6659 				error++;
6660 
6661 			/*
6662 			 * It's possible that the number of resources
6663 			 * provided to this port instance changed between
6664 			 * resets.  Detect this condition and reallocate
6665 			 * resources.  Otherwise, there is no action.
6666 			 */
6667 			if (error) {
6668 				lpfc_printf_log(phba, KERN_INFO,
6669 						LOG_MBOX | LOG_INIT,
6670 						"2931 Detected extent resource "
6671 						"change.  Reallocating all "
6672 						"extents.\n");
6673 				rc = lpfc_sli4_dealloc_extent(phba,
6674 						 LPFC_RSC_TYPE_FCOE_VFI);
6675 				rc = lpfc_sli4_dealloc_extent(phba,
6676 						 LPFC_RSC_TYPE_FCOE_VPI);
6677 				rc = lpfc_sli4_dealloc_extent(phba,
6678 						 LPFC_RSC_TYPE_FCOE_XRI);
6679 				rc = lpfc_sli4_dealloc_extent(phba,
6680 						 LPFC_RSC_TYPE_FCOE_RPI);
6681 			} else
6682 				return 0;
6683 		}
6684 
6685 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6686 		if (unlikely(rc))
6687 			goto err_exit;
6688 
6689 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6690 		if (unlikely(rc))
6691 			goto err_exit;
6692 
6693 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6694 		if (unlikely(rc))
6695 			goto err_exit;
6696 
6697 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6698 		if (unlikely(rc))
6699 			goto err_exit;
6700 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6701 		       LPFC_IDX_RSRC_RDY);
6702 		return rc;
6703 	} else {
6704 		/*
6705 		 * The port does not support resource extents.  The XRI, VPI,
6706 		 * VFI, RPI resource ids were determined from READ_CONFIG.
6707 		 * Just allocate the bitmasks and provision the resource id
6708 		 * arrays.  If a port reset is active, the resources don't
6709 		 * need any action - just exit.
6710 		 */
6711 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6712 		    LPFC_IDX_RSRC_RDY) {
6713 			lpfc_sli4_dealloc_resource_identifiers(phba);
6714 			lpfc_sli4_remove_rpis(phba);
6715 		}
6716 		/* RPIs. */
6717 		count = phba->sli4_hba.max_cfg_param.max_rpi;
6718 		if (count <= 0) {
6719 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6720 					"3279 Invalid provisioning of "
6721 					"rpi:%d\n", count);
6722 			rc = -EINVAL;
6723 			goto err_exit;
6724 		}
6725 		base = phba->sli4_hba.max_cfg_param.rpi_base;
6726 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6727 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6728 						   sizeof(unsigned long),
6729 						   GFP_KERNEL);
6730 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6731 			rc = -ENOMEM;
6732 			goto err_exit;
6733 		}
6734 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
6735 						 GFP_KERNEL);
6736 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6737 			rc = -ENOMEM;
6738 			goto free_rpi_bmask;
6739 		}
6740 
6741 		for (i = 0; i < count; i++)
6742 			phba->sli4_hba.rpi_ids[i] = base + i;
6743 
6744 		/* VPIs. */
6745 		count = phba->sli4_hba.max_cfg_param.max_vpi;
6746 		if (count <= 0) {
6747 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6748 					"3280 Invalid provisioning of "
6749 					"vpi:%d\n", count);
6750 			rc = -EINVAL;
6751 			goto free_rpi_ids;
6752 		}
6753 		base = phba->sli4_hba.max_cfg_param.vpi_base;
6754 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6755 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6756 					  GFP_KERNEL);
6757 		if (unlikely(!phba->vpi_bmask)) {
6758 			rc = -ENOMEM;
6759 			goto free_rpi_ids;
6760 		}
6761 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
6762 					GFP_KERNEL);
6763 		if (unlikely(!phba->vpi_ids)) {
6764 			rc = -ENOMEM;
6765 			goto free_vpi_bmask;
6766 		}
6767 
6768 		for (i = 0; i < count; i++)
6769 			phba->vpi_ids[i] = base + i;
6770 
6771 		/* XRIs. */
6772 		count = phba->sli4_hba.max_cfg_param.max_xri;
6773 		if (count <= 0) {
6774 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6775 					"3281 Invalid provisioning of "
6776 					"xri:%d\n", count);
6777 			rc = -EINVAL;
6778 			goto free_vpi_ids;
6779 		}
6780 		base = phba->sli4_hba.max_cfg_param.xri_base;
6781 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6782 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6783 						   sizeof(unsigned long),
6784 						   GFP_KERNEL);
6785 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6786 			rc = -ENOMEM;
6787 			goto free_vpi_ids;
6788 		}
6789 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6790 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
6791 						 GFP_KERNEL);
6792 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6793 			rc = -ENOMEM;
6794 			goto free_xri_bmask;
6795 		}
6796 
6797 		for (i = 0; i < count; i++)
6798 			phba->sli4_hba.xri_ids[i] = base + i;
6799 
6800 		/* VFIs. */
6801 		count = phba->sli4_hba.max_cfg_param.max_vfi;
6802 		if (count <= 0) {
6803 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6804 					"3282 Invalid provisioning of "
6805 					"vfi:%d\n", count);
6806 			rc = -EINVAL;
6807 			goto free_xri_ids;
6808 		}
6809 		base = phba->sli4_hba.max_cfg_param.vfi_base;
6810 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6811 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6812 						   sizeof(unsigned long),
6813 						   GFP_KERNEL);
6814 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6815 			rc = -ENOMEM;
6816 			goto free_xri_ids;
6817 		}
6818 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
6819 						 GFP_KERNEL);
6820 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6821 			rc = -ENOMEM;
6822 			goto free_vfi_bmask;
6823 		}
6824 
6825 		for (i = 0; i < count; i++)
6826 			phba->sli4_hba.vfi_ids[i] = base + i;
6827 
6828 		/*
6829 		 * Mark all resources ready.  An HBA reset doesn't need
6830 		 * to reset the initialization.
6831 		 */
6832 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6833 		       LPFC_IDX_RSRC_RDY);
6834 		return 0;
6835 	}
6836 
6837  free_vfi_bmask:
6838 	kfree(phba->sli4_hba.vfi_bmask);
6839 	phba->sli4_hba.vfi_bmask = NULL;
6840  free_xri_ids:
6841 	kfree(phba->sli4_hba.xri_ids);
6842 	phba->sli4_hba.xri_ids = NULL;
6843  free_xri_bmask:
6844 	kfree(phba->sli4_hba.xri_bmask);
6845 	phba->sli4_hba.xri_bmask = NULL;
6846  free_vpi_ids:
6847 	kfree(phba->vpi_ids);
6848 	phba->vpi_ids = NULL;
6849  free_vpi_bmask:
6850 	kfree(phba->vpi_bmask);
6851 	phba->vpi_bmask = NULL;
6852  free_rpi_ids:
6853 	kfree(phba->sli4_hba.rpi_ids);
6854 	phba->sli4_hba.rpi_ids = NULL;
6855  free_rpi_bmask:
6856 	kfree(phba->sli4_hba.rpi_bmask);
6857 	phba->sli4_hba.rpi_bmask = NULL;
6858  err_exit:
6859 	return rc;
6860 }
6861 
6862 /**
6863  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
6864  * @phba: Pointer to HBA context object.
6865  *
6866  * This function allocates the number of elements for the specified
6867  * resource type.
6868  **/
6869 int
6870 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
6871 {
6872 	if (phba->sli4_hba.extents_in_use) {
6873 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6874 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6875 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6876 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6877 	} else {
6878 		kfree(phba->vpi_bmask);
6879 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6880 		kfree(phba->vpi_ids);
6881 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6882 		kfree(phba->sli4_hba.xri_bmask);
6883 		kfree(phba->sli4_hba.xri_ids);
6884 		kfree(phba->sli4_hba.vfi_bmask);
6885 		kfree(phba->sli4_hba.vfi_ids);
6886 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6887 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6888 	}
6889 
6890 	return 0;
6891 }
6892 
6893 /**
6894  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
6895  * @phba: Pointer to HBA context object.
6896  * @type: The resource extent type.
6897  * @extnt_cnt: buffer to hold port extent count response
6898  * @extnt_size: buffer to hold port extent size response.
6899  *
6900  * This function calls the port to read the host allocated extents
6901  * for a particular type.
6902  **/
6903 int
6904 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
6905 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
6906 {
6907 	bool emb;
6908 	int rc = 0;
6909 	uint16_t curr_blks = 0;
6910 	uint32_t req_len, emb_len;
6911 	uint32_t alloc_len, mbox_tmo;
6912 	struct list_head *blk_list_head;
6913 	struct lpfc_rsrc_blks *rsrc_blk;
6914 	LPFC_MBOXQ_t *mbox;
6915 	void *virtaddr = NULL;
6916 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6917 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6918 	union  lpfc_sli4_cfg_shdr *shdr;
6919 
6920 	switch (type) {
6921 	case LPFC_RSC_TYPE_FCOE_VPI:
6922 		blk_list_head = &phba->lpfc_vpi_blk_list;
6923 		break;
6924 	case LPFC_RSC_TYPE_FCOE_XRI:
6925 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
6926 		break;
6927 	case LPFC_RSC_TYPE_FCOE_VFI:
6928 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
6929 		break;
6930 	case LPFC_RSC_TYPE_FCOE_RPI:
6931 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
6932 		break;
6933 	default:
6934 		return -EIO;
6935 	}
6936 
6937 	/* Count the number of extents currently allocatd for this type. */
6938 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
6939 		if (curr_blks == 0) {
6940 			/*
6941 			 * The GET_ALLOCATED mailbox does not return the size,
6942 			 * just the count.  The size should be just the size
6943 			 * stored in the current allocated block and all sizes
6944 			 * for an extent type are the same so set the return
6945 			 * value now.
6946 			 */
6947 			*extnt_size = rsrc_blk->rsrc_size;
6948 		}
6949 		curr_blks++;
6950 	}
6951 
6952 	/*
6953 	 * Calculate the size of an embedded mailbox.  The uint32_t
6954 	 * accounts for extents-specific word.
6955 	 */
6956 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6957 		sizeof(uint32_t);
6958 
6959 	/*
6960 	 * Presume the allocation and response will fit into an embedded
6961 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6962 	 */
6963 	emb = LPFC_SLI4_MBX_EMBED;
6964 	req_len = emb_len;
6965 	if (req_len > emb_len) {
6966 		req_len = curr_blks * sizeof(uint16_t) +
6967 			sizeof(union lpfc_sli4_cfg_shdr) +
6968 			sizeof(uint32_t);
6969 		emb = LPFC_SLI4_MBX_NEMBED;
6970 	}
6971 
6972 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6973 	if (!mbox)
6974 		return -ENOMEM;
6975 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
6976 
6977 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6978 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
6979 				     req_len, emb);
6980 	if (alloc_len < req_len) {
6981 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6982 			"2983 Allocated DMA memory size (x%x) is "
6983 			"less than the requested DMA memory "
6984 			"size (x%x)\n", alloc_len, req_len);
6985 		rc = -ENOMEM;
6986 		goto err_exit;
6987 	}
6988 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
6989 	if (unlikely(rc)) {
6990 		rc = -EIO;
6991 		goto err_exit;
6992 	}
6993 
6994 	if (!phba->sli4_hba.intr_enable)
6995 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6996 	else {
6997 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6998 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6999 	}
7000 
7001 	if (unlikely(rc)) {
7002 		rc = -EIO;
7003 		goto err_exit;
7004 	}
7005 
7006 	/*
7007 	 * Figure out where the response is located.  Then get local pointers
7008 	 * to the response data.  The port does not guarantee to respond to
7009 	 * all extents counts request so update the local variable with the
7010 	 * allocated count from the port.
7011 	 */
7012 	if (emb == LPFC_SLI4_MBX_EMBED) {
7013 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7014 		shdr = &rsrc_ext->header.cfg_shdr;
7015 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7016 	} else {
7017 		virtaddr = mbox->sge_array->addr[0];
7018 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7019 		shdr = &n_rsrc->cfg_shdr;
7020 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7021 	}
7022 
7023 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7024 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7025 			"2984 Failed to read allocated resources "
7026 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7027 			type,
7028 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7029 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7030 		rc = -EIO;
7031 		goto err_exit;
7032 	}
7033  err_exit:
7034 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7035 	return rc;
7036 }
7037 
7038 /**
7039  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7040  * @phba: pointer to lpfc hba data structure.
7041  * @sgl_list: linked link of sgl buffers to post
7042  * @cnt: number of linked list buffers
7043  *
7044  * This routine walks the list of buffers that have been allocated and
7045  * repost them to the port by using SGL block post. This is needed after a
7046  * pci_function_reset/warm_start or start. It attempts to construct blocks
7047  * of buffer sgls which contains contiguous xris and uses the non-embedded
7048  * SGL block post mailbox commands to post them to the port. For single
7049  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7050  * mailbox command for posting.
7051  *
7052  * Returns: 0 = success, non-zero failure.
7053  **/
7054 static int
7055 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7056 			  struct list_head *sgl_list, int cnt)
7057 {
7058 	struct lpfc_sglq *sglq_entry = NULL;
7059 	struct lpfc_sglq *sglq_entry_next = NULL;
7060 	struct lpfc_sglq *sglq_entry_first = NULL;
7061 	int status, total_cnt;
7062 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7063 	int last_xritag = NO_XRI;
7064 	LIST_HEAD(prep_sgl_list);
7065 	LIST_HEAD(blck_sgl_list);
7066 	LIST_HEAD(allc_sgl_list);
7067 	LIST_HEAD(post_sgl_list);
7068 	LIST_HEAD(free_sgl_list);
7069 
7070 	spin_lock_irq(&phba->hbalock);
7071 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7072 	list_splice_init(sgl_list, &allc_sgl_list);
7073 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7074 	spin_unlock_irq(&phba->hbalock);
7075 
7076 	total_cnt = cnt;
7077 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7078 				 &allc_sgl_list, list) {
7079 		list_del_init(&sglq_entry->list);
7080 		block_cnt++;
7081 		if ((last_xritag != NO_XRI) &&
7082 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7083 			/* a hole in xri block, form a sgl posting block */
7084 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7085 			post_cnt = block_cnt - 1;
7086 			/* prepare list for next posting block */
7087 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7088 			block_cnt = 1;
7089 		} else {
7090 			/* prepare list for next posting block */
7091 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7092 			/* enough sgls for non-embed sgl mbox command */
7093 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7094 				list_splice_init(&prep_sgl_list,
7095 						 &blck_sgl_list);
7096 				post_cnt = block_cnt;
7097 				block_cnt = 0;
7098 			}
7099 		}
7100 		num_posted++;
7101 
7102 		/* keep track of last sgl's xritag */
7103 		last_xritag = sglq_entry->sli4_xritag;
7104 
7105 		/* end of repost sgl list condition for buffers */
7106 		if (num_posted == total_cnt) {
7107 			if (post_cnt == 0) {
7108 				list_splice_init(&prep_sgl_list,
7109 						 &blck_sgl_list);
7110 				post_cnt = block_cnt;
7111 			} else if (block_cnt == 1) {
7112 				status = lpfc_sli4_post_sgl(phba,
7113 						sglq_entry->phys, 0,
7114 						sglq_entry->sli4_xritag);
7115 				if (!status) {
7116 					/* successful, put sgl to posted list */
7117 					list_add_tail(&sglq_entry->list,
7118 						      &post_sgl_list);
7119 				} else {
7120 					/* Failure, put sgl to free list */
7121 					lpfc_printf_log(phba, KERN_WARNING,
7122 						LOG_SLI,
7123 						"3159 Failed to post "
7124 						"sgl, xritag:x%x\n",
7125 						sglq_entry->sli4_xritag);
7126 					list_add_tail(&sglq_entry->list,
7127 						      &free_sgl_list);
7128 					total_cnt--;
7129 				}
7130 			}
7131 		}
7132 
7133 		/* continue until a nembed page worth of sgls */
7134 		if (post_cnt == 0)
7135 			continue;
7136 
7137 		/* post the buffer list sgls as a block */
7138 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7139 						 post_cnt);
7140 
7141 		if (!status) {
7142 			/* success, put sgl list to posted sgl list */
7143 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7144 		} else {
7145 			/* Failure, put sgl list to free sgl list */
7146 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7147 							    struct lpfc_sglq,
7148 							    list);
7149 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7150 					"3160 Failed to post sgl-list, "
7151 					"xritag:x%x-x%x\n",
7152 					sglq_entry_first->sli4_xritag,
7153 					(sglq_entry_first->sli4_xritag +
7154 					 post_cnt - 1));
7155 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7156 			total_cnt -= post_cnt;
7157 		}
7158 
7159 		/* don't reset xirtag due to hole in xri block */
7160 		if (block_cnt == 0)
7161 			last_xritag = NO_XRI;
7162 
7163 		/* reset sgl post count for next round of posting */
7164 		post_cnt = 0;
7165 	}
7166 
7167 	/* free the sgls failed to post */
7168 	lpfc_free_sgl_list(phba, &free_sgl_list);
7169 
7170 	/* push sgls posted to the available list */
7171 	if (!list_empty(&post_sgl_list)) {
7172 		spin_lock_irq(&phba->hbalock);
7173 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7174 		list_splice_init(&post_sgl_list, sgl_list);
7175 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7176 		spin_unlock_irq(&phba->hbalock);
7177 	} else {
7178 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7179 				"3161 Failure to post sgl to port.\n");
7180 		return -EIO;
7181 	}
7182 
7183 	/* return the number of XRIs actually posted */
7184 	return total_cnt;
7185 }
7186 
7187 /**
7188  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7189  * @phba: pointer to lpfc hba data structure.
7190  *
7191  * This routine walks the list of nvme buffers that have been allocated and
7192  * repost them to the port by using SGL block post. This is needed after a
7193  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7194  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7195  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7196  *
7197  * Returns: 0 = success, non-zero failure.
7198  **/
7199 static int
7200 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7201 {
7202 	LIST_HEAD(post_nblist);
7203 	int num_posted, rc = 0;
7204 
7205 	/* get all NVME buffers need to repost to a local list */
7206 	lpfc_io_buf_flush(phba, &post_nblist);
7207 
7208 	/* post the list of nvme buffer sgls to port if available */
7209 	if (!list_empty(&post_nblist)) {
7210 		num_posted = lpfc_sli4_post_io_sgl_list(
7211 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7212 		/* failed to post any nvme buffer, return error */
7213 		if (num_posted == 0)
7214 			rc = -EIO;
7215 	}
7216 	return rc;
7217 }
7218 
7219 static void
7220 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7221 {
7222 	uint32_t len;
7223 
7224 	len = sizeof(struct lpfc_mbx_set_host_data) -
7225 		sizeof(struct lpfc_sli4_cfg_mhdr);
7226 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7227 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7228 			 LPFC_SLI4_MBX_EMBED);
7229 
7230 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7231 	mbox->u.mqe.un.set_host_data.param_len =
7232 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7233 	snprintf(mbox->u.mqe.un.set_host_data.data,
7234 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7235 		 "Linux %s v"LPFC_DRIVER_VERSION,
7236 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7237 }
7238 
7239 int
7240 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7241 		    struct lpfc_queue *drq, int count, int idx)
7242 {
7243 	int rc, i;
7244 	struct lpfc_rqe hrqe;
7245 	struct lpfc_rqe drqe;
7246 	struct lpfc_rqb *rqbp;
7247 	unsigned long flags;
7248 	struct rqb_dmabuf *rqb_buffer;
7249 	LIST_HEAD(rqb_buf_list);
7250 
7251 	spin_lock_irqsave(&phba->hbalock, flags);
7252 	rqbp = hrq->rqbp;
7253 	for (i = 0; i < count; i++) {
7254 		/* IF RQ is already full, don't bother */
7255 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1)
7256 			break;
7257 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7258 		if (!rqb_buffer)
7259 			break;
7260 		rqb_buffer->hrq = hrq;
7261 		rqb_buffer->drq = drq;
7262 		rqb_buffer->idx = idx;
7263 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7264 	}
7265 	while (!list_empty(&rqb_buf_list)) {
7266 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7267 				 hbuf.list);
7268 
7269 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7270 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7271 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7272 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7273 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7274 		if (rc < 0) {
7275 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7276 					"6421 Cannot post to HRQ %d: %x %x %x "
7277 					"DRQ %x %x\n",
7278 					hrq->queue_id,
7279 					hrq->host_index,
7280 					hrq->hba_index,
7281 					hrq->entry_count,
7282 					drq->host_index,
7283 					drq->hba_index);
7284 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7285 		} else {
7286 			list_add_tail(&rqb_buffer->hbuf.list,
7287 				      &rqbp->rqb_buffer_list);
7288 			rqbp->buffer_count++;
7289 		}
7290 	}
7291 	spin_unlock_irqrestore(&phba->hbalock, flags);
7292 	return 1;
7293 }
7294 
7295 /**
7296  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7297  * @phba: pointer to lpfc hba data structure.
7298  *
7299  * This routine initializes the per-cq idle_stat to dynamically dictate
7300  * polling decisions.
7301  *
7302  * Return codes:
7303  *   None
7304  **/
7305 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
7306 {
7307 	int i;
7308 	struct lpfc_sli4_hdw_queue *hdwq;
7309 	struct lpfc_queue *cq;
7310 	struct lpfc_idle_stat *idle_stat;
7311 	u64 wall;
7312 
7313 	for_each_present_cpu(i) {
7314 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
7315 		cq = hdwq->io_cq;
7316 
7317 		/* Skip if we've already handled this cq's primary CPU */
7318 		if (cq->chann != i)
7319 			continue;
7320 
7321 		idle_stat = &phba->sli4_hba.idle_stat[i];
7322 
7323 		idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
7324 		idle_stat->prev_wall = wall;
7325 
7326 		if (phba->nvmet_support)
7327 			cq->poll_mode = LPFC_QUEUE_WORK;
7328 		else
7329 			cq->poll_mode = LPFC_IRQ_POLL;
7330 	}
7331 
7332 	if (!phba->nvmet_support)
7333 		schedule_delayed_work(&phba->idle_stat_delay_work,
7334 				      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
7335 }
7336 
7337 static void lpfc_sli4_dip(struct lpfc_hba *phba)
7338 {
7339 	uint32_t if_type;
7340 
7341 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
7342 	if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
7343 	    if_type == LPFC_SLI_INTF_IF_TYPE_6) {
7344 		struct lpfc_register reg_data;
7345 
7346 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
7347 			       &reg_data.word0))
7348 			return;
7349 
7350 		if (bf_get(lpfc_sliport_status_dip, &reg_data))
7351 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7352 					"2904 Firmware Dump Image Present"
7353 					" on Adapter");
7354 	}
7355 }
7356 
7357 /**
7358  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
7359  * @phba: Pointer to HBA context object.
7360  *
7361  * This function is the main SLI4 device initialization PCI function. This
7362  * function is called by the HBA initialization code, HBA reset code and
7363  * HBA error attention handler code. Caller is not required to hold any
7364  * locks.
7365  **/
7366 int
7367 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
7368 {
7369 	int rc, i, cnt, len, dd;
7370 	LPFC_MBOXQ_t *mboxq;
7371 	struct lpfc_mqe *mqe;
7372 	uint8_t *vpd;
7373 	uint32_t vpd_size;
7374 	uint32_t ftr_rsp = 0;
7375 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
7376 	struct lpfc_vport *vport = phba->pport;
7377 	struct lpfc_dmabuf *mp;
7378 	struct lpfc_rqb *rqbp;
7379 
7380 	/* Perform a PCI function reset to start from clean */
7381 	rc = lpfc_pci_function_reset(phba);
7382 	if (unlikely(rc))
7383 		return -ENODEV;
7384 
7385 	/* Check the HBA Host Status Register for readyness */
7386 	rc = lpfc_sli4_post_status_check(phba);
7387 	if (unlikely(rc))
7388 		return -ENODEV;
7389 	else {
7390 		spin_lock_irq(&phba->hbalock);
7391 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
7392 		spin_unlock_irq(&phba->hbalock);
7393 	}
7394 
7395 	lpfc_sli4_dip(phba);
7396 
7397 	/*
7398 	 * Allocate a single mailbox container for initializing the
7399 	 * port.
7400 	 */
7401 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7402 	if (!mboxq)
7403 		return -ENOMEM;
7404 
7405 	/* Issue READ_REV to collect vpd and FW information. */
7406 	vpd_size = SLI4_PAGE_SIZE;
7407 	vpd = kzalloc(vpd_size, GFP_KERNEL);
7408 	if (!vpd) {
7409 		rc = -ENOMEM;
7410 		goto out_free_mbox;
7411 	}
7412 
7413 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
7414 	if (unlikely(rc)) {
7415 		kfree(vpd);
7416 		goto out_free_mbox;
7417 	}
7418 
7419 	mqe = &mboxq->u.mqe;
7420 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
7421 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
7422 		phba->hba_flag |= HBA_FCOE_MODE;
7423 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
7424 	} else {
7425 		phba->hba_flag &= ~HBA_FCOE_MODE;
7426 	}
7427 
7428 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
7429 		LPFC_DCBX_CEE_MODE)
7430 		phba->hba_flag |= HBA_FIP_SUPPORT;
7431 	else
7432 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
7433 
7434 	phba->hba_flag &= ~HBA_IOQ_FLUSH;
7435 
7436 	if (phba->sli_rev != LPFC_SLI_REV4) {
7437 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7438 			"0376 READ_REV Error. SLI Level %d "
7439 			"FCoE enabled %d\n",
7440 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
7441 		rc = -EIO;
7442 		kfree(vpd);
7443 		goto out_free_mbox;
7444 	}
7445 
7446 	/*
7447 	 * Continue initialization with default values even if driver failed
7448 	 * to read FCoE param config regions, only read parameters if the
7449 	 * board is FCoE
7450 	 */
7451 	if (phba->hba_flag & HBA_FCOE_MODE &&
7452 	    lpfc_sli4_read_fcoe_params(phba))
7453 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
7454 			"2570 Failed to read FCoE parameters\n");
7455 
7456 	/*
7457 	 * Retrieve sli4 device physical port name, failure of doing it
7458 	 * is considered as non-fatal.
7459 	 */
7460 	rc = lpfc_sli4_retrieve_pport_name(phba);
7461 	if (!rc)
7462 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7463 				"3080 Successful retrieving SLI4 device "
7464 				"physical port name: %s.\n", phba->Port);
7465 
7466 	rc = lpfc_sli4_get_ctl_attr(phba);
7467 	if (!rc)
7468 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7469 				"8351 Successful retrieving SLI4 device "
7470 				"CTL ATTR\n");
7471 
7472 	/*
7473 	 * Evaluate the read rev and vpd data. Populate the driver
7474 	 * state with the results. If this routine fails, the failure
7475 	 * is not fatal as the driver will use generic values.
7476 	 */
7477 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
7478 	if (unlikely(!rc)) {
7479 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7480 				"0377 Error %d parsing vpd. "
7481 				"Using defaults.\n", rc);
7482 		rc = 0;
7483 	}
7484 	kfree(vpd);
7485 
7486 	/* Save information as VPD data */
7487 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
7488 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
7489 
7490 	/*
7491 	 * This is because first G7 ASIC doesn't support the standard
7492 	 * 0x5a NVME cmd descriptor type/subtype
7493 	 */
7494 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7495 			LPFC_SLI_INTF_IF_TYPE_6) &&
7496 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
7497 	    (phba->vpd.rev.smRev == 0) &&
7498 	    (phba->cfg_nvme_embed_cmd == 1))
7499 		phba->cfg_nvme_embed_cmd = 0;
7500 
7501 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
7502 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
7503 					 &mqe->un.read_rev);
7504 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
7505 				       &mqe->un.read_rev);
7506 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
7507 					    &mqe->un.read_rev);
7508 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
7509 					   &mqe->un.read_rev);
7510 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
7511 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
7512 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
7513 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
7514 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
7515 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
7516 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7517 			"(%d):0380 READ_REV Status x%x "
7518 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
7519 			mboxq->vport ? mboxq->vport->vpi : 0,
7520 			bf_get(lpfc_mqe_status, mqe),
7521 			phba->vpd.rev.opFwName,
7522 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
7523 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
7524 
7525 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7526 	    LPFC_SLI_INTF_IF_TYPE_0) {
7527 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
7528 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7529 		if (rc == MBX_SUCCESS) {
7530 			phba->hba_flag |= HBA_RECOVERABLE_UE;
7531 			/* Set 1Sec interval to detect UE */
7532 			phba->eratt_poll_interval = 1;
7533 			phba->sli4_hba.ue_to_sr = bf_get(
7534 					lpfc_mbx_set_feature_UESR,
7535 					&mboxq->u.mqe.un.set_feature);
7536 			phba->sli4_hba.ue_to_rp = bf_get(
7537 					lpfc_mbx_set_feature_UERP,
7538 					&mboxq->u.mqe.un.set_feature);
7539 		}
7540 	}
7541 
7542 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
7543 		/* Enable MDS Diagnostics only if the SLI Port supports it */
7544 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
7545 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7546 		if (rc != MBX_SUCCESS)
7547 			phba->mds_diags_support = 0;
7548 	}
7549 
7550 	/*
7551 	 * Discover the port's supported feature set and match it against the
7552 	 * hosts requests.
7553 	 */
7554 	lpfc_request_features(phba, mboxq);
7555 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7556 	if (unlikely(rc)) {
7557 		rc = -EIO;
7558 		goto out_free_mbox;
7559 	}
7560 
7561 	/*
7562 	 * The port must support FCP initiator mode as this is the
7563 	 * only mode running in the host.
7564 	 */
7565 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
7566 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7567 				"0378 No support for fcpi mode.\n");
7568 		ftr_rsp++;
7569 	}
7570 
7571 	/* Performance Hints are ONLY for FCoE */
7572 	if (phba->hba_flag & HBA_FCOE_MODE) {
7573 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
7574 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
7575 		else
7576 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
7577 	}
7578 
7579 	/*
7580 	 * If the port cannot support the host's requested features
7581 	 * then turn off the global config parameters to disable the
7582 	 * feature in the driver.  This is not a fatal error.
7583 	 */
7584 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
7585 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
7586 			phba->cfg_enable_bg = 0;
7587 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
7588 			ftr_rsp++;
7589 		}
7590 	}
7591 
7592 	if (phba->max_vpi && phba->cfg_enable_npiv &&
7593 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7594 		ftr_rsp++;
7595 
7596 	if (ftr_rsp) {
7597 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7598 				"0379 Feature Mismatch Data: x%08x %08x "
7599 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
7600 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
7601 				phba->cfg_enable_npiv, phba->max_vpi);
7602 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
7603 			phba->cfg_enable_bg = 0;
7604 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7605 			phba->cfg_enable_npiv = 0;
7606 	}
7607 
7608 	/* These SLI3 features are assumed in SLI4 */
7609 	spin_lock_irq(&phba->hbalock);
7610 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
7611 	spin_unlock_irq(&phba->hbalock);
7612 
7613 	/* Always try to enable dual dump feature if we can */
7614 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
7615 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7616 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
7617 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
7618 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7619 				"6448 Dual Dump is enabled\n");
7620 	else
7621 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
7622 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
7623 				"rc:x%x dd:x%x\n",
7624 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7625 				lpfc_sli_config_mbox_subsys_get(
7626 					phba, mboxq),
7627 				lpfc_sli_config_mbox_opcode_get(
7628 					phba, mboxq),
7629 				rc, dd);
7630 	/*
7631 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
7632 	 * calls depends on these resources to complete port setup.
7633 	 */
7634 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
7635 	if (rc) {
7636 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7637 				"2920 Failed to alloc Resource IDs "
7638 				"rc = x%x\n", rc);
7639 		goto out_free_mbox;
7640 	}
7641 
7642 	lpfc_set_host_data(phba, mboxq);
7643 
7644 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7645 	if (rc) {
7646 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7647 				"2134 Failed to set host os driver version %x",
7648 				rc);
7649 	}
7650 
7651 	/* Read the port's service parameters. */
7652 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
7653 	if (rc) {
7654 		phba->link_state = LPFC_HBA_ERROR;
7655 		rc = -ENOMEM;
7656 		goto out_free_mbox;
7657 	}
7658 
7659 	mboxq->vport = vport;
7660 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7661 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
7662 	if (rc == MBX_SUCCESS) {
7663 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
7664 		rc = 0;
7665 	}
7666 
7667 	/*
7668 	 * This memory was allocated by the lpfc_read_sparam routine. Release
7669 	 * it to the mbuf pool.
7670 	 */
7671 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
7672 	kfree(mp);
7673 	mboxq->ctx_buf = NULL;
7674 	if (unlikely(rc)) {
7675 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7676 				"0382 READ_SPARAM command failed "
7677 				"status %d, mbxStatus x%x\n",
7678 				rc, bf_get(lpfc_mqe_status, mqe));
7679 		phba->link_state = LPFC_HBA_ERROR;
7680 		rc = -EIO;
7681 		goto out_free_mbox;
7682 	}
7683 
7684 	lpfc_update_vport_wwn(vport);
7685 
7686 	/* Update the fc_host data structures with new wwn. */
7687 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
7688 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
7689 
7690 	/* Create all the SLI4 queues */
7691 	rc = lpfc_sli4_queue_create(phba);
7692 	if (rc) {
7693 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7694 				"3089 Failed to allocate queues\n");
7695 		rc = -ENODEV;
7696 		goto out_free_mbox;
7697 	}
7698 	/* Set up all the queues to the device */
7699 	rc = lpfc_sli4_queue_setup(phba);
7700 	if (unlikely(rc)) {
7701 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7702 				"0381 Error %d during queue setup.\n ", rc);
7703 		goto out_stop_timers;
7704 	}
7705 	/* Initialize the driver internal SLI layer lists. */
7706 	lpfc_sli4_setup(phba);
7707 	lpfc_sli4_queue_init(phba);
7708 
7709 	/* update host els xri-sgl sizes and mappings */
7710 	rc = lpfc_sli4_els_sgl_update(phba);
7711 	if (unlikely(rc)) {
7712 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7713 				"1400 Failed to update xri-sgl size and "
7714 				"mapping: %d\n", rc);
7715 		goto out_destroy_queue;
7716 	}
7717 
7718 	/* register the els sgl pool to the port */
7719 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
7720 				       phba->sli4_hba.els_xri_cnt);
7721 	if (unlikely(rc < 0)) {
7722 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7723 				"0582 Error %d during els sgl post "
7724 				"operation\n", rc);
7725 		rc = -ENODEV;
7726 		goto out_destroy_queue;
7727 	}
7728 	phba->sli4_hba.els_xri_cnt = rc;
7729 
7730 	if (phba->nvmet_support) {
7731 		/* update host nvmet xri-sgl sizes and mappings */
7732 		rc = lpfc_sli4_nvmet_sgl_update(phba);
7733 		if (unlikely(rc)) {
7734 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7735 					"6308 Failed to update nvmet-sgl size "
7736 					"and mapping: %d\n", rc);
7737 			goto out_destroy_queue;
7738 		}
7739 
7740 		/* register the nvmet sgl pool to the port */
7741 		rc = lpfc_sli4_repost_sgl_list(
7742 			phba,
7743 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
7744 			phba->sli4_hba.nvmet_xri_cnt);
7745 		if (unlikely(rc < 0)) {
7746 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7747 					"3117 Error %d during nvmet "
7748 					"sgl post\n", rc);
7749 			rc = -ENODEV;
7750 			goto out_destroy_queue;
7751 		}
7752 		phba->sli4_hba.nvmet_xri_cnt = rc;
7753 
7754 		/* We allocate an iocbq for every receive context SGL.
7755 		 * The additional allocation is for abort and ls handling.
7756 		 */
7757 		cnt = phba->sli4_hba.nvmet_xri_cnt +
7758 			phba->sli4_hba.max_cfg_param.max_xri;
7759 	} else {
7760 		/* update host common xri-sgl sizes and mappings */
7761 		rc = lpfc_sli4_io_sgl_update(phba);
7762 		if (unlikely(rc)) {
7763 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7764 					"6082 Failed to update nvme-sgl size "
7765 					"and mapping: %d\n", rc);
7766 			goto out_destroy_queue;
7767 		}
7768 
7769 		/* register the allocated common sgl pool to the port */
7770 		rc = lpfc_sli4_repost_io_sgl_list(phba);
7771 		if (unlikely(rc)) {
7772 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7773 					"6116 Error %d during nvme sgl post "
7774 					"operation\n", rc);
7775 			/* Some NVME buffers were moved to abort nvme list */
7776 			/* A pci function reset will repost them */
7777 			rc = -ENODEV;
7778 			goto out_destroy_queue;
7779 		}
7780 		/* Each lpfc_io_buf job structure has an iocbq element.
7781 		 * This cnt provides for abort, els, ct and ls requests.
7782 		 */
7783 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
7784 	}
7785 
7786 	if (!phba->sli.iocbq_lookup) {
7787 		/* Initialize and populate the iocb list per host */
7788 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7789 				"2821 initialize iocb list with %d entries\n",
7790 				cnt);
7791 		rc = lpfc_init_iocb_list(phba, cnt);
7792 		if (rc) {
7793 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7794 					"1413 Failed to init iocb list.\n");
7795 			goto out_destroy_queue;
7796 		}
7797 	}
7798 
7799 	if (phba->nvmet_support)
7800 		lpfc_nvmet_create_targetport(phba);
7801 
7802 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
7803 		/* Post initial buffers to all RQs created */
7804 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
7805 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
7806 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
7807 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
7808 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
7809 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
7810 			rqbp->buffer_count = 0;
7811 
7812 			lpfc_post_rq_buffer(
7813 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
7814 				phba->sli4_hba.nvmet_mrq_data[i],
7815 				phba->cfg_nvmet_mrq_post, i);
7816 		}
7817 	}
7818 
7819 	/* Post the rpi header region to the device. */
7820 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
7821 	if (unlikely(rc)) {
7822 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7823 				"0393 Error %d during rpi post operation\n",
7824 				rc);
7825 		rc = -ENODEV;
7826 		goto out_destroy_queue;
7827 	}
7828 	lpfc_sli4_node_prep(phba);
7829 
7830 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
7831 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
7832 			/*
7833 			 * The FC Port needs to register FCFI (index 0)
7834 			 */
7835 			lpfc_reg_fcfi(phba, mboxq);
7836 			mboxq->vport = phba->pport;
7837 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7838 			if (rc != MBX_SUCCESS)
7839 				goto out_unset_queue;
7840 			rc = 0;
7841 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
7842 						&mboxq->u.mqe.un.reg_fcfi);
7843 		} else {
7844 			/* We are a NVME Target mode with MRQ > 1 */
7845 
7846 			/* First register the FCFI */
7847 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
7848 			mboxq->vport = phba->pport;
7849 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7850 			if (rc != MBX_SUCCESS)
7851 				goto out_unset_queue;
7852 			rc = 0;
7853 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
7854 						&mboxq->u.mqe.un.reg_fcfi_mrq);
7855 
7856 			/* Next register the MRQs */
7857 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
7858 			mboxq->vport = phba->pport;
7859 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7860 			if (rc != MBX_SUCCESS)
7861 				goto out_unset_queue;
7862 			rc = 0;
7863 		}
7864 		/* Check if the port is configured to be disabled */
7865 		lpfc_sli_read_link_ste(phba);
7866 	}
7867 
7868 	/* Don't post more new bufs if repost already recovered
7869 	 * the nvme sgls.
7870 	 */
7871 	if (phba->nvmet_support == 0) {
7872 		if (phba->sli4_hba.io_xri_cnt == 0) {
7873 			len = lpfc_new_io_buf(
7874 					      phba, phba->sli4_hba.io_xri_max);
7875 			if (len == 0) {
7876 				rc = -ENOMEM;
7877 				goto out_unset_queue;
7878 			}
7879 
7880 			if (phba->cfg_xri_rebalancing)
7881 				lpfc_create_multixri_pools(phba);
7882 		}
7883 	} else {
7884 		phba->cfg_xri_rebalancing = 0;
7885 	}
7886 
7887 	/* Allow asynchronous mailbox command to go through */
7888 	spin_lock_irq(&phba->hbalock);
7889 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7890 	spin_unlock_irq(&phba->hbalock);
7891 
7892 	/* Post receive buffers to the device */
7893 	lpfc_sli4_rb_setup(phba);
7894 
7895 	/* Reset HBA FCF states after HBA reset */
7896 	phba->fcf.fcf_flag = 0;
7897 	phba->fcf.current_rec.flag = 0;
7898 
7899 	/* Start the ELS watchdog timer */
7900 	mod_timer(&vport->els_tmofunc,
7901 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
7902 
7903 	/* Start heart beat timer */
7904 	mod_timer(&phba->hb_tmofunc,
7905 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
7906 	phba->hb_outstanding = 0;
7907 	phba->last_completion_time = jiffies;
7908 
7909 	/* start eq_delay heartbeat */
7910 	if (phba->cfg_auto_imax)
7911 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
7912 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
7913 
7914 	/* start per phba idle_stat_delay heartbeat */
7915 	lpfc_init_idle_stat_hb(phba);
7916 
7917 	/* Start error attention (ERATT) polling timer */
7918 	mod_timer(&phba->eratt_poll,
7919 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
7920 
7921 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
7922 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
7923 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
7924 		if (!rc) {
7925 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7926 					"2829 This device supports "
7927 					"Advanced Error Reporting (AER)\n");
7928 			spin_lock_irq(&phba->hbalock);
7929 			phba->hba_flag |= HBA_AER_ENABLED;
7930 			spin_unlock_irq(&phba->hbalock);
7931 		} else {
7932 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7933 					"2830 This device does not support "
7934 					"Advanced Error Reporting (AER)\n");
7935 			phba->cfg_aer_support = 0;
7936 		}
7937 		rc = 0;
7938 	}
7939 
7940 	/*
7941 	 * The port is ready, set the host's link state to LINK_DOWN
7942 	 * in preparation for link interrupts.
7943 	 */
7944 	spin_lock_irq(&phba->hbalock);
7945 	phba->link_state = LPFC_LINK_DOWN;
7946 
7947 	/* Check if physical ports are trunked */
7948 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
7949 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
7950 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
7951 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
7952 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
7953 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
7954 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
7955 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
7956 	spin_unlock_irq(&phba->hbalock);
7957 
7958 	/* Arm the CQs and then EQs on device */
7959 	lpfc_sli4_arm_cqeq_intr(phba);
7960 
7961 	/* Indicate device interrupt mode */
7962 	phba->sli4_hba.intr_enable = 1;
7963 
7964 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
7965 	    (phba->hba_flag & LINK_DISABLED)) {
7966 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7967 				"3103 Adapter Link is disabled.\n");
7968 		lpfc_down_link(phba, mboxq);
7969 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7970 		if (rc != MBX_SUCCESS) {
7971 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7972 					"3104 Adapter failed to issue "
7973 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
7974 			goto out_io_buff_free;
7975 		}
7976 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
7977 		/* don't perform init_link on SLI4 FC port loopback test */
7978 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
7979 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
7980 			if (rc)
7981 				goto out_io_buff_free;
7982 		}
7983 	}
7984 	mempool_free(mboxq, phba->mbox_mem_pool);
7985 	return rc;
7986 out_io_buff_free:
7987 	/* Free allocated IO Buffers */
7988 	lpfc_io_free(phba);
7989 out_unset_queue:
7990 	/* Unset all the queues set up in this routine when error out */
7991 	lpfc_sli4_queue_unset(phba);
7992 out_destroy_queue:
7993 	lpfc_free_iocb_list(phba);
7994 	lpfc_sli4_queue_destroy(phba);
7995 out_stop_timers:
7996 	lpfc_stop_hba_timers(phba);
7997 out_free_mbox:
7998 	mempool_free(mboxq, phba->mbox_mem_pool);
7999 	return rc;
8000 }
8001 
8002 /**
8003  * lpfc_mbox_timeout - Timeout call back function for mbox timer
8004  * @t: Context to fetch pointer to hba structure from.
8005  *
8006  * This is the callback function for mailbox timer. The mailbox
8007  * timer is armed when a new mailbox command is issued and the timer
8008  * is deleted when the mailbox complete. The function is called by
8009  * the kernel timer code when a mailbox does not complete within
8010  * expected time. This function wakes up the worker thread to
8011  * process the mailbox timeout and returns. All the processing is
8012  * done by the worker thread function lpfc_mbox_timeout_handler.
8013  **/
8014 void
8015 lpfc_mbox_timeout(struct timer_list *t)
8016 {
8017 	struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
8018 	unsigned long iflag;
8019 	uint32_t tmo_posted;
8020 
8021 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
8022 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
8023 	if (!tmo_posted)
8024 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
8025 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
8026 
8027 	if (!tmo_posted)
8028 		lpfc_worker_wake_up(phba);
8029 	return;
8030 }
8031 
8032 /**
8033  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
8034  *                                    are pending
8035  * @phba: Pointer to HBA context object.
8036  *
8037  * This function checks if any mailbox completions are present on the mailbox
8038  * completion queue.
8039  **/
8040 static bool
8041 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
8042 {
8043 
8044 	uint32_t idx;
8045 	struct lpfc_queue *mcq;
8046 	struct lpfc_mcqe *mcqe;
8047 	bool pending_completions = false;
8048 	uint8_t	qe_valid;
8049 
8050 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8051 		return false;
8052 
8053 	/* Check for completions on mailbox completion queue */
8054 
8055 	mcq = phba->sli4_hba.mbx_cq;
8056 	idx = mcq->hba_index;
8057 	qe_valid = mcq->qe_valid;
8058 	while (bf_get_le32(lpfc_cqe_valid,
8059 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
8060 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
8061 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
8062 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
8063 			pending_completions = true;
8064 			break;
8065 		}
8066 		idx = (idx + 1) % mcq->entry_count;
8067 		if (mcq->hba_index == idx)
8068 			break;
8069 
8070 		/* if the index wrapped around, toggle the valid bit */
8071 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
8072 			qe_valid = (qe_valid) ? 0 : 1;
8073 	}
8074 	return pending_completions;
8075 
8076 }
8077 
8078 /**
8079  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
8080  *					      that were missed.
8081  * @phba: Pointer to HBA context object.
8082  *
8083  * For sli4, it is possible to miss an interrupt. As such mbox completions
8084  * maybe missed causing erroneous mailbox timeouts to occur. This function
8085  * checks to see if mbox completions are on the mailbox completion queue
8086  * and will process all the completions associated with the eq for the
8087  * mailbox completion queue.
8088  **/
8089 static bool
8090 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
8091 {
8092 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
8093 	uint32_t eqidx;
8094 	struct lpfc_queue *fpeq = NULL;
8095 	struct lpfc_queue *eq;
8096 	bool mbox_pending;
8097 
8098 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8099 		return false;
8100 
8101 	/* Find the EQ associated with the mbox CQ */
8102 	if (sli4_hba->hdwq) {
8103 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
8104 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
8105 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
8106 				fpeq = eq;
8107 				break;
8108 			}
8109 		}
8110 	}
8111 	if (!fpeq)
8112 		return false;
8113 
8114 	/* Turn off interrupts from this EQ */
8115 
8116 	sli4_hba->sli4_eq_clr_intr(fpeq);
8117 
8118 	/* Check to see if a mbox completion is pending */
8119 
8120 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
8121 
8122 	/*
8123 	 * If a mbox completion is pending, process all the events on EQ
8124 	 * associated with the mbox completion queue (this could include
8125 	 * mailbox commands, async events, els commands, receive queue data
8126 	 * and fcp commands)
8127 	 */
8128 
8129 	if (mbox_pending)
8130 		/* process and rearm the EQ */
8131 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
8132 	else
8133 		/* Always clear and re-arm the EQ */
8134 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
8135 
8136 	return mbox_pending;
8137 
8138 }
8139 
8140 /**
8141  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
8142  * @phba: Pointer to HBA context object.
8143  *
8144  * This function is called from worker thread when a mailbox command times out.
8145  * The caller is not required to hold any locks. This function will reset the
8146  * HBA and recover all the pending commands.
8147  **/
8148 void
8149 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
8150 {
8151 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
8152 	MAILBOX_t *mb = NULL;
8153 
8154 	struct lpfc_sli *psli = &phba->sli;
8155 
8156 	/* If the mailbox completed, process the completion and return */
8157 	if (lpfc_sli4_process_missed_mbox_completions(phba))
8158 		return;
8159 
8160 	if (pmbox != NULL)
8161 		mb = &pmbox->u.mb;
8162 	/* Check the pmbox pointer first.  There is a race condition
8163 	 * between the mbox timeout handler getting executed in the
8164 	 * worklist and the mailbox actually completing. When this
8165 	 * race condition occurs, the mbox_active will be NULL.
8166 	 */
8167 	spin_lock_irq(&phba->hbalock);
8168 	if (pmbox == NULL) {
8169 		lpfc_printf_log(phba, KERN_WARNING,
8170 				LOG_MBOX | LOG_SLI,
8171 				"0353 Active Mailbox cleared - mailbox timeout "
8172 				"exiting\n");
8173 		spin_unlock_irq(&phba->hbalock);
8174 		return;
8175 	}
8176 
8177 	/* Mbox cmd <mbxCommand> timeout */
8178 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8179 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
8180 			mb->mbxCommand,
8181 			phba->pport->port_state,
8182 			phba->sli.sli_flag,
8183 			phba->sli.mbox_active);
8184 	spin_unlock_irq(&phba->hbalock);
8185 
8186 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
8187 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
8188 	 * it to fail all outstanding SCSI IO.
8189 	 */
8190 	spin_lock_irq(&phba->pport->work_port_lock);
8191 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
8192 	spin_unlock_irq(&phba->pport->work_port_lock);
8193 	spin_lock_irq(&phba->hbalock);
8194 	phba->link_state = LPFC_LINK_UNKNOWN;
8195 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
8196 	spin_unlock_irq(&phba->hbalock);
8197 
8198 	lpfc_sli_abort_fcp_rings(phba);
8199 
8200 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8201 			"0345 Resetting board due to mailbox timeout\n");
8202 
8203 	/* Reset the HBA device */
8204 	lpfc_reset_hba(phba);
8205 }
8206 
8207 /**
8208  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
8209  * @phba: Pointer to HBA context object.
8210  * @pmbox: Pointer to mailbox object.
8211  * @flag: Flag indicating how the mailbox need to be processed.
8212  *
8213  * This function is called by discovery code and HBA management code
8214  * to submit a mailbox command to firmware with SLI-3 interface spec. This
8215  * function gets the hbalock to protect the data structures.
8216  * The mailbox command can be submitted in polling mode, in which case
8217  * this function will wait in a polling loop for the completion of the
8218  * mailbox.
8219  * If the mailbox is submitted in no_wait mode (not polling) the
8220  * function will submit the command and returns immediately without waiting
8221  * for the mailbox completion. The no_wait is supported only when HBA
8222  * is in SLI2/SLI3 mode - interrupts are enabled.
8223  * The SLI interface allows only one mailbox pending at a time. If the
8224  * mailbox is issued in polling mode and there is already a mailbox
8225  * pending, then the function will return an error. If the mailbox is issued
8226  * in NO_WAIT mode and there is a mailbox pending already, the function
8227  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
8228  * The sli layer owns the mailbox object until the completion of mailbox
8229  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
8230  * return codes the caller owns the mailbox command after the return of
8231  * the function.
8232  **/
8233 static int
8234 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
8235 		       uint32_t flag)
8236 {
8237 	MAILBOX_t *mbx;
8238 	struct lpfc_sli *psli = &phba->sli;
8239 	uint32_t status, evtctr;
8240 	uint32_t ha_copy, hc_copy;
8241 	int i;
8242 	unsigned long timeout;
8243 	unsigned long drvr_flag = 0;
8244 	uint32_t word0, ldata;
8245 	void __iomem *to_slim;
8246 	int processing_queue = 0;
8247 
8248 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
8249 	if (!pmbox) {
8250 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8251 		/* processing mbox queue from intr_handler */
8252 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8253 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8254 			return MBX_SUCCESS;
8255 		}
8256 		processing_queue = 1;
8257 		pmbox = lpfc_mbox_get(phba);
8258 		if (!pmbox) {
8259 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8260 			return MBX_SUCCESS;
8261 		}
8262 	}
8263 
8264 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
8265 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
8266 		if(!pmbox->vport) {
8267 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8268 			lpfc_printf_log(phba, KERN_ERR,
8269 					LOG_MBOX | LOG_VPORT,
8270 					"1806 Mbox x%x failed. No vport\n",
8271 					pmbox->u.mb.mbxCommand);
8272 			dump_stack();
8273 			goto out_not_finished;
8274 		}
8275 	}
8276 
8277 	/* If the PCI channel is in offline state, do not post mbox. */
8278 	if (unlikely(pci_channel_offline(phba->pcidev))) {
8279 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8280 		goto out_not_finished;
8281 	}
8282 
8283 	/* If HBA has a deferred error attention, fail the iocb. */
8284 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
8285 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8286 		goto out_not_finished;
8287 	}
8288 
8289 	psli = &phba->sli;
8290 
8291 	mbx = &pmbox->u.mb;
8292 	status = MBX_SUCCESS;
8293 
8294 	if (phba->link_state == LPFC_HBA_ERROR) {
8295 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8296 
8297 		/* Mbox command <mbxCommand> cannot issue */
8298 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8299 				"(%d):0311 Mailbox command x%x cannot "
8300 				"issue Data: x%x x%x\n",
8301 				pmbox->vport ? pmbox->vport->vpi : 0,
8302 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8303 		goto out_not_finished;
8304 	}
8305 
8306 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
8307 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
8308 			!(hc_copy & HC_MBINT_ENA)) {
8309 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8310 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8311 				"(%d):2528 Mailbox command x%x cannot "
8312 				"issue Data: x%x x%x\n",
8313 				pmbox->vport ? pmbox->vport->vpi : 0,
8314 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8315 			goto out_not_finished;
8316 		}
8317 	}
8318 
8319 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8320 		/* Polling for a mbox command when another one is already active
8321 		 * is not allowed in SLI. Also, the driver must have established
8322 		 * SLI2 mode to queue and process multiple mbox commands.
8323 		 */
8324 
8325 		if (flag & MBX_POLL) {
8326 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8327 
8328 			/* Mbox command <mbxCommand> cannot issue */
8329 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8330 					"(%d):2529 Mailbox command x%x "
8331 					"cannot issue Data: x%x x%x\n",
8332 					pmbox->vport ? pmbox->vport->vpi : 0,
8333 					pmbox->u.mb.mbxCommand,
8334 					psli->sli_flag, flag);
8335 			goto out_not_finished;
8336 		}
8337 
8338 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
8339 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8340 			/* Mbox command <mbxCommand> cannot issue */
8341 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8342 					"(%d):2530 Mailbox command x%x "
8343 					"cannot issue Data: x%x x%x\n",
8344 					pmbox->vport ? pmbox->vport->vpi : 0,
8345 					pmbox->u.mb.mbxCommand,
8346 					psli->sli_flag, flag);
8347 			goto out_not_finished;
8348 		}
8349 
8350 		/* Another mailbox command is still being processed, queue this
8351 		 * command to be processed later.
8352 		 */
8353 		lpfc_mbox_put(phba, pmbox);
8354 
8355 		/* Mbox cmd issue - BUSY */
8356 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8357 				"(%d):0308 Mbox cmd issue - BUSY Data: "
8358 				"x%x x%x x%x x%x\n",
8359 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
8360 				mbx->mbxCommand,
8361 				phba->pport ? phba->pport->port_state : 0xff,
8362 				psli->sli_flag, flag);
8363 
8364 		psli->slistat.mbox_busy++;
8365 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8366 
8367 		if (pmbox->vport) {
8368 			lpfc_debugfs_disc_trc(pmbox->vport,
8369 				LPFC_DISC_TRC_MBOX_VPORT,
8370 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
8371 				(uint32_t)mbx->mbxCommand,
8372 				mbx->un.varWords[0], mbx->un.varWords[1]);
8373 		}
8374 		else {
8375 			lpfc_debugfs_disc_trc(phba->pport,
8376 				LPFC_DISC_TRC_MBOX,
8377 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
8378 				(uint32_t)mbx->mbxCommand,
8379 				mbx->un.varWords[0], mbx->un.varWords[1]);
8380 		}
8381 
8382 		return MBX_BUSY;
8383 	}
8384 
8385 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8386 
8387 	/* If we are not polling, we MUST be in SLI2 mode */
8388 	if (flag != MBX_POLL) {
8389 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
8390 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
8391 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8392 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8393 			/* Mbox command <mbxCommand> cannot issue */
8394 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8395 					"(%d):2531 Mailbox command x%x "
8396 					"cannot issue Data: x%x x%x\n",
8397 					pmbox->vport ? pmbox->vport->vpi : 0,
8398 					pmbox->u.mb.mbxCommand,
8399 					psli->sli_flag, flag);
8400 			goto out_not_finished;
8401 		}
8402 		/* timeout active mbox command */
8403 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8404 					   1000);
8405 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
8406 	}
8407 
8408 	/* Mailbox cmd <cmd> issue */
8409 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8410 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
8411 			"x%x\n",
8412 			pmbox->vport ? pmbox->vport->vpi : 0,
8413 			mbx->mbxCommand,
8414 			phba->pport ? phba->pport->port_state : 0xff,
8415 			psli->sli_flag, flag);
8416 
8417 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
8418 		if (pmbox->vport) {
8419 			lpfc_debugfs_disc_trc(pmbox->vport,
8420 				LPFC_DISC_TRC_MBOX_VPORT,
8421 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
8422 				(uint32_t)mbx->mbxCommand,
8423 				mbx->un.varWords[0], mbx->un.varWords[1]);
8424 		}
8425 		else {
8426 			lpfc_debugfs_disc_trc(phba->pport,
8427 				LPFC_DISC_TRC_MBOX,
8428 				"MBOX Send:       cmd:x%x mb:x%x x%x",
8429 				(uint32_t)mbx->mbxCommand,
8430 				mbx->un.varWords[0], mbx->un.varWords[1]);
8431 		}
8432 	}
8433 
8434 	psli->slistat.mbox_cmd++;
8435 	evtctr = psli->slistat.mbox_event;
8436 
8437 	/* next set own bit for the adapter and copy over command word */
8438 	mbx->mbxOwner = OWN_CHIP;
8439 
8440 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8441 		/* Populate mbox extension offset word. */
8442 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
8443 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8444 				= (uint8_t *)phba->mbox_ext
8445 				  - (uint8_t *)phba->mbox;
8446 		}
8447 
8448 		/* Copy the mailbox extension data */
8449 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
8450 			lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
8451 					      (uint8_t *)phba->mbox_ext,
8452 					      pmbox->in_ext_byte_len);
8453 		}
8454 		/* Copy command data to host SLIM area */
8455 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
8456 	} else {
8457 		/* Populate mbox extension offset word. */
8458 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
8459 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8460 				= MAILBOX_HBA_EXT_OFFSET;
8461 
8462 		/* Copy the mailbox extension data */
8463 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
8464 			lpfc_memcpy_to_slim(phba->MBslimaddr +
8465 				MAILBOX_HBA_EXT_OFFSET,
8466 				pmbox->ctx_buf, pmbox->in_ext_byte_len);
8467 
8468 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8469 			/* copy command data into host mbox for cmpl */
8470 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
8471 					      MAILBOX_CMD_SIZE);
8472 
8473 		/* First copy mbox command data to HBA SLIM, skip past first
8474 		   word */
8475 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
8476 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
8477 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
8478 
8479 		/* Next copy over first word, with mbxOwner set */
8480 		ldata = *((uint32_t *)mbx);
8481 		to_slim = phba->MBslimaddr;
8482 		writel(ldata, to_slim);
8483 		readl(to_slim); /* flush */
8484 
8485 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8486 			/* switch over to host mailbox */
8487 			psli->sli_flag |= LPFC_SLI_ACTIVE;
8488 	}
8489 
8490 	wmb();
8491 
8492 	switch (flag) {
8493 	case MBX_NOWAIT:
8494 		/* Set up reference to mailbox command */
8495 		psli->mbox_active = pmbox;
8496 		/* Interrupt board to do it */
8497 		writel(CA_MBATT, phba->CAregaddr);
8498 		readl(phba->CAregaddr); /* flush */
8499 		/* Don't wait for it to finish, just return */
8500 		break;
8501 
8502 	case MBX_POLL:
8503 		/* Set up null reference to mailbox command */
8504 		psli->mbox_active = NULL;
8505 		/* Interrupt board to do it */
8506 		writel(CA_MBATT, phba->CAregaddr);
8507 		readl(phba->CAregaddr); /* flush */
8508 
8509 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8510 			/* First read mbox status word */
8511 			word0 = *((uint32_t *)phba->mbox);
8512 			word0 = le32_to_cpu(word0);
8513 		} else {
8514 			/* First read mbox status word */
8515 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
8516 				spin_unlock_irqrestore(&phba->hbalock,
8517 						       drvr_flag);
8518 				goto out_not_finished;
8519 			}
8520 		}
8521 
8522 		/* Read the HBA Host Attention Register */
8523 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8524 			spin_unlock_irqrestore(&phba->hbalock,
8525 						       drvr_flag);
8526 			goto out_not_finished;
8527 		}
8528 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8529 							1000) + jiffies;
8530 		i = 0;
8531 		/* Wait for command to complete */
8532 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
8533 		       (!(ha_copy & HA_MBATT) &&
8534 			(phba->link_state > LPFC_WARM_START))) {
8535 			if (time_after(jiffies, timeout)) {
8536 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8537 				spin_unlock_irqrestore(&phba->hbalock,
8538 						       drvr_flag);
8539 				goto out_not_finished;
8540 			}
8541 
8542 			/* Check if we took a mbox interrupt while we were
8543 			   polling */
8544 			if (((word0 & OWN_CHIP) != OWN_CHIP)
8545 			    && (evtctr != psli->slistat.mbox_event))
8546 				break;
8547 
8548 			if (i++ > 10) {
8549 				spin_unlock_irqrestore(&phba->hbalock,
8550 						       drvr_flag);
8551 				msleep(1);
8552 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
8553 			}
8554 
8555 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8556 				/* First copy command data */
8557 				word0 = *((uint32_t *)phba->mbox);
8558 				word0 = le32_to_cpu(word0);
8559 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
8560 					MAILBOX_t *slimmb;
8561 					uint32_t slimword0;
8562 					/* Check real SLIM for any errors */
8563 					slimword0 = readl(phba->MBslimaddr);
8564 					slimmb = (MAILBOX_t *) & slimword0;
8565 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
8566 					    && slimmb->mbxStatus) {
8567 						psli->sli_flag &=
8568 						    ~LPFC_SLI_ACTIVE;
8569 						word0 = slimword0;
8570 					}
8571 				}
8572 			} else {
8573 				/* First copy command data */
8574 				word0 = readl(phba->MBslimaddr);
8575 			}
8576 			/* Read the HBA Host Attention Register */
8577 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8578 				spin_unlock_irqrestore(&phba->hbalock,
8579 						       drvr_flag);
8580 				goto out_not_finished;
8581 			}
8582 		}
8583 
8584 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8585 			/* copy results back to user */
8586 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
8587 						MAILBOX_CMD_SIZE);
8588 			/* Copy the mailbox extension data */
8589 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8590 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
8591 						      pmbox->ctx_buf,
8592 						      pmbox->out_ext_byte_len);
8593 			}
8594 		} else {
8595 			/* First copy command data */
8596 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
8597 						MAILBOX_CMD_SIZE);
8598 			/* Copy the mailbox extension data */
8599 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8600 				lpfc_memcpy_from_slim(
8601 					pmbox->ctx_buf,
8602 					phba->MBslimaddr +
8603 					MAILBOX_HBA_EXT_OFFSET,
8604 					pmbox->out_ext_byte_len);
8605 			}
8606 		}
8607 
8608 		writel(HA_MBATT, phba->HAregaddr);
8609 		readl(phba->HAregaddr); /* flush */
8610 
8611 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8612 		status = mbx->mbxStatus;
8613 	}
8614 
8615 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8616 	return status;
8617 
8618 out_not_finished:
8619 	if (processing_queue) {
8620 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
8621 		lpfc_mbox_cmpl_put(phba, pmbox);
8622 	}
8623 	return MBX_NOT_FINISHED;
8624 }
8625 
8626 /**
8627  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
8628  * @phba: Pointer to HBA context object.
8629  *
8630  * The function blocks the posting of SLI4 asynchronous mailbox commands from
8631  * the driver internal pending mailbox queue. It will then try to wait out the
8632  * possible outstanding mailbox command before return.
8633  *
8634  * Returns:
8635  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
8636  * 	the outstanding mailbox command timed out.
8637  **/
8638 static int
8639 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
8640 {
8641 	struct lpfc_sli *psli = &phba->sli;
8642 	int rc = 0;
8643 	unsigned long timeout = 0;
8644 
8645 	/* Mark the asynchronous mailbox command posting as blocked */
8646 	spin_lock_irq(&phba->hbalock);
8647 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
8648 	/* Determine how long we might wait for the active mailbox
8649 	 * command to be gracefully completed by firmware.
8650 	 */
8651 	if (phba->sli.mbox_active)
8652 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
8653 						phba->sli.mbox_active) *
8654 						1000) + jiffies;
8655 	spin_unlock_irq(&phba->hbalock);
8656 
8657 	/* Make sure the mailbox is really active */
8658 	if (timeout)
8659 		lpfc_sli4_process_missed_mbox_completions(phba);
8660 
8661 	/* Wait for the outstnading mailbox command to complete */
8662 	while (phba->sli.mbox_active) {
8663 		/* Check active mailbox complete status every 2ms */
8664 		msleep(2);
8665 		if (time_after(jiffies, timeout)) {
8666 			/* Timeout, marked the outstanding cmd not complete */
8667 			rc = 1;
8668 			break;
8669 		}
8670 	}
8671 
8672 	/* Can not cleanly block async mailbox command, fails it */
8673 	if (rc) {
8674 		spin_lock_irq(&phba->hbalock);
8675 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8676 		spin_unlock_irq(&phba->hbalock);
8677 	}
8678 	return rc;
8679 }
8680 
8681 /**
8682  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
8683  * @phba: Pointer to HBA context object.
8684  *
8685  * The function unblocks and resume posting of SLI4 asynchronous mailbox
8686  * commands from the driver internal pending mailbox queue. It makes sure
8687  * that there is no outstanding mailbox command before resuming posting
8688  * asynchronous mailbox commands. If, for any reason, there is outstanding
8689  * mailbox command, it will try to wait it out before resuming asynchronous
8690  * mailbox command posting.
8691  **/
8692 static void
8693 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
8694 {
8695 	struct lpfc_sli *psli = &phba->sli;
8696 
8697 	spin_lock_irq(&phba->hbalock);
8698 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8699 		/* Asynchronous mailbox posting is not blocked, do nothing */
8700 		spin_unlock_irq(&phba->hbalock);
8701 		return;
8702 	}
8703 
8704 	/* Outstanding synchronous mailbox command is guaranteed to be done,
8705 	 * successful or timeout, after timing-out the outstanding mailbox
8706 	 * command shall always be removed, so just unblock posting async
8707 	 * mailbox command and resume
8708 	 */
8709 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8710 	spin_unlock_irq(&phba->hbalock);
8711 
8712 	/* wake up worker thread to post asynchronous mailbox command */
8713 	lpfc_worker_wake_up(phba);
8714 }
8715 
8716 /**
8717  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
8718  * @phba: Pointer to HBA context object.
8719  * @mboxq: Pointer to mailbox object.
8720  *
8721  * The function waits for the bootstrap mailbox register ready bit from
8722  * port for twice the regular mailbox command timeout value.
8723  *
8724  *      0 - no timeout on waiting for bootstrap mailbox register ready.
8725  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
8726  **/
8727 static int
8728 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8729 {
8730 	uint32_t db_ready;
8731 	unsigned long timeout;
8732 	struct lpfc_register bmbx_reg;
8733 
8734 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
8735 				   * 1000) + jiffies;
8736 
8737 	do {
8738 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
8739 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
8740 		if (!db_ready)
8741 			mdelay(2);
8742 
8743 		if (time_after(jiffies, timeout))
8744 			return MBXERR_ERROR;
8745 	} while (!db_ready);
8746 
8747 	return 0;
8748 }
8749 
8750 /**
8751  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
8752  * @phba: Pointer to HBA context object.
8753  * @mboxq: Pointer to mailbox object.
8754  *
8755  * The function posts a mailbox to the port.  The mailbox is expected
8756  * to be comletely filled in and ready for the port to operate on it.
8757  * This routine executes a synchronous completion operation on the
8758  * mailbox by polling for its completion.
8759  *
8760  * The caller must not be holding any locks when calling this routine.
8761  *
8762  * Returns:
8763  *	MBX_SUCCESS - mailbox posted successfully
8764  *	Any of the MBX error values.
8765  **/
8766 static int
8767 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8768 {
8769 	int rc = MBX_SUCCESS;
8770 	unsigned long iflag;
8771 	uint32_t mcqe_status;
8772 	uint32_t mbx_cmnd;
8773 	struct lpfc_sli *psli = &phba->sli;
8774 	struct lpfc_mqe *mb = &mboxq->u.mqe;
8775 	struct lpfc_bmbx_create *mbox_rgn;
8776 	struct dma_address *dma_address;
8777 
8778 	/*
8779 	 * Only one mailbox can be active to the bootstrap mailbox region
8780 	 * at a time and there is no queueing provided.
8781 	 */
8782 	spin_lock_irqsave(&phba->hbalock, iflag);
8783 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8784 		spin_unlock_irqrestore(&phba->hbalock, iflag);
8785 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8786 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
8787 				"cannot issue Data: x%x x%x\n",
8788 				mboxq->vport ? mboxq->vport->vpi : 0,
8789 				mboxq->u.mb.mbxCommand,
8790 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8791 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8792 				psli->sli_flag, MBX_POLL);
8793 		return MBXERR_ERROR;
8794 	}
8795 	/* The server grabs the token and owns it until release */
8796 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8797 	phba->sli.mbox_active = mboxq;
8798 	spin_unlock_irqrestore(&phba->hbalock, iflag);
8799 
8800 	/* wait for bootstrap mbox register for readyness */
8801 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8802 	if (rc)
8803 		goto exit;
8804 	/*
8805 	 * Initialize the bootstrap memory region to avoid stale data areas
8806 	 * in the mailbox post.  Then copy the caller's mailbox contents to
8807 	 * the bmbx mailbox region.
8808 	 */
8809 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
8810 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
8811 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
8812 			       sizeof(struct lpfc_mqe));
8813 
8814 	/* Post the high mailbox dma address to the port and wait for ready. */
8815 	dma_address = &phba->sli4_hba.bmbx.dma_address;
8816 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
8817 
8818 	/* wait for bootstrap mbox register for hi-address write done */
8819 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8820 	if (rc)
8821 		goto exit;
8822 
8823 	/* Post the low mailbox dma address to the port. */
8824 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
8825 
8826 	/* wait for bootstrap mbox register for low address write done */
8827 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8828 	if (rc)
8829 		goto exit;
8830 
8831 	/*
8832 	 * Read the CQ to ensure the mailbox has completed.
8833 	 * If so, update the mailbox status so that the upper layers
8834 	 * can complete the request normally.
8835 	 */
8836 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
8837 			       sizeof(struct lpfc_mqe));
8838 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
8839 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
8840 			       sizeof(struct lpfc_mcqe));
8841 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
8842 	/*
8843 	 * When the CQE status indicates a failure and the mailbox status
8844 	 * indicates success then copy the CQE status into the mailbox status
8845 	 * (and prefix it with x4000).
8846 	 */
8847 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
8848 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
8849 			bf_set(lpfc_mqe_status, mb,
8850 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
8851 		rc = MBXERR_ERROR;
8852 	} else
8853 		lpfc_sli4_swap_str(phba, mboxq);
8854 
8855 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8856 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
8857 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
8858 			" x%x x%x CQ: x%x x%x x%x x%x\n",
8859 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
8860 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8861 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8862 			bf_get(lpfc_mqe_status, mb),
8863 			mb->un.mb_words[0], mb->un.mb_words[1],
8864 			mb->un.mb_words[2], mb->un.mb_words[3],
8865 			mb->un.mb_words[4], mb->un.mb_words[5],
8866 			mb->un.mb_words[6], mb->un.mb_words[7],
8867 			mb->un.mb_words[8], mb->un.mb_words[9],
8868 			mb->un.mb_words[10], mb->un.mb_words[11],
8869 			mb->un.mb_words[12], mboxq->mcqe.word0,
8870 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
8871 			mboxq->mcqe.trailer);
8872 exit:
8873 	/* We are holding the token, no needed for lock when release */
8874 	spin_lock_irqsave(&phba->hbalock, iflag);
8875 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8876 	phba->sli.mbox_active = NULL;
8877 	spin_unlock_irqrestore(&phba->hbalock, iflag);
8878 	return rc;
8879 }
8880 
8881 /**
8882  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
8883  * @phba: Pointer to HBA context object.
8884  * @mboxq: Pointer to mailbox object.
8885  * @flag: Flag indicating how the mailbox need to be processed.
8886  *
8887  * This function is called by discovery code and HBA management code to submit
8888  * a mailbox command to firmware with SLI-4 interface spec.
8889  *
8890  * Return codes the caller owns the mailbox command after the return of the
8891  * function.
8892  **/
8893 static int
8894 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
8895 		       uint32_t flag)
8896 {
8897 	struct lpfc_sli *psli = &phba->sli;
8898 	unsigned long iflags;
8899 	int rc;
8900 
8901 	/* dump from issue mailbox command if setup */
8902 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
8903 
8904 	rc = lpfc_mbox_dev_check(phba);
8905 	if (unlikely(rc)) {
8906 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8907 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
8908 				"cannot issue Data: x%x x%x\n",
8909 				mboxq->vport ? mboxq->vport->vpi : 0,
8910 				mboxq->u.mb.mbxCommand,
8911 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8912 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8913 				psli->sli_flag, flag);
8914 		goto out_not_finished;
8915 	}
8916 
8917 	/* Detect polling mode and jump to a handler */
8918 	if (!phba->sli4_hba.intr_enable) {
8919 		if (flag == MBX_POLL)
8920 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
8921 		else
8922 			rc = -EIO;
8923 		if (rc != MBX_SUCCESS)
8924 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8925 					"(%d):2541 Mailbox command x%x "
8926 					"(x%x/x%x) failure: "
8927 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
8928 					"Data: x%x x%x\n,",
8929 					mboxq->vport ? mboxq->vport->vpi : 0,
8930 					mboxq->u.mb.mbxCommand,
8931 					lpfc_sli_config_mbox_subsys_get(phba,
8932 									mboxq),
8933 					lpfc_sli_config_mbox_opcode_get(phba,
8934 									mboxq),
8935 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
8936 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
8937 					bf_get(lpfc_mcqe_ext_status,
8938 					       &mboxq->mcqe),
8939 					psli->sli_flag, flag);
8940 		return rc;
8941 	} else if (flag == MBX_POLL) {
8942 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8943 				"(%d):2542 Try to issue mailbox command "
8944 				"x%x (x%x/x%x) synchronously ahead of async "
8945 				"mailbox command queue: x%x x%x\n",
8946 				mboxq->vport ? mboxq->vport->vpi : 0,
8947 				mboxq->u.mb.mbxCommand,
8948 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8949 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8950 				psli->sli_flag, flag);
8951 		/* Try to block the asynchronous mailbox posting */
8952 		rc = lpfc_sli4_async_mbox_block(phba);
8953 		if (!rc) {
8954 			/* Successfully blocked, now issue sync mbox cmd */
8955 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
8956 			if (rc != MBX_SUCCESS)
8957 				lpfc_printf_log(phba, KERN_WARNING,
8958 					LOG_MBOX | LOG_SLI,
8959 					"(%d):2597 Sync Mailbox command "
8960 					"x%x (x%x/x%x) failure: "
8961 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
8962 					"Data: x%x x%x\n,",
8963 					mboxq->vport ? mboxq->vport->vpi : 0,
8964 					mboxq->u.mb.mbxCommand,
8965 					lpfc_sli_config_mbox_subsys_get(phba,
8966 									mboxq),
8967 					lpfc_sli_config_mbox_opcode_get(phba,
8968 									mboxq),
8969 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
8970 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
8971 					bf_get(lpfc_mcqe_ext_status,
8972 					       &mboxq->mcqe),
8973 					psli->sli_flag, flag);
8974 			/* Unblock the async mailbox posting afterward */
8975 			lpfc_sli4_async_mbox_unblock(phba);
8976 		}
8977 		return rc;
8978 	}
8979 
8980 	/* Now, interrupt mode asynchronous mailbox command */
8981 	rc = lpfc_mbox_cmd_check(phba, mboxq);
8982 	if (rc) {
8983 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8984 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
8985 				"cannot issue Data: x%x x%x\n",
8986 				mboxq->vport ? mboxq->vport->vpi : 0,
8987 				mboxq->u.mb.mbxCommand,
8988 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8989 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8990 				psli->sli_flag, flag);
8991 		goto out_not_finished;
8992 	}
8993 
8994 	/* Put the mailbox command to the driver internal FIFO */
8995 	psli->slistat.mbox_busy++;
8996 	spin_lock_irqsave(&phba->hbalock, iflags);
8997 	lpfc_mbox_put(phba, mboxq);
8998 	spin_unlock_irqrestore(&phba->hbalock, iflags);
8999 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9000 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
9001 			"x%x (x%x/x%x) x%x x%x x%x\n",
9002 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
9003 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
9004 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9005 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9006 			phba->pport->port_state,
9007 			psli->sli_flag, MBX_NOWAIT);
9008 	/* Wake up worker thread to transport mailbox command from head */
9009 	lpfc_worker_wake_up(phba);
9010 
9011 	return MBX_BUSY;
9012 
9013 out_not_finished:
9014 	return MBX_NOT_FINISHED;
9015 }
9016 
9017 /**
9018  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
9019  * @phba: Pointer to HBA context object.
9020  *
9021  * This function is called by worker thread to send a mailbox command to
9022  * SLI4 HBA firmware.
9023  *
9024  **/
9025 int
9026 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
9027 {
9028 	struct lpfc_sli *psli = &phba->sli;
9029 	LPFC_MBOXQ_t *mboxq;
9030 	int rc = MBX_SUCCESS;
9031 	unsigned long iflags;
9032 	struct lpfc_mqe *mqe;
9033 	uint32_t mbx_cmnd;
9034 
9035 	/* Check interrupt mode before post async mailbox command */
9036 	if (unlikely(!phba->sli4_hba.intr_enable))
9037 		return MBX_NOT_FINISHED;
9038 
9039 	/* Check for mailbox command service token */
9040 	spin_lock_irqsave(&phba->hbalock, iflags);
9041 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9042 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9043 		return MBX_NOT_FINISHED;
9044 	}
9045 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9046 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9047 		return MBX_NOT_FINISHED;
9048 	}
9049 	if (unlikely(phba->sli.mbox_active)) {
9050 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9051 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9052 				"0384 There is pending active mailbox cmd\n");
9053 		return MBX_NOT_FINISHED;
9054 	}
9055 	/* Take the mailbox command service token */
9056 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9057 
9058 	/* Get the next mailbox command from head of queue */
9059 	mboxq = lpfc_mbox_get(phba);
9060 
9061 	/* If no more mailbox command waiting for post, we're done */
9062 	if (!mboxq) {
9063 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9064 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9065 		return MBX_SUCCESS;
9066 	}
9067 	phba->sli.mbox_active = mboxq;
9068 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9069 
9070 	/* Check device readiness for posting mailbox command */
9071 	rc = lpfc_mbox_dev_check(phba);
9072 	if (unlikely(rc))
9073 		/* Driver clean routine will clean up pending mailbox */
9074 		goto out_not_finished;
9075 
9076 	/* Prepare the mbox command to be posted */
9077 	mqe = &mboxq->u.mqe;
9078 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
9079 
9080 	/* Start timer for the mbox_tmo and log some mailbox post messages */
9081 	mod_timer(&psli->mbox_tmo, (jiffies +
9082 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
9083 
9084 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9085 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
9086 			"x%x x%x\n",
9087 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
9088 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9089 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9090 			phba->pport->port_state, psli->sli_flag);
9091 
9092 	if (mbx_cmnd != MBX_HEARTBEAT) {
9093 		if (mboxq->vport) {
9094 			lpfc_debugfs_disc_trc(mboxq->vport,
9095 				LPFC_DISC_TRC_MBOX_VPORT,
9096 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9097 				mbx_cmnd, mqe->un.mb_words[0],
9098 				mqe->un.mb_words[1]);
9099 		} else {
9100 			lpfc_debugfs_disc_trc(phba->pport,
9101 				LPFC_DISC_TRC_MBOX,
9102 				"MBOX Send: cmd:x%x mb:x%x x%x",
9103 				mbx_cmnd, mqe->un.mb_words[0],
9104 				mqe->un.mb_words[1]);
9105 		}
9106 	}
9107 	psli->slistat.mbox_cmd++;
9108 
9109 	/* Post the mailbox command to the port */
9110 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
9111 	if (rc != MBX_SUCCESS) {
9112 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9113 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
9114 				"cannot issue Data: x%x x%x\n",
9115 				mboxq->vport ? mboxq->vport->vpi : 0,
9116 				mboxq->u.mb.mbxCommand,
9117 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9118 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9119 				psli->sli_flag, MBX_NOWAIT);
9120 		goto out_not_finished;
9121 	}
9122 
9123 	return rc;
9124 
9125 out_not_finished:
9126 	spin_lock_irqsave(&phba->hbalock, iflags);
9127 	if (phba->sli.mbox_active) {
9128 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
9129 		__lpfc_mbox_cmpl_put(phba, mboxq);
9130 		/* Release the token */
9131 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9132 		phba->sli.mbox_active = NULL;
9133 	}
9134 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9135 
9136 	return MBX_NOT_FINISHED;
9137 }
9138 
9139 /**
9140  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
9141  * @phba: Pointer to HBA context object.
9142  * @pmbox: Pointer to mailbox object.
9143  * @flag: Flag indicating how the mailbox need to be processed.
9144  *
9145  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
9146  * the API jump table function pointer from the lpfc_hba struct.
9147  *
9148  * Return codes the caller owns the mailbox command after the return of the
9149  * function.
9150  **/
9151 int
9152 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
9153 {
9154 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
9155 }
9156 
9157 /**
9158  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
9159  * @phba: The hba struct for which this call is being executed.
9160  * @dev_grp: The HBA PCI-Device group number.
9161  *
9162  * This routine sets up the mbox interface API function jump table in @phba
9163  * struct.
9164  * Returns: 0 - success, -ENODEV - failure.
9165  **/
9166 int
9167 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
9168 {
9169 
9170 	switch (dev_grp) {
9171 	case LPFC_PCI_DEV_LP:
9172 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
9173 		phba->lpfc_sli_handle_slow_ring_event =
9174 				lpfc_sli_handle_slow_ring_event_s3;
9175 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
9176 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
9177 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
9178 		break;
9179 	case LPFC_PCI_DEV_OC:
9180 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
9181 		phba->lpfc_sli_handle_slow_ring_event =
9182 				lpfc_sli_handle_slow_ring_event_s4;
9183 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
9184 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
9185 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
9186 		break;
9187 	default:
9188 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9189 				"1420 Invalid HBA PCI-device group: 0x%x\n",
9190 				dev_grp);
9191 		return -ENODEV;
9192 		break;
9193 	}
9194 	return 0;
9195 }
9196 
9197 /**
9198  * __lpfc_sli_ringtx_put - Add an iocb to the txq
9199  * @phba: Pointer to HBA context object.
9200  * @pring: Pointer to driver SLI ring object.
9201  * @piocb: Pointer to address of newly added command iocb.
9202  *
9203  * This function is called with hbalock held for SLI3 ports or
9204  * the ring lock held for SLI4 ports to add a command
9205  * iocb to the txq when SLI layer cannot submit the command iocb
9206  * to the ring.
9207  **/
9208 void
9209 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9210 		    struct lpfc_iocbq *piocb)
9211 {
9212 	if (phba->sli_rev == LPFC_SLI_REV4)
9213 		lockdep_assert_held(&pring->ring_lock);
9214 	else
9215 		lockdep_assert_held(&phba->hbalock);
9216 	/* Insert the caller's iocb in the txq tail for later processing. */
9217 	list_add_tail(&piocb->list, &pring->txq);
9218 }
9219 
9220 /**
9221  * lpfc_sli_next_iocb - Get the next iocb in the txq
9222  * @phba: Pointer to HBA context object.
9223  * @pring: Pointer to driver SLI ring object.
9224  * @piocb: Pointer to address of newly added command iocb.
9225  *
9226  * This function is called with hbalock held before a new
9227  * iocb is submitted to the firmware. This function checks
9228  * txq to flush the iocbs in txq to Firmware before
9229  * submitting new iocbs to the Firmware.
9230  * If there are iocbs in the txq which need to be submitted
9231  * to firmware, lpfc_sli_next_iocb returns the first element
9232  * of the txq after dequeuing it from txq.
9233  * If there is no iocb in the txq then the function will return
9234  * *piocb and *piocb is set to NULL. Caller needs to check
9235  * *piocb to find if there are more commands in the txq.
9236  **/
9237 static struct lpfc_iocbq *
9238 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9239 		   struct lpfc_iocbq **piocb)
9240 {
9241 	struct lpfc_iocbq * nextiocb;
9242 
9243 	lockdep_assert_held(&phba->hbalock);
9244 
9245 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
9246 	if (!nextiocb) {
9247 		nextiocb = *piocb;
9248 		*piocb = NULL;
9249 	}
9250 
9251 	return nextiocb;
9252 }
9253 
9254 /**
9255  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
9256  * @phba: Pointer to HBA context object.
9257  * @ring_number: SLI ring number to issue iocb on.
9258  * @piocb: Pointer to command iocb.
9259  * @flag: Flag indicating if this command can be put into txq.
9260  *
9261  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
9262  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
9263  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
9264  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
9265  * this function allows only iocbs for posting buffers. This function finds
9266  * next available slot in the command ring and posts the command to the
9267  * available slot and writes the port attention register to request HBA start
9268  * processing new iocb. If there is no slot available in the ring and
9269  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
9270  * the function returns IOCB_BUSY.
9271  *
9272  * This function is called with hbalock held. The function will return success
9273  * after it successfully submit the iocb to firmware or after adding to the
9274  * txq.
9275  **/
9276 static int
9277 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
9278 		    struct lpfc_iocbq *piocb, uint32_t flag)
9279 {
9280 	struct lpfc_iocbq *nextiocb;
9281 	IOCB_t *iocb;
9282 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
9283 
9284 	lockdep_assert_held(&phba->hbalock);
9285 
9286 	if (piocb->iocb_cmpl && (!piocb->vport) &&
9287 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
9288 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
9289 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9290 				"1807 IOCB x%x failed. No vport\n",
9291 				piocb->iocb.ulpCommand);
9292 		dump_stack();
9293 		return IOCB_ERROR;
9294 	}
9295 
9296 
9297 	/* If the PCI channel is in offline state, do not post iocbs. */
9298 	if (unlikely(pci_channel_offline(phba->pcidev)))
9299 		return IOCB_ERROR;
9300 
9301 	/* If HBA has a deferred error attention, fail the iocb. */
9302 	if (unlikely(phba->hba_flag & DEFER_ERATT))
9303 		return IOCB_ERROR;
9304 
9305 	/*
9306 	 * We should never get an IOCB if we are in a < LINK_DOWN state
9307 	 */
9308 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
9309 		return IOCB_ERROR;
9310 
9311 	/*
9312 	 * Check to see if we are blocking IOCB processing because of a
9313 	 * outstanding event.
9314 	 */
9315 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
9316 		goto iocb_busy;
9317 
9318 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
9319 		/*
9320 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
9321 		 * can be issued if the link is not up.
9322 		 */
9323 		switch (piocb->iocb.ulpCommand) {
9324 		case CMD_GEN_REQUEST64_CR:
9325 		case CMD_GEN_REQUEST64_CX:
9326 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
9327 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
9328 					FC_RCTL_DD_UNSOL_CMD) ||
9329 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
9330 					MENLO_TRANSPORT_TYPE))
9331 
9332 				goto iocb_busy;
9333 			break;
9334 		case CMD_QUE_RING_BUF_CN:
9335 		case CMD_QUE_RING_BUF64_CN:
9336 			/*
9337 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
9338 			 * completion, iocb_cmpl MUST be 0.
9339 			 */
9340 			if (piocb->iocb_cmpl)
9341 				piocb->iocb_cmpl = NULL;
9342 			/*FALLTHROUGH*/
9343 		case CMD_CREATE_XRI_CR:
9344 		case CMD_CLOSE_XRI_CN:
9345 		case CMD_CLOSE_XRI_CX:
9346 			break;
9347 		default:
9348 			goto iocb_busy;
9349 		}
9350 
9351 	/*
9352 	 * For FCP commands, we must be in a state where we can process link
9353 	 * attention events.
9354 	 */
9355 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
9356 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
9357 		goto iocb_busy;
9358 	}
9359 
9360 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
9361 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
9362 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
9363 
9364 	if (iocb)
9365 		lpfc_sli_update_ring(phba, pring);
9366 	else
9367 		lpfc_sli_update_full_ring(phba, pring);
9368 
9369 	if (!piocb)
9370 		return IOCB_SUCCESS;
9371 
9372 	goto out_busy;
9373 
9374  iocb_busy:
9375 	pring->stats.iocb_cmd_delay++;
9376 
9377  out_busy:
9378 
9379 	if (!(flag & SLI_IOCB_RET_IOCB)) {
9380 		__lpfc_sli_ringtx_put(phba, pring, piocb);
9381 		return IOCB_SUCCESS;
9382 	}
9383 
9384 	return IOCB_BUSY;
9385 }
9386 
9387 /**
9388  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
9389  * @phba: Pointer to HBA context object.
9390  * @piocbq: Pointer to command iocb.
9391  * @sglq: Pointer to the scatter gather queue object.
9392  *
9393  * This routine converts the bpl or bde that is in the IOCB
9394  * to a sgl list for the sli4 hardware. The physical address
9395  * of the bpl/bde is converted back to a virtual address.
9396  * If the IOCB contains a BPL then the list of BDE's is
9397  * converted to sli4_sge's. If the IOCB contains a single
9398  * BDE then it is converted to a single sli_sge.
9399  * The IOCB is still in cpu endianess so the contents of
9400  * the bpl can be used without byte swapping.
9401  *
9402  * Returns valid XRI = Success, NO_XRI = Failure.
9403 **/
9404 static uint16_t
9405 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
9406 		struct lpfc_sglq *sglq)
9407 {
9408 	uint16_t xritag = NO_XRI;
9409 	struct ulp_bde64 *bpl = NULL;
9410 	struct ulp_bde64 bde;
9411 	struct sli4_sge *sgl  = NULL;
9412 	struct lpfc_dmabuf *dmabuf;
9413 	IOCB_t *icmd;
9414 	int numBdes = 0;
9415 	int i = 0;
9416 	uint32_t offset = 0; /* accumulated offset in the sg request list */
9417 	int inbound = 0; /* number of sg reply entries inbound from firmware */
9418 
9419 	if (!piocbq || !sglq)
9420 		return xritag;
9421 
9422 	sgl  = (struct sli4_sge *)sglq->sgl;
9423 	icmd = &piocbq->iocb;
9424 	if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
9425 		return sglq->sli4_xritag;
9426 	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9427 		numBdes = icmd->un.genreq64.bdl.bdeSize /
9428 				sizeof(struct ulp_bde64);
9429 		/* The addrHigh and addrLow fields within the IOCB
9430 		 * have not been byteswapped yet so there is no
9431 		 * need to swap them back.
9432 		 */
9433 		if (piocbq->context3)
9434 			dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
9435 		else
9436 			return xritag;
9437 
9438 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
9439 		if (!bpl)
9440 			return xritag;
9441 
9442 		for (i = 0; i < numBdes; i++) {
9443 			/* Should already be byte swapped. */
9444 			sgl->addr_hi = bpl->addrHigh;
9445 			sgl->addr_lo = bpl->addrLow;
9446 
9447 			sgl->word2 = le32_to_cpu(sgl->word2);
9448 			if ((i+1) == numBdes)
9449 				bf_set(lpfc_sli4_sge_last, sgl, 1);
9450 			else
9451 				bf_set(lpfc_sli4_sge_last, sgl, 0);
9452 			/* swap the size field back to the cpu so we
9453 			 * can assign it to the sgl.
9454 			 */
9455 			bde.tus.w = le32_to_cpu(bpl->tus.w);
9456 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
9457 			/* The offsets in the sgl need to be accumulated
9458 			 * separately for the request and reply lists.
9459 			 * The request is always first, the reply follows.
9460 			 */
9461 			if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
9462 				/* add up the reply sg entries */
9463 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
9464 					inbound++;
9465 				/* first inbound? reset the offset */
9466 				if (inbound == 1)
9467 					offset = 0;
9468 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
9469 				bf_set(lpfc_sli4_sge_type, sgl,
9470 					LPFC_SGE_TYPE_DATA);
9471 				offset += bde.tus.f.bdeSize;
9472 			}
9473 			sgl->word2 = cpu_to_le32(sgl->word2);
9474 			bpl++;
9475 			sgl++;
9476 		}
9477 	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
9478 			/* The addrHigh and addrLow fields of the BDE have not
9479 			 * been byteswapped yet so they need to be swapped
9480 			 * before putting them in the sgl.
9481 			 */
9482 			sgl->addr_hi =
9483 				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
9484 			sgl->addr_lo =
9485 				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
9486 			sgl->word2 = le32_to_cpu(sgl->word2);
9487 			bf_set(lpfc_sli4_sge_last, sgl, 1);
9488 			sgl->word2 = cpu_to_le32(sgl->word2);
9489 			sgl->sge_len =
9490 				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
9491 	}
9492 	return sglq->sli4_xritag;
9493 }
9494 
9495 /**
9496  * lpfc_sli_iocb2wqe - Convert the IOCB to a work queue entry.
9497  * @phba: Pointer to HBA context object.
9498  * @iocbq: Pointer to command iocb.
9499  * @wqe: Pointer to the work queue entry.
9500  *
9501  * This routine converts the iocb command to its Work Queue Entry
9502  * equivalent. The wqe pointer should not have any fields set when
9503  * this routine is called because it will memcpy over them.
9504  * This routine does not set the CQ_ID or the WQEC bits in the
9505  * wqe.
9506  *
9507  * Returns: 0 = Success, IOCB_ERROR = Failure.
9508  **/
9509 static int
9510 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
9511 		union lpfc_wqe128 *wqe)
9512 {
9513 	uint32_t xmit_len = 0, total_len = 0;
9514 	uint8_t ct = 0;
9515 	uint32_t fip;
9516 	uint32_t abort_tag;
9517 	uint8_t command_type = ELS_COMMAND_NON_FIP;
9518 	uint8_t cmnd;
9519 	uint16_t xritag;
9520 	uint16_t abrt_iotag;
9521 	struct lpfc_iocbq *abrtiocbq;
9522 	struct ulp_bde64 *bpl = NULL;
9523 	uint32_t els_id = LPFC_ELS_ID_DEFAULT;
9524 	int numBdes, i;
9525 	struct ulp_bde64 bde;
9526 	struct lpfc_nodelist *ndlp;
9527 	uint32_t *pcmd;
9528 	uint32_t if_type;
9529 
9530 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
9531 	/* The fcp commands will set command type */
9532 	if (iocbq->iocb_flag &  LPFC_IO_FCP)
9533 		command_type = FCP_COMMAND;
9534 	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
9535 		command_type = ELS_COMMAND_FIP;
9536 	else
9537 		command_type = ELS_COMMAND_NON_FIP;
9538 
9539 	if (phba->fcp_embed_io)
9540 		memset(wqe, 0, sizeof(union lpfc_wqe128));
9541 	/* Some of the fields are in the right position already */
9542 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
9543 	/* The ct field has moved so reset */
9544 	wqe->generic.wqe_com.word7 = 0;
9545 	wqe->generic.wqe_com.word10 = 0;
9546 
9547 	abort_tag = (uint32_t) iocbq->iotag;
9548 	xritag = iocbq->sli4_xritag;
9549 	/* words0-2 bpl convert bde */
9550 	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9551 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
9552 				sizeof(struct ulp_bde64);
9553 		bpl  = (struct ulp_bde64 *)
9554 			((struct lpfc_dmabuf *)iocbq->context3)->virt;
9555 		if (!bpl)
9556 			return IOCB_ERROR;
9557 
9558 		/* Should already be byte swapped. */
9559 		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
9560 		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
9561 		/* swap the size field back to the cpu so we
9562 		 * can assign it to the sgl.
9563 		 */
9564 		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
9565 		xmit_len = wqe->generic.bde.tus.f.bdeSize;
9566 		total_len = 0;
9567 		for (i = 0; i < numBdes; i++) {
9568 			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
9569 			total_len += bde.tus.f.bdeSize;
9570 		}
9571 	} else
9572 		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
9573 
9574 	iocbq->iocb.ulpIoTag = iocbq->iotag;
9575 	cmnd = iocbq->iocb.ulpCommand;
9576 
9577 	switch (iocbq->iocb.ulpCommand) {
9578 	case CMD_ELS_REQUEST64_CR:
9579 		if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
9580 			ndlp = iocbq->context_un.ndlp;
9581 		else
9582 			ndlp = (struct lpfc_nodelist *)iocbq->context1;
9583 		if (!iocbq->iocb.ulpLe) {
9584 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9585 				"2007 Only Limited Edition cmd Format"
9586 				" supported 0x%x\n",
9587 				iocbq->iocb.ulpCommand);
9588 			return IOCB_ERROR;
9589 		}
9590 
9591 		wqe->els_req.payload_len = xmit_len;
9592 		/* Els_reguest64 has a TMO */
9593 		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
9594 			iocbq->iocb.ulpTimeout);
9595 		/* Need a VF for word 4 set the vf bit*/
9596 		bf_set(els_req64_vf, &wqe->els_req, 0);
9597 		/* And a VFID for word 12 */
9598 		bf_set(els_req64_vfid, &wqe->els_req, 0);
9599 		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
9600 		bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9601 		       iocbq->iocb.ulpContext);
9602 		bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
9603 		bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
9604 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
9605 		if (command_type == ELS_COMMAND_FIP)
9606 			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
9607 					>> LPFC_FIP_ELS_ID_SHIFT);
9608 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9609 					iocbq->context2)->virt);
9610 		if_type = bf_get(lpfc_sli_intf_if_type,
9611 					&phba->sli4_hba.sli_intf);
9612 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9613 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
9614 				*pcmd == ELS_CMD_SCR ||
9615 				*pcmd == ELS_CMD_RDF ||
9616 				*pcmd == ELS_CMD_RSCN_XMT ||
9617 				*pcmd == ELS_CMD_FDISC ||
9618 				*pcmd == ELS_CMD_LOGO ||
9619 				*pcmd == ELS_CMD_PLOGI)) {
9620 				bf_set(els_req64_sp, &wqe->els_req, 1);
9621 				bf_set(els_req64_sid, &wqe->els_req,
9622 					iocbq->vport->fc_myDID);
9623 				if ((*pcmd == ELS_CMD_FLOGI) &&
9624 					!(phba->fc_topology ==
9625 						LPFC_TOPOLOGY_LOOP))
9626 					bf_set(els_req64_sid, &wqe->els_req, 0);
9627 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
9628 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9629 					phba->vpi_ids[iocbq->vport->vpi]);
9630 			} else if (pcmd && iocbq->context1) {
9631 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
9632 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9633 					phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9634 			}
9635 		}
9636 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
9637 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9638 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
9639 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
9640 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
9641 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
9642 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
9643 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
9644 		wqe->els_req.max_response_payload_len = total_len - xmit_len;
9645 		break;
9646 	case CMD_XMIT_SEQUENCE64_CX:
9647 		bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
9648 		       iocbq->iocb.un.ulpWord[3]);
9649 		bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
9650 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
9651 		/* The entire sequence is transmitted for this IOCB */
9652 		xmit_len = total_len;
9653 		cmnd = CMD_XMIT_SEQUENCE64_CR;
9654 		if (phba->link_flag & LS_LOOPBACK_MODE)
9655 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
9656 		/* fall through */
9657 	case CMD_XMIT_SEQUENCE64_CR:
9658 		/* word3 iocb=io_tag32 wqe=reserved */
9659 		wqe->xmit_sequence.rsvd3 = 0;
9660 		/* word4 relative_offset memcpy */
9661 		/* word5 r_ctl/df_ctl memcpy */
9662 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
9663 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
9664 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
9665 		       LPFC_WQE_IOD_WRITE);
9666 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
9667 		       LPFC_WQE_LENLOC_WORD12);
9668 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
9669 		wqe->xmit_sequence.xmit_len = xmit_len;
9670 		command_type = OTHER_COMMAND;
9671 		break;
9672 	case CMD_XMIT_BCAST64_CN:
9673 		/* word3 iocb=iotag32 wqe=seq_payload_len */
9674 		wqe->xmit_bcast64.seq_payload_len = xmit_len;
9675 		/* word4 iocb=rsvd wqe=rsvd */
9676 		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
9677 		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
9678 		bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
9679 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9680 		bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
9681 		bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
9682 		bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
9683 		       LPFC_WQE_LENLOC_WORD3);
9684 		bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
9685 		break;
9686 	case CMD_FCP_IWRITE64_CR:
9687 		command_type = FCP_COMMAND_DATA_OUT;
9688 		/* word3 iocb=iotag wqe=payload_offset_len */
9689 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9690 		bf_set(payload_offset_len, &wqe->fcp_iwrite,
9691 		       xmit_len + sizeof(struct fcp_rsp));
9692 		bf_set(cmd_buff_len, &wqe->fcp_iwrite,
9693 		       0);
9694 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9695 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9696 		bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
9697 		       iocbq->iocb.ulpFCP2Rcvy);
9698 		bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
9699 		/* Always open the exchange */
9700 		bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
9701 		bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
9702 		       LPFC_WQE_LENLOC_WORD4);
9703 		bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
9704 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
9705 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9706 			bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
9707 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
9708 			if (iocbq->priority) {
9709 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9710 				       (iocbq->priority << 1));
9711 			} else {
9712 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9713 				       (phba->cfg_XLanePriority << 1));
9714 			}
9715 		}
9716 		/* Note, word 10 is already initialized to 0 */
9717 
9718 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9719 		if (phba->cfg_enable_pbde)
9720 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 1);
9721 		else
9722 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
9723 
9724 		if (phba->fcp_embed_io) {
9725 			struct lpfc_io_buf *lpfc_cmd;
9726 			struct sli4_sge *sgl;
9727 			struct fcp_cmnd *fcp_cmnd;
9728 			uint32_t *ptr;
9729 
9730 			/* 128 byte wqe support here */
9731 
9732 			lpfc_cmd = iocbq->context1;
9733 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9734 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9735 
9736 			/* Word 0-2 - FCP_CMND */
9737 			wqe->generic.bde.tus.f.bdeFlags =
9738 				BUFF_TYPE_BDE_IMMED;
9739 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9740 			wqe->generic.bde.addrHigh = 0;
9741 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9742 
9743 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
9744 			bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
9745 
9746 			/* Word 22-29  FCP CMND Payload */
9747 			ptr = &wqe->words[22];
9748 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9749 		}
9750 		break;
9751 	case CMD_FCP_IREAD64_CR:
9752 		/* word3 iocb=iotag wqe=payload_offset_len */
9753 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9754 		bf_set(payload_offset_len, &wqe->fcp_iread,
9755 		       xmit_len + sizeof(struct fcp_rsp));
9756 		bf_set(cmd_buff_len, &wqe->fcp_iread,
9757 		       0);
9758 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9759 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9760 		bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
9761 		       iocbq->iocb.ulpFCP2Rcvy);
9762 		bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
9763 		/* Always open the exchange */
9764 		bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
9765 		bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
9766 		       LPFC_WQE_LENLOC_WORD4);
9767 		bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
9768 		bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
9769 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9770 			bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
9771 			bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
9772 			if (iocbq->priority) {
9773 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9774 				       (iocbq->priority << 1));
9775 			} else {
9776 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9777 				       (phba->cfg_XLanePriority << 1));
9778 			}
9779 		}
9780 		/* Note, word 10 is already initialized to 0 */
9781 
9782 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9783 		if (phba->cfg_enable_pbde)
9784 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 1);
9785 		else
9786 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
9787 
9788 		if (phba->fcp_embed_io) {
9789 			struct lpfc_io_buf *lpfc_cmd;
9790 			struct sli4_sge *sgl;
9791 			struct fcp_cmnd *fcp_cmnd;
9792 			uint32_t *ptr;
9793 
9794 			/* 128 byte wqe support here */
9795 
9796 			lpfc_cmd = iocbq->context1;
9797 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9798 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9799 
9800 			/* Word 0-2 - FCP_CMND */
9801 			wqe->generic.bde.tus.f.bdeFlags =
9802 				BUFF_TYPE_BDE_IMMED;
9803 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9804 			wqe->generic.bde.addrHigh = 0;
9805 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9806 
9807 			bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
9808 			bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
9809 
9810 			/* Word 22-29  FCP CMND Payload */
9811 			ptr = &wqe->words[22];
9812 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9813 		}
9814 		break;
9815 	case CMD_FCP_ICMND64_CR:
9816 		/* word3 iocb=iotag wqe=payload_offset_len */
9817 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9818 		bf_set(payload_offset_len, &wqe->fcp_icmd,
9819 		       xmit_len + sizeof(struct fcp_rsp));
9820 		bf_set(cmd_buff_len, &wqe->fcp_icmd,
9821 		       0);
9822 		/* word3 iocb=IO_TAG wqe=reserved */
9823 		bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
9824 		/* Always open the exchange */
9825 		bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
9826 		bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
9827 		bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
9828 		bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
9829 		       LPFC_WQE_LENLOC_NONE);
9830 		bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
9831 		       iocbq->iocb.ulpFCP2Rcvy);
9832 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9833 			bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
9834 			bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
9835 			if (iocbq->priority) {
9836 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9837 				       (iocbq->priority << 1));
9838 			} else {
9839 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9840 				       (phba->cfg_XLanePriority << 1));
9841 			}
9842 		}
9843 		/* Note, word 10 is already initialized to 0 */
9844 
9845 		if (phba->fcp_embed_io) {
9846 			struct lpfc_io_buf *lpfc_cmd;
9847 			struct sli4_sge *sgl;
9848 			struct fcp_cmnd *fcp_cmnd;
9849 			uint32_t *ptr;
9850 
9851 			/* 128 byte wqe support here */
9852 
9853 			lpfc_cmd = iocbq->context1;
9854 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9855 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9856 
9857 			/* Word 0-2 - FCP_CMND */
9858 			wqe->generic.bde.tus.f.bdeFlags =
9859 				BUFF_TYPE_BDE_IMMED;
9860 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9861 			wqe->generic.bde.addrHigh = 0;
9862 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9863 
9864 			bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
9865 			bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
9866 
9867 			/* Word 22-29  FCP CMND Payload */
9868 			ptr = &wqe->words[22];
9869 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9870 		}
9871 		break;
9872 	case CMD_GEN_REQUEST64_CR:
9873 		/* For this command calculate the xmit length of the
9874 		 * request bde.
9875 		 */
9876 		xmit_len = 0;
9877 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
9878 			sizeof(struct ulp_bde64);
9879 		for (i = 0; i < numBdes; i++) {
9880 			bde.tus.w = le32_to_cpu(bpl[i].tus.w);
9881 			if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
9882 				break;
9883 			xmit_len += bde.tus.f.bdeSize;
9884 		}
9885 		/* word3 iocb=IO_TAG wqe=request_payload_len */
9886 		wqe->gen_req.request_payload_len = xmit_len;
9887 		/* word4 iocb=parameter wqe=relative_offset memcpy */
9888 		/* word5 [rctl, type, df_ctl, la] copied in memcpy */
9889 		/* word6 context tag copied in memcpy */
9890 		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
9891 			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
9892 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9893 				"2015 Invalid CT %x command 0x%x\n",
9894 				ct, iocbq->iocb.ulpCommand);
9895 			return IOCB_ERROR;
9896 		}
9897 		bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
9898 		bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
9899 		bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
9900 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
9901 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
9902 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
9903 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
9904 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
9905 		wqe->gen_req.max_response_payload_len = total_len - xmit_len;
9906 		command_type = OTHER_COMMAND;
9907 		break;
9908 	case CMD_XMIT_ELS_RSP64_CX:
9909 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
9910 		/* words0-2 BDE memcpy */
9911 		/* word3 iocb=iotag32 wqe=response_payload_len */
9912 		wqe->xmit_els_rsp.response_payload_len = xmit_len;
9913 		/* word4 */
9914 		wqe->xmit_els_rsp.word4 = 0;
9915 		/* word5 iocb=rsvd wge=did */
9916 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
9917 			 iocbq->iocb.un.xseq64.xmit_els_remoteID);
9918 
9919 		if_type = bf_get(lpfc_sli_intf_if_type,
9920 					&phba->sli4_hba.sli_intf);
9921 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9922 			if (iocbq->vport->fc_flag & FC_PT2PT) {
9923 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
9924 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
9925 					iocbq->vport->fc_myDID);
9926 				if (iocbq->vport->fc_myDID == Fabric_DID) {
9927 					bf_set(wqe_els_did,
9928 						&wqe->xmit_els_rsp.wqe_dest, 0);
9929 				}
9930 			}
9931 		}
9932 		bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
9933 		       ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9934 		bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
9935 		bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
9936 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
9937 		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
9938 			bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
9939 			       phba->vpi_ids[iocbq->vport->vpi]);
9940 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
9941 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
9942 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
9943 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
9944 		       LPFC_WQE_LENLOC_WORD3);
9945 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
9946 		bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
9947 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9948 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9949 					iocbq->context2)->virt);
9950 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
9951 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
9952 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
9953 					iocbq->vport->fc_myDID);
9954 				bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
9955 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
9956 					phba->vpi_ids[phba->pport->vpi]);
9957 		}
9958 		command_type = OTHER_COMMAND;
9959 		break;
9960 	case CMD_CLOSE_XRI_CN:
9961 	case CMD_ABORT_XRI_CN:
9962 	case CMD_ABORT_XRI_CX:
9963 		/* words 0-2 memcpy should be 0 rserved */
9964 		/* port will send abts */
9965 		abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
9966 		if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
9967 			abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
9968 			fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
9969 		} else
9970 			fip = 0;
9971 
9972 		if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
9973 			/*
9974 			 * The link is down, or the command was ELS_FIP
9975 			 * so the fw does not need to send abts
9976 			 * on the wire.
9977 			 */
9978 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
9979 		else
9980 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
9981 		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
9982 		/* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
9983 		wqe->abort_cmd.rsrvd5 = 0;
9984 		bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
9985 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9986 		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
9987 		/*
9988 		 * The abort handler will send us CMD_ABORT_XRI_CN or
9989 		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
9990 		 */
9991 		bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
9992 		bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
9993 		bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
9994 		       LPFC_WQE_LENLOC_NONE);
9995 		cmnd = CMD_ABORT_XRI_CX;
9996 		command_type = OTHER_COMMAND;
9997 		xritag = 0;
9998 		break;
9999 	case CMD_XMIT_BLS_RSP64_CX:
10000 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
10001 		/* As BLS ABTS RSP WQE is very different from other WQEs,
10002 		 * we re-construct this WQE here based on information in
10003 		 * iocbq from scratch.
10004 		 */
10005 		memset(wqe, 0, sizeof(*wqe));
10006 		/* OX_ID is invariable to who sent ABTS to CT exchange */
10007 		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
10008 		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
10009 		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
10010 		    LPFC_ABTS_UNSOL_INT) {
10011 			/* ABTS sent by initiator to CT exchange, the
10012 			 * RX_ID field will be filled with the newly
10013 			 * allocated responder XRI.
10014 			 */
10015 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10016 			       iocbq->sli4_xritag);
10017 		} else {
10018 			/* ABTS sent by responder to CT exchange, the
10019 			 * RX_ID field will be filled with the responder
10020 			 * RX_ID from ABTS.
10021 			 */
10022 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10023 			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
10024 		}
10025 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
10026 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
10027 
10028 		/* Use CT=VPI */
10029 		bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
10030 			ndlp->nlp_DID);
10031 		bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
10032 			iocbq->iocb.ulpContext);
10033 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
10034 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
10035 			phba->vpi_ids[phba->pport->vpi]);
10036 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
10037 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
10038 		       LPFC_WQE_LENLOC_NONE);
10039 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
10040 		command_type = OTHER_COMMAND;
10041 		if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
10042 			bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
10043 			       bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
10044 			bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
10045 			       bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
10046 			bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
10047 			       bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
10048 		}
10049 
10050 		break;
10051 	case CMD_SEND_FRAME:
10052 		bf_set(wqe_cmnd, &wqe->generic.wqe_com, CMD_SEND_FRAME);
10053 		bf_set(wqe_sof, &wqe->generic.wqe_com, 0x2E); /* SOF byte */
10054 		bf_set(wqe_eof, &wqe->generic.wqe_com, 0x41); /* EOF byte */
10055 		bf_set(wqe_lenloc, &wqe->generic.wqe_com, 1);
10056 		bf_set(wqe_xbl, &wqe->generic.wqe_com, 1);
10057 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10058 		bf_set(wqe_xc, &wqe->generic.wqe_com, 1);
10059 		bf_set(wqe_cmd_type, &wqe->generic.wqe_com, 0xA);
10060 		bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10061 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10062 		bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10063 		return 0;
10064 	case CMD_XRI_ABORTED_CX:
10065 	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
10066 	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
10067 	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
10068 	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
10069 	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
10070 	default:
10071 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10072 				"2014 Invalid command 0x%x\n",
10073 				iocbq->iocb.ulpCommand);
10074 		return IOCB_ERROR;
10075 		break;
10076 	}
10077 
10078 	if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
10079 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
10080 	else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
10081 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
10082 	else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
10083 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
10084 	iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
10085 			      LPFC_IO_DIF_INSERT);
10086 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10087 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10088 	wqe->generic.wqe_com.abort_tag = abort_tag;
10089 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
10090 	bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
10091 	bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
10092 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10093 	return 0;
10094 }
10095 
10096 /**
10097  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10098  * @phba: Pointer to HBA context object.
10099  * @ring_number: SLI ring number to issue iocb on.
10100  * @piocb: Pointer to command iocb.
10101  * @flag: Flag indicating if this command can be put into txq.
10102  *
10103  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10104  * an iocb command to an HBA with SLI-4 interface spec.
10105  *
10106  * This function is called with ringlock held. The function will return success
10107  * after it successfully submit the iocb to firmware or after adding to the
10108  * txq.
10109  **/
10110 static int
10111 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10112 			 struct lpfc_iocbq *piocb, uint32_t flag)
10113 {
10114 	struct lpfc_sglq *sglq;
10115 	union lpfc_wqe128 wqe;
10116 	struct lpfc_queue *wq;
10117 	struct lpfc_sli_ring *pring;
10118 
10119 	/* Get the WQ */
10120 	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
10121 	    (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
10122 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10123 	} else {
10124 		wq = phba->sli4_hba.els_wq;
10125 	}
10126 
10127 	/* Get corresponding ring */
10128 	pring = wq->pring;
10129 
10130 	/*
10131 	 * The WQE can be either 64 or 128 bytes,
10132 	 */
10133 
10134 	lockdep_assert_held(&pring->ring_lock);
10135 
10136 	if (piocb->sli4_xritag == NO_XRI) {
10137 		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
10138 		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
10139 			sglq = NULL;
10140 		else {
10141 			if (!list_empty(&pring->txq)) {
10142 				if (!(flag & SLI_IOCB_RET_IOCB)) {
10143 					__lpfc_sli_ringtx_put(phba,
10144 						pring, piocb);
10145 					return IOCB_SUCCESS;
10146 				} else {
10147 					return IOCB_BUSY;
10148 				}
10149 			} else {
10150 				sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10151 				if (!sglq) {
10152 					if (!(flag & SLI_IOCB_RET_IOCB)) {
10153 						__lpfc_sli_ringtx_put(phba,
10154 								pring,
10155 								piocb);
10156 						return IOCB_SUCCESS;
10157 					} else
10158 						return IOCB_BUSY;
10159 				}
10160 			}
10161 		}
10162 	} else if (piocb->iocb_flag &  LPFC_IO_FCP)
10163 		/* These IO's already have an XRI and a mapped sgl. */
10164 		sglq = NULL;
10165 	else {
10166 		/*
10167 		 * This is a continuation of a commandi,(CX) so this
10168 		 * sglq is on the active list
10169 		 */
10170 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10171 		if (!sglq)
10172 			return IOCB_ERROR;
10173 	}
10174 
10175 	if (sglq) {
10176 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10177 		piocb->sli4_xritag = sglq->sli4_xritag;
10178 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
10179 			return IOCB_ERROR;
10180 	}
10181 
10182 	if (lpfc_sli4_iocb2wqe(phba, piocb, &wqe))
10183 		return IOCB_ERROR;
10184 
10185 	if (lpfc_sli4_wq_put(wq, &wqe))
10186 		return IOCB_ERROR;
10187 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10188 
10189 	return 0;
10190 }
10191 
10192 /*
10193  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10194  *
10195  * This routine wraps the actual lockless version for issusing IOCB function
10196  * pointer from the lpfc_hba struct.
10197  *
10198  * Return codes:
10199  * IOCB_ERROR - Error
10200  * IOCB_SUCCESS - Success
10201  * IOCB_BUSY - Busy
10202  **/
10203 int
10204 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10205 		struct lpfc_iocbq *piocb, uint32_t flag)
10206 {
10207 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10208 }
10209 
10210 /**
10211  * lpfc_sli_api_table_setup - Set up sli api function jump table
10212  * @phba: The hba struct for which this call is being executed.
10213  * @dev_grp: The HBA PCI-Device group number.
10214  *
10215  * This routine sets up the SLI interface API function jump table in @phba
10216  * struct.
10217  * Returns: 0 - success, -ENODEV - failure.
10218  **/
10219 int
10220 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10221 {
10222 
10223 	switch (dev_grp) {
10224 	case LPFC_PCI_DEV_LP:
10225 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
10226 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
10227 		break;
10228 	case LPFC_PCI_DEV_OC:
10229 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
10230 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
10231 		break;
10232 	default:
10233 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10234 				"1419 Invalid HBA PCI-device group: 0x%x\n",
10235 				dev_grp);
10236 		return -ENODEV;
10237 		break;
10238 	}
10239 	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
10240 	return 0;
10241 }
10242 
10243 /**
10244  * lpfc_sli4_calc_ring - Calculates which ring to use
10245  * @phba: Pointer to HBA context object.
10246  * @piocb: Pointer to command iocb.
10247  *
10248  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
10249  * hba_wqidx, thus we need to calculate the corresponding ring.
10250  * Since ABORTS must go on the same WQ of the command they are
10251  * aborting, we use command's hba_wqidx.
10252  */
10253 struct lpfc_sli_ring *
10254 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
10255 {
10256 	struct lpfc_io_buf *lpfc_cmd;
10257 
10258 	if (piocb->iocb_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
10259 		if (unlikely(!phba->sli4_hba.hdwq))
10260 			return NULL;
10261 		/*
10262 		 * for abort iocb hba_wqidx should already
10263 		 * be setup based on what work queue we used.
10264 		 */
10265 		if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
10266 			lpfc_cmd = (struct lpfc_io_buf *)piocb->context1;
10267 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
10268 		}
10269 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
10270 	} else {
10271 		if (unlikely(!phba->sli4_hba.els_wq))
10272 			return NULL;
10273 		piocb->hba_wqidx = 0;
10274 		return phba->sli4_hba.els_wq->pring;
10275 	}
10276 }
10277 
10278 /**
10279  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
10280  * @phba: Pointer to HBA context object.
10281  * @ring_number: Ring number
10282  * @piocb: Pointer to command iocb.
10283  * @flag: Flag indicating if this command can be put into txq.
10284  *
10285  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
10286  * function. This function gets the hbalock and calls
10287  * __lpfc_sli_issue_iocb function and will return the error returned
10288  * by __lpfc_sli_issue_iocb function. This wrapper is used by
10289  * functions which do not hold hbalock.
10290  **/
10291 int
10292 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10293 		    struct lpfc_iocbq *piocb, uint32_t flag)
10294 {
10295 	struct lpfc_sli_ring *pring;
10296 	struct lpfc_queue *eq;
10297 	unsigned long iflags;
10298 	int rc;
10299 
10300 	if (phba->sli_rev == LPFC_SLI_REV4) {
10301 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
10302 
10303 		pring = lpfc_sli4_calc_ring(phba, piocb);
10304 		if (unlikely(pring == NULL))
10305 			return IOCB_ERROR;
10306 
10307 		spin_lock_irqsave(&pring->ring_lock, iflags);
10308 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10309 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
10310 
10311 		lpfc_sli4_poll_eq(eq, LPFC_POLL_FASTPATH);
10312 	} else {
10313 		/* For now, SLI2/3 will still use hbalock */
10314 		spin_lock_irqsave(&phba->hbalock, iflags);
10315 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10316 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10317 	}
10318 	return rc;
10319 }
10320 
10321 /**
10322  * lpfc_extra_ring_setup - Extra ring setup function
10323  * @phba: Pointer to HBA context object.
10324  *
10325  * This function is called while driver attaches with the
10326  * HBA to setup the extra ring. The extra ring is used
10327  * only when driver needs to support target mode functionality
10328  * or IP over FC functionalities.
10329  *
10330  * This function is called with no lock held. SLI3 only.
10331  **/
10332 static int
10333 lpfc_extra_ring_setup( struct lpfc_hba *phba)
10334 {
10335 	struct lpfc_sli *psli;
10336 	struct lpfc_sli_ring *pring;
10337 
10338 	psli = &phba->sli;
10339 
10340 	/* Adjust cmd/rsp ring iocb entries more evenly */
10341 
10342 	/* Take some away from the FCP ring */
10343 	pring = &psli->sli3_ring[LPFC_FCP_RING];
10344 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10345 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10346 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10347 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10348 
10349 	/* and give them to the extra ring */
10350 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
10351 
10352 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10353 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10354 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10355 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10356 
10357 	/* Setup default profile for this ring */
10358 	pring->iotag_max = 4096;
10359 	pring->num_mask = 1;
10360 	pring->prt[0].profile = 0;      /* Mask 0 */
10361 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
10362 	pring->prt[0].type = phba->cfg_multi_ring_type;
10363 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
10364 	return 0;
10365 }
10366 
10367 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
10368  * @phba: Pointer to HBA context object.
10369  * @iocbq: Pointer to iocb object.
10370  *
10371  * The async_event handler calls this routine when it receives
10372  * an ASYNC_STATUS_CN event from the port.  The port generates
10373  * this event when an Abort Sequence request to an rport fails
10374  * twice in succession.  The abort could be originated by the
10375  * driver or by the port.  The ABTS could have been for an ELS
10376  * or FCP IO.  The port only generates this event when an ABTS
10377  * fails to complete after one retry.
10378  */
10379 static void
10380 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
10381 			  struct lpfc_iocbq *iocbq)
10382 {
10383 	struct lpfc_nodelist *ndlp = NULL;
10384 	uint16_t rpi = 0, vpi = 0;
10385 	struct lpfc_vport *vport = NULL;
10386 
10387 	/* The rpi in the ulpContext is vport-sensitive. */
10388 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
10389 	rpi = iocbq->iocb.ulpContext;
10390 
10391 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10392 			"3092 Port generated ABTS async event "
10393 			"on vpi %d rpi %d status 0x%x\n",
10394 			vpi, rpi, iocbq->iocb.ulpStatus);
10395 
10396 	vport = lpfc_find_vport_by_vpid(phba, vpi);
10397 	if (!vport)
10398 		goto err_exit;
10399 	ndlp = lpfc_findnode_rpi(vport, rpi);
10400 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp))
10401 		goto err_exit;
10402 
10403 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
10404 		lpfc_sli_abts_recover_port(vport, ndlp);
10405 	return;
10406 
10407  err_exit:
10408 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10409 			"3095 Event Context not found, no "
10410 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
10411 			iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
10412 			vpi, rpi);
10413 }
10414 
10415 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
10416  * @phba: pointer to HBA context object.
10417  * @ndlp: nodelist pointer for the impacted rport.
10418  * @axri: pointer to the wcqe containing the failed exchange.
10419  *
10420  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
10421  * port.  The port generates this event when an abort exchange request to an
10422  * rport fails twice in succession with no reply.  The abort could be originated
10423  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
10424  */
10425 void
10426 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
10427 			   struct lpfc_nodelist *ndlp,
10428 			   struct sli4_wcqe_xri_aborted *axri)
10429 {
10430 	struct lpfc_vport *vport;
10431 	uint32_t ext_status = 0;
10432 
10433 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
10434 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10435 				"3115 Node Context not found, driver "
10436 				"ignoring abts err event\n");
10437 		return;
10438 	}
10439 
10440 	vport = ndlp->vport;
10441 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10442 			"3116 Port generated FCP XRI ABORT event on "
10443 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
10444 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
10445 			bf_get(lpfc_wcqe_xa_xri, axri),
10446 			bf_get(lpfc_wcqe_xa_status, axri),
10447 			axri->parameter);
10448 
10449 	/*
10450 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
10451 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
10452 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
10453 	 */
10454 	ext_status = axri->parameter & IOERR_PARAM_MASK;
10455 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
10456 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
10457 		lpfc_sli_abts_recover_port(vport, ndlp);
10458 }
10459 
10460 /**
10461  * lpfc_sli_async_event_handler - ASYNC iocb handler function
10462  * @phba: Pointer to HBA context object.
10463  * @pring: Pointer to driver SLI ring object.
10464  * @iocbq: Pointer to iocb object.
10465  *
10466  * This function is called by the slow ring event handler
10467  * function when there is an ASYNC event iocb in the ring.
10468  * This function is called with no lock held.
10469  * Currently this function handles only temperature related
10470  * ASYNC events. The function decodes the temperature sensor
10471  * event message and posts events for the management applications.
10472  **/
10473 static void
10474 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
10475 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
10476 {
10477 	IOCB_t *icmd;
10478 	uint16_t evt_code;
10479 	struct temp_event temp_event_data;
10480 	struct Scsi_Host *shost;
10481 	uint32_t *iocb_w;
10482 
10483 	icmd = &iocbq->iocb;
10484 	evt_code = icmd->un.asyncstat.evt_code;
10485 
10486 	switch (evt_code) {
10487 	case ASYNC_TEMP_WARN:
10488 	case ASYNC_TEMP_SAFE:
10489 		temp_event_data.data = (uint32_t) icmd->ulpContext;
10490 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
10491 		if (evt_code == ASYNC_TEMP_WARN) {
10492 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
10493 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10494 				"0347 Adapter is very hot, please take "
10495 				"corrective action. temperature : %d Celsius\n",
10496 				(uint32_t) icmd->ulpContext);
10497 		} else {
10498 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
10499 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10500 				"0340 Adapter temperature is OK now. "
10501 				"temperature : %d Celsius\n",
10502 				(uint32_t) icmd->ulpContext);
10503 		}
10504 
10505 		/* Send temperature change event to applications */
10506 		shost = lpfc_shost_from_vport(phba->pport);
10507 		fc_host_post_vendor_event(shost, fc_get_event_number(),
10508 			sizeof(temp_event_data), (char *) &temp_event_data,
10509 			LPFC_NL_VENDOR_ID);
10510 		break;
10511 	case ASYNC_STATUS_CN:
10512 		lpfc_sli_abts_err_handler(phba, iocbq);
10513 		break;
10514 	default:
10515 		iocb_w = (uint32_t *) icmd;
10516 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10517 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
10518 			" evt_code 0x%x\n"
10519 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
10520 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
10521 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
10522 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
10523 			pring->ringno, icmd->un.asyncstat.evt_code,
10524 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
10525 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
10526 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
10527 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
10528 
10529 		break;
10530 	}
10531 }
10532 
10533 
10534 /**
10535  * lpfc_sli4_setup - SLI ring setup function
10536  * @phba: Pointer to HBA context object.
10537  *
10538  * lpfc_sli_setup sets up rings of the SLI interface with
10539  * number of iocbs per ring and iotags. This function is
10540  * called while driver attach to the HBA and before the
10541  * interrupts are enabled. So there is no need for locking.
10542  *
10543  * This function always returns 0.
10544  **/
10545 int
10546 lpfc_sli4_setup(struct lpfc_hba *phba)
10547 {
10548 	struct lpfc_sli_ring *pring;
10549 
10550 	pring = phba->sli4_hba.els_wq->pring;
10551 	pring->num_mask = LPFC_MAX_RING_MASK;
10552 	pring->prt[0].profile = 0;	/* Mask 0 */
10553 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10554 	pring->prt[0].type = FC_TYPE_ELS;
10555 	pring->prt[0].lpfc_sli_rcv_unsol_event =
10556 	    lpfc_els_unsol_event;
10557 	pring->prt[1].profile = 0;	/* Mask 1 */
10558 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
10559 	pring->prt[1].type = FC_TYPE_ELS;
10560 	pring->prt[1].lpfc_sli_rcv_unsol_event =
10561 	    lpfc_els_unsol_event;
10562 	pring->prt[2].profile = 0;	/* Mask 2 */
10563 	/* NameServer Inquiry */
10564 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10565 	/* NameServer */
10566 	pring->prt[2].type = FC_TYPE_CT;
10567 	pring->prt[2].lpfc_sli_rcv_unsol_event =
10568 	    lpfc_ct_unsol_event;
10569 	pring->prt[3].profile = 0;	/* Mask 3 */
10570 	/* NameServer response */
10571 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10572 	/* NameServer */
10573 	pring->prt[3].type = FC_TYPE_CT;
10574 	pring->prt[3].lpfc_sli_rcv_unsol_event =
10575 	    lpfc_ct_unsol_event;
10576 	return 0;
10577 }
10578 
10579 /**
10580  * lpfc_sli_setup - SLI ring setup function
10581  * @phba: Pointer to HBA context object.
10582  *
10583  * lpfc_sli_setup sets up rings of the SLI interface with
10584  * number of iocbs per ring and iotags. This function is
10585  * called while driver attach to the HBA and before the
10586  * interrupts are enabled. So there is no need for locking.
10587  *
10588  * This function always returns 0. SLI3 only.
10589  **/
10590 int
10591 lpfc_sli_setup(struct lpfc_hba *phba)
10592 {
10593 	int i, totiocbsize = 0;
10594 	struct lpfc_sli *psli = &phba->sli;
10595 	struct lpfc_sli_ring *pring;
10596 
10597 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
10598 	psli->sli_flag = 0;
10599 
10600 	psli->iocbq_lookup = NULL;
10601 	psli->iocbq_lookup_len = 0;
10602 	psli->last_iotag = 0;
10603 
10604 	for (i = 0; i < psli->num_rings; i++) {
10605 		pring = &psli->sli3_ring[i];
10606 		switch (i) {
10607 		case LPFC_FCP_RING:	/* ring 0 - FCP */
10608 			/* numCiocb and numRiocb are used in config_port */
10609 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
10610 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
10611 			pring->sli.sli3.numCiocb +=
10612 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10613 			pring->sli.sli3.numRiocb +=
10614 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10615 			pring->sli.sli3.numCiocb +=
10616 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10617 			pring->sli.sli3.numRiocb +=
10618 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10619 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10620 							SLI3_IOCB_CMD_SIZE :
10621 							SLI2_IOCB_CMD_SIZE;
10622 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10623 							SLI3_IOCB_RSP_SIZE :
10624 							SLI2_IOCB_RSP_SIZE;
10625 			pring->iotag_ctr = 0;
10626 			pring->iotag_max =
10627 			    (phba->cfg_hba_queue_depth * 2);
10628 			pring->fast_iotag = pring->iotag_max;
10629 			pring->num_mask = 0;
10630 			break;
10631 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
10632 			/* numCiocb and numRiocb are used in config_port */
10633 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
10634 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
10635 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10636 							SLI3_IOCB_CMD_SIZE :
10637 							SLI2_IOCB_CMD_SIZE;
10638 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10639 							SLI3_IOCB_RSP_SIZE :
10640 							SLI2_IOCB_RSP_SIZE;
10641 			pring->iotag_max = phba->cfg_hba_queue_depth;
10642 			pring->num_mask = 0;
10643 			break;
10644 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
10645 			/* numCiocb and numRiocb are used in config_port */
10646 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
10647 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
10648 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10649 							SLI3_IOCB_CMD_SIZE :
10650 							SLI2_IOCB_CMD_SIZE;
10651 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10652 							SLI3_IOCB_RSP_SIZE :
10653 							SLI2_IOCB_RSP_SIZE;
10654 			pring->fast_iotag = 0;
10655 			pring->iotag_ctr = 0;
10656 			pring->iotag_max = 4096;
10657 			pring->lpfc_sli_rcv_async_status =
10658 				lpfc_sli_async_event_handler;
10659 			pring->num_mask = LPFC_MAX_RING_MASK;
10660 			pring->prt[0].profile = 0;	/* Mask 0 */
10661 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10662 			pring->prt[0].type = FC_TYPE_ELS;
10663 			pring->prt[0].lpfc_sli_rcv_unsol_event =
10664 			    lpfc_els_unsol_event;
10665 			pring->prt[1].profile = 0;	/* Mask 1 */
10666 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
10667 			pring->prt[1].type = FC_TYPE_ELS;
10668 			pring->prt[1].lpfc_sli_rcv_unsol_event =
10669 			    lpfc_els_unsol_event;
10670 			pring->prt[2].profile = 0;	/* Mask 2 */
10671 			/* NameServer Inquiry */
10672 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10673 			/* NameServer */
10674 			pring->prt[2].type = FC_TYPE_CT;
10675 			pring->prt[2].lpfc_sli_rcv_unsol_event =
10676 			    lpfc_ct_unsol_event;
10677 			pring->prt[3].profile = 0;	/* Mask 3 */
10678 			/* NameServer response */
10679 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10680 			/* NameServer */
10681 			pring->prt[3].type = FC_TYPE_CT;
10682 			pring->prt[3].lpfc_sli_rcv_unsol_event =
10683 			    lpfc_ct_unsol_event;
10684 			break;
10685 		}
10686 		totiocbsize += (pring->sli.sli3.numCiocb *
10687 			pring->sli.sli3.sizeCiocb) +
10688 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
10689 	}
10690 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
10691 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
10692 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
10693 		       "SLI2 SLIM Data: x%x x%lx\n",
10694 		       phba->brd_no, totiocbsize,
10695 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
10696 	}
10697 	if (phba->cfg_multi_ring_support == 2)
10698 		lpfc_extra_ring_setup(phba);
10699 
10700 	return 0;
10701 }
10702 
10703 /**
10704  * lpfc_sli4_queue_init - Queue initialization function
10705  * @phba: Pointer to HBA context object.
10706  *
10707  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
10708  * ring. This function also initializes ring indices of each ring.
10709  * This function is called during the initialization of the SLI
10710  * interface of an HBA.
10711  * This function is called with no lock held and always returns
10712  * 1.
10713  **/
10714 void
10715 lpfc_sli4_queue_init(struct lpfc_hba *phba)
10716 {
10717 	struct lpfc_sli *psli;
10718 	struct lpfc_sli_ring *pring;
10719 	int i;
10720 
10721 	psli = &phba->sli;
10722 	spin_lock_irq(&phba->hbalock);
10723 	INIT_LIST_HEAD(&psli->mboxq);
10724 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
10725 	/* Initialize list headers for txq and txcmplq as double linked lists */
10726 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
10727 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
10728 		pring->flag = 0;
10729 		pring->ringno = LPFC_FCP_RING;
10730 		pring->txcmplq_cnt = 0;
10731 		INIT_LIST_HEAD(&pring->txq);
10732 		INIT_LIST_HEAD(&pring->txcmplq);
10733 		INIT_LIST_HEAD(&pring->iocb_continueq);
10734 		spin_lock_init(&pring->ring_lock);
10735 	}
10736 	pring = phba->sli4_hba.els_wq->pring;
10737 	pring->flag = 0;
10738 	pring->ringno = LPFC_ELS_RING;
10739 	pring->txcmplq_cnt = 0;
10740 	INIT_LIST_HEAD(&pring->txq);
10741 	INIT_LIST_HEAD(&pring->txcmplq);
10742 	INIT_LIST_HEAD(&pring->iocb_continueq);
10743 	spin_lock_init(&pring->ring_lock);
10744 
10745 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10746 		pring = phba->sli4_hba.nvmels_wq->pring;
10747 		pring->flag = 0;
10748 		pring->ringno = LPFC_ELS_RING;
10749 		pring->txcmplq_cnt = 0;
10750 		INIT_LIST_HEAD(&pring->txq);
10751 		INIT_LIST_HEAD(&pring->txcmplq);
10752 		INIT_LIST_HEAD(&pring->iocb_continueq);
10753 		spin_lock_init(&pring->ring_lock);
10754 	}
10755 
10756 	spin_unlock_irq(&phba->hbalock);
10757 }
10758 
10759 /**
10760  * lpfc_sli_queue_init - Queue initialization function
10761  * @phba: Pointer to HBA context object.
10762  *
10763  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
10764  * ring. This function also initializes ring indices of each ring.
10765  * This function is called during the initialization of the SLI
10766  * interface of an HBA.
10767  * This function is called with no lock held and always returns
10768  * 1.
10769  **/
10770 void
10771 lpfc_sli_queue_init(struct lpfc_hba *phba)
10772 {
10773 	struct lpfc_sli *psli;
10774 	struct lpfc_sli_ring *pring;
10775 	int i;
10776 
10777 	psli = &phba->sli;
10778 	spin_lock_irq(&phba->hbalock);
10779 	INIT_LIST_HEAD(&psli->mboxq);
10780 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
10781 	/* Initialize list headers for txq and txcmplq as double linked lists */
10782 	for (i = 0; i < psli->num_rings; i++) {
10783 		pring = &psli->sli3_ring[i];
10784 		pring->ringno = i;
10785 		pring->sli.sli3.next_cmdidx  = 0;
10786 		pring->sli.sli3.local_getidx = 0;
10787 		pring->sli.sli3.cmdidx = 0;
10788 		INIT_LIST_HEAD(&pring->iocb_continueq);
10789 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
10790 		INIT_LIST_HEAD(&pring->postbufq);
10791 		pring->flag = 0;
10792 		INIT_LIST_HEAD(&pring->txq);
10793 		INIT_LIST_HEAD(&pring->txcmplq);
10794 		spin_lock_init(&pring->ring_lock);
10795 	}
10796 	spin_unlock_irq(&phba->hbalock);
10797 }
10798 
10799 /**
10800  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
10801  * @phba: Pointer to HBA context object.
10802  *
10803  * This routine flushes the mailbox command subsystem. It will unconditionally
10804  * flush all the mailbox commands in the three possible stages in the mailbox
10805  * command sub-system: pending mailbox command queue; the outstanding mailbox
10806  * command; and completed mailbox command queue. It is caller's responsibility
10807  * to make sure that the driver is in the proper state to flush the mailbox
10808  * command sub-system. Namely, the posting of mailbox commands into the
10809  * pending mailbox command queue from the various clients must be stopped;
10810  * either the HBA is in a state that it will never works on the outstanding
10811  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
10812  * mailbox command has been completed.
10813  **/
10814 static void
10815 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
10816 {
10817 	LIST_HEAD(completions);
10818 	struct lpfc_sli *psli = &phba->sli;
10819 	LPFC_MBOXQ_t *pmb;
10820 	unsigned long iflag;
10821 
10822 	/* Disable softirqs, including timers from obtaining phba->hbalock */
10823 	local_bh_disable();
10824 
10825 	/* Flush all the mailbox commands in the mbox system */
10826 	spin_lock_irqsave(&phba->hbalock, iflag);
10827 
10828 	/* The pending mailbox command queue */
10829 	list_splice_init(&phba->sli.mboxq, &completions);
10830 	/* The outstanding active mailbox command */
10831 	if (psli->mbox_active) {
10832 		list_add_tail(&psli->mbox_active->list, &completions);
10833 		psli->mbox_active = NULL;
10834 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10835 	}
10836 	/* The completed mailbox command queue */
10837 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
10838 	spin_unlock_irqrestore(&phba->hbalock, iflag);
10839 
10840 	/* Enable softirqs again, done with phba->hbalock */
10841 	local_bh_enable();
10842 
10843 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
10844 	while (!list_empty(&completions)) {
10845 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
10846 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
10847 		if (pmb->mbox_cmpl)
10848 			pmb->mbox_cmpl(phba, pmb);
10849 	}
10850 }
10851 
10852 /**
10853  * lpfc_sli_host_down - Vport cleanup function
10854  * @vport: Pointer to virtual port object.
10855  *
10856  * lpfc_sli_host_down is called to clean up the resources
10857  * associated with a vport before destroying virtual
10858  * port data structures.
10859  * This function does following operations:
10860  * - Free discovery resources associated with this virtual
10861  *   port.
10862  * - Free iocbs associated with this virtual port in
10863  *   the txq.
10864  * - Send abort for all iocb commands associated with this
10865  *   vport in txcmplq.
10866  *
10867  * This function is called with no lock held and always returns 1.
10868  **/
10869 int
10870 lpfc_sli_host_down(struct lpfc_vport *vport)
10871 {
10872 	LIST_HEAD(completions);
10873 	struct lpfc_hba *phba = vport->phba;
10874 	struct lpfc_sli *psli = &phba->sli;
10875 	struct lpfc_queue *qp = NULL;
10876 	struct lpfc_sli_ring *pring;
10877 	struct lpfc_iocbq *iocb, *next_iocb;
10878 	int i;
10879 	unsigned long flags = 0;
10880 	uint16_t prev_pring_flag;
10881 
10882 	lpfc_cleanup_discovery_resources(vport);
10883 
10884 	spin_lock_irqsave(&phba->hbalock, flags);
10885 
10886 	/*
10887 	 * Error everything on the txq since these iocbs
10888 	 * have not been given to the FW yet.
10889 	 * Also issue ABTS for everything on the txcmplq
10890 	 */
10891 	if (phba->sli_rev != LPFC_SLI_REV4) {
10892 		for (i = 0; i < psli->num_rings; i++) {
10893 			pring = &psli->sli3_ring[i];
10894 			prev_pring_flag = pring->flag;
10895 			/* Only slow rings */
10896 			if (pring->ringno == LPFC_ELS_RING) {
10897 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10898 				/* Set the lpfc data pending flag */
10899 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10900 			}
10901 			list_for_each_entry_safe(iocb, next_iocb,
10902 						 &pring->txq, list) {
10903 				if (iocb->vport != vport)
10904 					continue;
10905 				list_move_tail(&iocb->list, &completions);
10906 			}
10907 			list_for_each_entry_safe(iocb, next_iocb,
10908 						 &pring->txcmplq, list) {
10909 				if (iocb->vport != vport)
10910 					continue;
10911 				lpfc_sli_issue_abort_iotag(phba, pring, iocb);
10912 			}
10913 			pring->flag = prev_pring_flag;
10914 		}
10915 	} else {
10916 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
10917 			pring = qp->pring;
10918 			if (!pring)
10919 				continue;
10920 			if (pring == phba->sli4_hba.els_wq->pring) {
10921 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10922 				/* Set the lpfc data pending flag */
10923 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10924 			}
10925 			prev_pring_flag = pring->flag;
10926 			spin_lock(&pring->ring_lock);
10927 			list_for_each_entry_safe(iocb, next_iocb,
10928 						 &pring->txq, list) {
10929 				if (iocb->vport != vport)
10930 					continue;
10931 				list_move_tail(&iocb->list, &completions);
10932 			}
10933 			spin_unlock(&pring->ring_lock);
10934 			list_for_each_entry_safe(iocb, next_iocb,
10935 						 &pring->txcmplq, list) {
10936 				if (iocb->vport != vport)
10937 					continue;
10938 				lpfc_sli_issue_abort_iotag(phba, pring, iocb);
10939 			}
10940 			pring->flag = prev_pring_flag;
10941 		}
10942 	}
10943 	spin_unlock_irqrestore(&phba->hbalock, flags);
10944 
10945 	/* Cancel all the IOCBs from the completions list */
10946 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
10947 			      IOERR_SLI_DOWN);
10948 	return 1;
10949 }
10950 
10951 /**
10952  * lpfc_sli_hba_down - Resource cleanup function for the HBA
10953  * @phba: Pointer to HBA context object.
10954  *
10955  * This function cleans up all iocb, buffers, mailbox commands
10956  * while shutting down the HBA. This function is called with no
10957  * lock held and always returns 1.
10958  * This function does the following to cleanup driver resources:
10959  * - Free discovery resources for each virtual port
10960  * - Cleanup any pending fabric iocbs
10961  * - Iterate through the iocb txq and free each entry
10962  *   in the list.
10963  * - Free up any buffer posted to the HBA
10964  * - Free mailbox commands in the mailbox queue.
10965  **/
10966 int
10967 lpfc_sli_hba_down(struct lpfc_hba *phba)
10968 {
10969 	LIST_HEAD(completions);
10970 	struct lpfc_sli *psli = &phba->sli;
10971 	struct lpfc_queue *qp = NULL;
10972 	struct lpfc_sli_ring *pring;
10973 	struct lpfc_dmabuf *buf_ptr;
10974 	unsigned long flags = 0;
10975 	int i;
10976 
10977 	/* Shutdown the mailbox command sub-system */
10978 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
10979 
10980 	lpfc_hba_down_prep(phba);
10981 
10982 	/* Disable softirqs, including timers from obtaining phba->hbalock */
10983 	local_bh_disable();
10984 
10985 	lpfc_fabric_abort_hba(phba);
10986 
10987 	spin_lock_irqsave(&phba->hbalock, flags);
10988 
10989 	/*
10990 	 * Error everything on the txq since these iocbs
10991 	 * have not been given to the FW yet.
10992 	 */
10993 	if (phba->sli_rev != LPFC_SLI_REV4) {
10994 		for (i = 0; i < psli->num_rings; i++) {
10995 			pring = &psli->sli3_ring[i];
10996 			/* Only slow rings */
10997 			if (pring->ringno == LPFC_ELS_RING) {
10998 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10999 				/* Set the lpfc data pending flag */
11000 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11001 			}
11002 			list_splice_init(&pring->txq, &completions);
11003 		}
11004 	} else {
11005 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11006 			pring = qp->pring;
11007 			if (!pring)
11008 				continue;
11009 			spin_lock(&pring->ring_lock);
11010 			list_splice_init(&pring->txq, &completions);
11011 			spin_unlock(&pring->ring_lock);
11012 			if (pring == phba->sli4_hba.els_wq->pring) {
11013 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11014 				/* Set the lpfc data pending flag */
11015 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11016 			}
11017 		}
11018 	}
11019 	spin_unlock_irqrestore(&phba->hbalock, flags);
11020 
11021 	/* Cancel all the IOCBs from the completions list */
11022 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11023 			      IOERR_SLI_DOWN);
11024 
11025 	spin_lock_irqsave(&phba->hbalock, flags);
11026 	list_splice_init(&phba->elsbuf, &completions);
11027 	phba->elsbuf_cnt = 0;
11028 	phba->elsbuf_prev_cnt = 0;
11029 	spin_unlock_irqrestore(&phba->hbalock, flags);
11030 
11031 	while (!list_empty(&completions)) {
11032 		list_remove_head(&completions, buf_ptr,
11033 			struct lpfc_dmabuf, list);
11034 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
11035 		kfree(buf_ptr);
11036 	}
11037 
11038 	/* Enable softirqs again, done with phba->hbalock */
11039 	local_bh_enable();
11040 
11041 	/* Return any active mbox cmds */
11042 	del_timer_sync(&psli->mbox_tmo);
11043 
11044 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
11045 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
11046 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
11047 
11048 	return 1;
11049 }
11050 
11051 /**
11052  * lpfc_sli_pcimem_bcopy - SLI memory copy function
11053  * @srcp: Source memory pointer.
11054  * @destp: Destination memory pointer.
11055  * @cnt: Number of words required to be copied.
11056  *
11057  * This function is used for copying data between driver memory
11058  * and the SLI memory. This function also changes the endianness
11059  * of each word if native endianness is different from SLI
11060  * endianness. This function can be called with or without
11061  * lock.
11062  **/
11063 void
11064 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
11065 {
11066 	uint32_t *src = srcp;
11067 	uint32_t *dest = destp;
11068 	uint32_t ldata;
11069 	int i;
11070 
11071 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
11072 		ldata = *src;
11073 		ldata = le32_to_cpu(ldata);
11074 		*dest = ldata;
11075 		src++;
11076 		dest++;
11077 	}
11078 }
11079 
11080 
11081 /**
11082  * lpfc_sli_bemem_bcopy - SLI memory copy function
11083  * @srcp: Source memory pointer.
11084  * @destp: Destination memory pointer.
11085  * @cnt: Number of words required to be copied.
11086  *
11087  * This function is used for copying data between a data structure
11088  * with big endian representation to local endianness.
11089  * This function can be called with or without lock.
11090  **/
11091 void
11092 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
11093 {
11094 	uint32_t *src = srcp;
11095 	uint32_t *dest = destp;
11096 	uint32_t ldata;
11097 	int i;
11098 
11099 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
11100 		ldata = *src;
11101 		ldata = be32_to_cpu(ldata);
11102 		*dest = ldata;
11103 		src++;
11104 		dest++;
11105 	}
11106 }
11107 
11108 /**
11109  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
11110  * @phba: Pointer to HBA context object.
11111  * @pring: Pointer to driver SLI ring object.
11112  * @mp: Pointer to driver buffer object.
11113  *
11114  * This function is called with no lock held.
11115  * It always return zero after adding the buffer to the postbufq
11116  * buffer list.
11117  **/
11118 int
11119 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11120 			 struct lpfc_dmabuf *mp)
11121 {
11122 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
11123 	   later */
11124 	spin_lock_irq(&phba->hbalock);
11125 	list_add_tail(&mp->list, &pring->postbufq);
11126 	pring->postbufq_cnt++;
11127 	spin_unlock_irq(&phba->hbalock);
11128 	return 0;
11129 }
11130 
11131 /**
11132  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
11133  * @phba: Pointer to HBA context object.
11134  *
11135  * When HBQ is enabled, buffers are searched based on tags. This function
11136  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
11137  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
11138  * does not conflict with tags of buffer posted for unsolicited events.
11139  * The function returns the allocated tag. The function is called with
11140  * no locks held.
11141  **/
11142 uint32_t
11143 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
11144 {
11145 	spin_lock_irq(&phba->hbalock);
11146 	phba->buffer_tag_count++;
11147 	/*
11148 	 * Always set the QUE_BUFTAG_BIT to distiguish between
11149 	 * a tag assigned by HBQ.
11150 	 */
11151 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
11152 	spin_unlock_irq(&phba->hbalock);
11153 	return phba->buffer_tag_count;
11154 }
11155 
11156 /**
11157  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
11158  * @phba: Pointer to HBA context object.
11159  * @pring: Pointer to driver SLI ring object.
11160  * @tag: Buffer tag.
11161  *
11162  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
11163  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
11164  * iocb is posted to the response ring with the tag of the buffer.
11165  * This function searches the pring->postbufq list using the tag
11166  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
11167  * iocb. If the buffer is found then lpfc_dmabuf object of the
11168  * buffer is returned to the caller else NULL is returned.
11169  * This function is called with no lock held.
11170  **/
11171 struct lpfc_dmabuf *
11172 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11173 			uint32_t tag)
11174 {
11175 	struct lpfc_dmabuf *mp, *next_mp;
11176 	struct list_head *slp = &pring->postbufq;
11177 
11178 	/* Search postbufq, from the beginning, looking for a match on tag */
11179 	spin_lock_irq(&phba->hbalock);
11180 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11181 		if (mp->buffer_tag == tag) {
11182 			list_del_init(&mp->list);
11183 			pring->postbufq_cnt--;
11184 			spin_unlock_irq(&phba->hbalock);
11185 			return mp;
11186 		}
11187 	}
11188 
11189 	spin_unlock_irq(&phba->hbalock);
11190 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11191 			"0402 Cannot find virtual addr for buffer tag on "
11192 			"ring %d Data x%lx x%px x%px x%x\n",
11193 			pring->ringno, (unsigned long) tag,
11194 			slp->next, slp->prev, pring->postbufq_cnt);
11195 
11196 	return NULL;
11197 }
11198 
11199 /**
11200  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
11201  * @phba: Pointer to HBA context object.
11202  * @pring: Pointer to driver SLI ring object.
11203  * @phys: DMA address of the buffer.
11204  *
11205  * This function searches the buffer list using the dma_address
11206  * of unsolicited event to find the driver's lpfc_dmabuf object
11207  * corresponding to the dma_address. The function returns the
11208  * lpfc_dmabuf object if a buffer is found else it returns NULL.
11209  * This function is called by the ct and els unsolicited event
11210  * handlers to get the buffer associated with the unsolicited
11211  * event.
11212  *
11213  * This function is called with no lock held.
11214  **/
11215 struct lpfc_dmabuf *
11216 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11217 			 dma_addr_t phys)
11218 {
11219 	struct lpfc_dmabuf *mp, *next_mp;
11220 	struct list_head *slp = &pring->postbufq;
11221 
11222 	/* Search postbufq, from the beginning, looking for a match on phys */
11223 	spin_lock_irq(&phba->hbalock);
11224 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11225 		if (mp->phys == phys) {
11226 			list_del_init(&mp->list);
11227 			pring->postbufq_cnt--;
11228 			spin_unlock_irq(&phba->hbalock);
11229 			return mp;
11230 		}
11231 	}
11232 
11233 	spin_unlock_irq(&phba->hbalock);
11234 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11235 			"0410 Cannot find virtual addr for mapped buf on "
11236 			"ring %d Data x%llx x%px x%px x%x\n",
11237 			pring->ringno, (unsigned long long)phys,
11238 			slp->next, slp->prev, pring->postbufq_cnt);
11239 	return NULL;
11240 }
11241 
11242 /**
11243  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
11244  * @phba: Pointer to HBA context object.
11245  * @cmdiocb: Pointer to driver command iocb object.
11246  * @rspiocb: Pointer to driver response iocb object.
11247  *
11248  * This function is the completion handler for the abort iocbs for
11249  * ELS commands. This function is called from the ELS ring event
11250  * handler with no lock held. This function frees memory resources
11251  * associated with the abort iocb.
11252  **/
11253 static void
11254 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11255 			struct lpfc_iocbq *rspiocb)
11256 {
11257 	IOCB_t *irsp = &rspiocb->iocb;
11258 	uint16_t abort_iotag, abort_context;
11259 	struct lpfc_iocbq *abort_iocb = NULL;
11260 
11261 	if (irsp->ulpStatus) {
11262 
11263 		/*
11264 		 * Assume that the port already completed and returned, or
11265 		 * will return the iocb. Just Log the message.
11266 		 */
11267 		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
11268 		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
11269 
11270 		spin_lock_irq(&phba->hbalock);
11271 		if (phba->sli_rev < LPFC_SLI_REV4) {
11272 			if (irsp->ulpCommand == CMD_ABORT_XRI_CX &&
11273 			    irsp->ulpStatus == IOSTAT_LOCAL_REJECT &&
11274 			    irsp->un.ulpWord[4] == IOERR_ABORT_REQUESTED) {
11275 				spin_unlock_irq(&phba->hbalock);
11276 				goto release_iocb;
11277 			}
11278 			if (abort_iotag != 0 &&
11279 				abort_iotag <= phba->sli.last_iotag)
11280 				abort_iocb =
11281 					phba->sli.iocbq_lookup[abort_iotag];
11282 		} else
11283 			/* For sli4 the abort_tag is the XRI,
11284 			 * so the abort routine puts the iotag  of the iocb
11285 			 * being aborted in the context field of the abort
11286 			 * IOCB.
11287 			 */
11288 			abort_iocb = phba->sli.iocbq_lookup[abort_context];
11289 
11290 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
11291 				"0327 Cannot abort els iocb x%px "
11292 				"with tag %x context %x, abort status %x, "
11293 				"abort code %x\n",
11294 				abort_iocb, abort_iotag, abort_context,
11295 				irsp->ulpStatus, irsp->un.ulpWord[4]);
11296 
11297 		spin_unlock_irq(&phba->hbalock);
11298 	}
11299 release_iocb:
11300 	lpfc_sli_release_iocbq(phba, cmdiocb);
11301 	return;
11302 }
11303 
11304 /**
11305  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
11306  * @phba: Pointer to HBA context object.
11307  * @cmdiocb: Pointer to driver command iocb object.
11308  * @rspiocb: Pointer to driver response iocb object.
11309  *
11310  * The function is called from SLI ring event handler with no
11311  * lock held. This function is the completion handler for ELS commands
11312  * which are aborted. The function frees memory resources used for
11313  * the aborted ELS commands.
11314  **/
11315 static void
11316 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11317 		     struct lpfc_iocbq *rspiocb)
11318 {
11319 	IOCB_t *irsp = &rspiocb->iocb;
11320 
11321 	/* ELS cmd tag <ulpIoTag> completes */
11322 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
11323 			"0139 Ignoring ELS cmd tag x%x completion Data: "
11324 			"x%x x%x x%x\n",
11325 			irsp->ulpIoTag, irsp->ulpStatus,
11326 			irsp->un.ulpWord[4], irsp->ulpTimeout);
11327 	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
11328 		lpfc_ct_free_iocb(phba, cmdiocb);
11329 	else
11330 		lpfc_els_free_iocb(phba, cmdiocb);
11331 	return;
11332 }
11333 
11334 /**
11335  * lpfc_sli_abort_iotag_issue - Issue abort for a command iocb
11336  * @phba: Pointer to HBA context object.
11337  * @pring: Pointer to driver SLI ring object.
11338  * @cmdiocb: Pointer to driver command iocb object.
11339  *
11340  * This function issues an abort iocb for the provided command iocb down to
11341  * the port. Other than the case the outstanding command iocb is an abort
11342  * request, this function issues abort out unconditionally. This function is
11343  * called with hbalock held. The function returns 0 when it fails due to
11344  * memory allocation failure or when the command iocb is an abort request.
11345  * The hbalock is asserted held in the code path calling this routine.
11346  **/
11347 static int
11348 lpfc_sli_abort_iotag_issue(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11349 			   struct lpfc_iocbq *cmdiocb)
11350 {
11351 	struct lpfc_vport *vport = cmdiocb->vport;
11352 	struct lpfc_iocbq *abtsiocbp;
11353 	IOCB_t *icmd = NULL;
11354 	IOCB_t *iabt = NULL;
11355 	int retval;
11356 	unsigned long iflags;
11357 	struct lpfc_nodelist *ndlp;
11358 
11359 	/*
11360 	 * There are certain command types we don't want to abort.  And we
11361 	 * don't want to abort commands that are already in the process of
11362 	 * being aborted.
11363 	 */
11364 	icmd = &cmdiocb->iocb;
11365 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11366 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
11367 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
11368 		return 0;
11369 
11370 	/* issue ABTS for this IOCB based on iotag */
11371 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
11372 	if (abtsiocbp == NULL)
11373 		return 0;
11374 
11375 	/* This signals the response to set the correct status
11376 	 * before calling the completion handler
11377 	 */
11378 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
11379 
11380 	iabt = &abtsiocbp->iocb;
11381 	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
11382 	iabt->un.acxri.abortContextTag = icmd->ulpContext;
11383 	if (phba->sli_rev == LPFC_SLI_REV4) {
11384 		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
11385 		iabt->un.acxri.abortContextTag = cmdiocb->iotag;
11386 	} else {
11387 		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
11388 		if (pring->ringno == LPFC_ELS_RING) {
11389 			ndlp = (struct lpfc_nodelist *)(cmdiocb->context1);
11390 			iabt->un.acxri.abortContextTag = ndlp->nlp_rpi;
11391 		}
11392 	}
11393 	iabt->ulpLe = 1;
11394 	iabt->ulpClass = icmd->ulpClass;
11395 
11396 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11397 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
11398 	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
11399 		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
11400 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
11401 		abtsiocbp->iocb_flag |= LPFC_IO_FOF;
11402 
11403 	if (phba->link_state >= LPFC_LINK_UP)
11404 		iabt->ulpCommand = CMD_ABORT_XRI_CN;
11405 	else
11406 		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
11407 
11408 	abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
11409 	abtsiocbp->vport = vport;
11410 
11411 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
11412 			 "0339 Abort xri x%x, original iotag x%x, "
11413 			 "abort cmd iotag x%x\n",
11414 			 iabt->un.acxri.abortIoTag,
11415 			 iabt->un.acxri.abortContextTag,
11416 			 abtsiocbp->iotag);
11417 
11418 	if (phba->sli_rev == LPFC_SLI_REV4) {
11419 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
11420 		if (unlikely(pring == NULL))
11421 			return 0;
11422 		/* Note: both hbalock and ring_lock need to be set here */
11423 		spin_lock_irqsave(&pring->ring_lock, iflags);
11424 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11425 			abtsiocbp, 0);
11426 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11427 	} else {
11428 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11429 			abtsiocbp, 0);
11430 	}
11431 
11432 	if (retval)
11433 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
11434 
11435 	/*
11436 	 * Caller to this routine should check for IOCB_ERROR
11437 	 * and handle it properly.  This routine no longer removes
11438 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
11439 	 */
11440 	return retval;
11441 }
11442 
11443 /**
11444  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
11445  * @phba: Pointer to HBA context object.
11446  * @pring: Pointer to driver SLI ring object.
11447  * @cmdiocb: Pointer to driver command iocb object.
11448  *
11449  * This function issues an abort iocb for the provided command iocb. In case
11450  * of unloading, the abort iocb will not be issued to commands on the ELS
11451  * ring. Instead, the callback function shall be changed to those commands
11452  * so that nothing happens when them finishes. This function is called with
11453  * hbalock held. The function returns 0 when the command iocb is an abort
11454  * request.
11455  **/
11456 int
11457 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11458 			   struct lpfc_iocbq *cmdiocb)
11459 {
11460 	struct lpfc_vport *vport = cmdiocb->vport;
11461 	int retval = IOCB_ERROR;
11462 	IOCB_t *icmd = NULL;
11463 
11464 	lockdep_assert_held(&phba->hbalock);
11465 
11466 	/*
11467 	 * There are certain command types we don't want to abort.  And we
11468 	 * don't want to abort commands that are already in the process of
11469 	 * being aborted.
11470 	 */
11471 	icmd = &cmdiocb->iocb;
11472 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11473 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
11474 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
11475 		return 0;
11476 
11477 	if (!pring) {
11478 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11479 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11480 		else
11481 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11482 		goto abort_iotag_exit;
11483 	}
11484 
11485 	/*
11486 	 * If we're unloading, don't abort iocb on the ELS ring, but change
11487 	 * the callback so that nothing happens when it finishes.
11488 	 */
11489 	if ((vport->load_flag & FC_UNLOADING) &&
11490 	    (pring->ringno == LPFC_ELS_RING)) {
11491 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11492 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11493 		else
11494 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11495 		goto abort_iotag_exit;
11496 	}
11497 
11498 	/* Now, we try to issue the abort to the cmdiocb out */
11499 	retval = lpfc_sli_abort_iotag_issue(phba, pring, cmdiocb);
11500 
11501 abort_iotag_exit:
11502 	/*
11503 	 * Caller to this routine should check for IOCB_ERROR
11504 	 * and handle it properly.  This routine no longer removes
11505 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
11506 	 */
11507 	return retval;
11508 }
11509 
11510 /**
11511  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
11512  * @phba: pointer to lpfc HBA data structure.
11513  *
11514  * This routine will abort all pending and outstanding iocbs to an HBA.
11515  **/
11516 void
11517 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
11518 {
11519 	struct lpfc_sli *psli = &phba->sli;
11520 	struct lpfc_sli_ring *pring;
11521 	struct lpfc_queue *qp = NULL;
11522 	int i;
11523 
11524 	if (phba->sli_rev != LPFC_SLI_REV4) {
11525 		for (i = 0; i < psli->num_rings; i++) {
11526 			pring = &psli->sli3_ring[i];
11527 			lpfc_sli_abort_iocb_ring(phba, pring);
11528 		}
11529 		return;
11530 	}
11531 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11532 		pring = qp->pring;
11533 		if (!pring)
11534 			continue;
11535 		lpfc_sli_abort_iocb_ring(phba, pring);
11536 	}
11537 }
11538 
11539 /**
11540  * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
11541  * @iocbq: Pointer to driver iocb object.
11542  * @vport: Pointer to driver virtual port object.
11543  * @tgt_id: SCSI ID of the target.
11544  * @lun_id: LUN ID of the scsi device.
11545  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
11546  *
11547  * This function acts as an iocb filter for functions which abort or count
11548  * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
11549  * 0 if the filtering criteria is met for the given iocb and will return
11550  * 1 if the filtering criteria is not met.
11551  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
11552  * given iocb is for the SCSI device specified by vport, tgt_id and
11553  * lun_id parameter.
11554  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
11555  * given iocb is for the SCSI target specified by vport and tgt_id
11556  * parameters.
11557  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
11558  * given iocb is for the SCSI host associated with the given vport.
11559  * This function is called with no locks held.
11560  **/
11561 static int
11562 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
11563 			   uint16_t tgt_id, uint64_t lun_id,
11564 			   lpfc_ctx_cmd ctx_cmd)
11565 {
11566 	struct lpfc_io_buf *lpfc_cmd;
11567 	int rc = 1;
11568 
11569 	if (iocbq->vport != vport)
11570 		return rc;
11571 
11572 	if (!(iocbq->iocb_flag &  LPFC_IO_FCP) ||
11573 	    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ))
11574 		return rc;
11575 
11576 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
11577 
11578 	if (lpfc_cmd->pCmd == NULL)
11579 		return rc;
11580 
11581 	switch (ctx_cmd) {
11582 	case LPFC_CTX_LUN:
11583 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11584 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
11585 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
11586 			rc = 0;
11587 		break;
11588 	case LPFC_CTX_TGT:
11589 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11590 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
11591 			rc = 0;
11592 		break;
11593 	case LPFC_CTX_HOST:
11594 		rc = 0;
11595 		break;
11596 	default:
11597 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
11598 			__func__, ctx_cmd);
11599 		break;
11600 	}
11601 
11602 	return rc;
11603 }
11604 
11605 /**
11606  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
11607  * @vport: Pointer to virtual port.
11608  * @tgt_id: SCSI ID of the target.
11609  * @lun_id: LUN ID of the scsi device.
11610  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11611  *
11612  * This function returns number of FCP commands pending for the vport.
11613  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
11614  * commands pending on the vport associated with SCSI device specified
11615  * by tgt_id and lun_id parameters.
11616  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
11617  * commands pending on the vport associated with SCSI target specified
11618  * by tgt_id parameter.
11619  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
11620  * commands pending on the vport.
11621  * This function returns the number of iocbs which satisfy the filter.
11622  * This function is called without any lock held.
11623  **/
11624 int
11625 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
11626 		  lpfc_ctx_cmd ctx_cmd)
11627 {
11628 	struct lpfc_hba *phba = vport->phba;
11629 	struct lpfc_iocbq *iocbq;
11630 	int sum, i;
11631 
11632 	spin_lock_irq(&phba->hbalock);
11633 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
11634 		iocbq = phba->sli.iocbq_lookup[i];
11635 
11636 		if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
11637 						ctx_cmd) == 0)
11638 			sum++;
11639 	}
11640 	spin_unlock_irq(&phba->hbalock);
11641 
11642 	return sum;
11643 }
11644 
11645 /**
11646  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
11647  * @phba: Pointer to HBA context object
11648  * @cmdiocb: Pointer to command iocb object.
11649  * @rspiocb: Pointer to response iocb object.
11650  *
11651  * This function is called when an aborted FCP iocb completes. This
11652  * function is called by the ring event handler with no lock held.
11653  * This function frees the iocb.
11654  **/
11655 void
11656 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11657 			struct lpfc_iocbq *rspiocb)
11658 {
11659 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11660 			"3096 ABORT_XRI_CN completing on rpi x%x "
11661 			"original iotag x%x, abort cmd iotag x%x "
11662 			"status 0x%x, reason 0x%x\n",
11663 			cmdiocb->iocb.un.acxri.abortContextTag,
11664 			cmdiocb->iocb.un.acxri.abortIoTag,
11665 			cmdiocb->iotag, rspiocb->iocb.ulpStatus,
11666 			rspiocb->iocb.un.ulpWord[4]);
11667 	lpfc_sli_release_iocbq(phba, cmdiocb);
11668 	return;
11669 }
11670 
11671 /**
11672  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
11673  * @vport: Pointer to virtual port.
11674  * @pring: Pointer to driver SLI ring object.
11675  * @tgt_id: SCSI ID of the target.
11676  * @lun_id: LUN ID of the scsi device.
11677  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11678  *
11679  * This function sends an abort command for every SCSI command
11680  * associated with the given virtual port pending on the ring
11681  * filtered by lpfc_sli_validate_fcp_iocb function.
11682  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
11683  * FCP iocbs associated with lun specified by tgt_id and lun_id
11684  * parameters
11685  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
11686  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
11687  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
11688  * FCP iocbs associated with virtual port.
11689  * This function returns number of iocbs it failed to abort.
11690  * This function is called with no locks held.
11691  **/
11692 int
11693 lpfc_sli_abort_iocb(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
11694 		    uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd abort_cmd)
11695 {
11696 	struct lpfc_hba *phba = vport->phba;
11697 	struct lpfc_iocbq *iocbq;
11698 	struct lpfc_iocbq *abtsiocb;
11699 	struct lpfc_sli_ring *pring_s4;
11700 	IOCB_t *cmd = NULL;
11701 	int errcnt = 0, ret_val = 0;
11702 	int i;
11703 
11704 	/* all I/Os are in process of being flushed */
11705 	if (phba->hba_flag & HBA_IOQ_FLUSH)
11706 		return errcnt;
11707 
11708 	for (i = 1; i <= phba->sli.last_iotag; i++) {
11709 		iocbq = phba->sli.iocbq_lookup[i];
11710 
11711 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
11712 					       abort_cmd) != 0)
11713 			continue;
11714 
11715 		/*
11716 		 * If the iocbq is already being aborted, don't take a second
11717 		 * action, but do count it.
11718 		 */
11719 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
11720 			continue;
11721 
11722 		/* issue ABTS for this IOCB based on iotag */
11723 		abtsiocb = lpfc_sli_get_iocbq(phba);
11724 		if (abtsiocb == NULL) {
11725 			errcnt++;
11726 			continue;
11727 		}
11728 
11729 		/* indicate the IO is being aborted by the driver. */
11730 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
11731 
11732 		cmd = &iocbq->iocb;
11733 		abtsiocb->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
11734 		abtsiocb->iocb.un.acxri.abortContextTag = cmd->ulpContext;
11735 		if (phba->sli_rev == LPFC_SLI_REV4)
11736 			abtsiocb->iocb.un.acxri.abortIoTag = iocbq->sli4_xritag;
11737 		else
11738 			abtsiocb->iocb.un.acxri.abortIoTag = cmd->ulpIoTag;
11739 		abtsiocb->iocb.ulpLe = 1;
11740 		abtsiocb->iocb.ulpClass = cmd->ulpClass;
11741 		abtsiocb->vport = vport;
11742 
11743 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11744 		abtsiocb->hba_wqidx = iocbq->hba_wqidx;
11745 		if (iocbq->iocb_flag & LPFC_IO_FCP)
11746 			abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
11747 		if (iocbq->iocb_flag & LPFC_IO_FOF)
11748 			abtsiocb->iocb_flag |= LPFC_IO_FOF;
11749 
11750 		if (lpfc_is_link_up(phba))
11751 			abtsiocb->iocb.ulpCommand = CMD_ABORT_XRI_CN;
11752 		else
11753 			abtsiocb->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
11754 
11755 		/* Setup callback routine and issue the command. */
11756 		abtsiocb->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
11757 		if (phba->sli_rev == LPFC_SLI_REV4) {
11758 			pring_s4 = lpfc_sli4_calc_ring(phba, iocbq);
11759 			if (!pring_s4)
11760 				continue;
11761 			ret_val = lpfc_sli_issue_iocb(phba, pring_s4->ringno,
11762 						      abtsiocb, 0);
11763 		} else
11764 			ret_val = lpfc_sli_issue_iocb(phba, pring->ringno,
11765 						      abtsiocb, 0);
11766 		if (ret_val == IOCB_ERROR) {
11767 			lpfc_sli_release_iocbq(phba, abtsiocb);
11768 			errcnt++;
11769 			continue;
11770 		}
11771 	}
11772 
11773 	return errcnt;
11774 }
11775 
11776 /**
11777  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
11778  * @vport: Pointer to virtual port.
11779  * @pring: Pointer to driver SLI ring object.
11780  * @tgt_id: SCSI ID of the target.
11781  * @lun_id: LUN ID of the scsi device.
11782  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11783  *
11784  * This function sends an abort command for every SCSI command
11785  * associated with the given virtual port pending on the ring
11786  * filtered by lpfc_sli_validate_fcp_iocb function.
11787  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
11788  * FCP iocbs associated with lun specified by tgt_id and lun_id
11789  * parameters
11790  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
11791  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
11792  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
11793  * FCP iocbs associated with virtual port.
11794  * This function returns number of iocbs it aborted .
11795  * This function is called with no locks held right after a taskmgmt
11796  * command is sent.
11797  **/
11798 int
11799 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
11800 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
11801 {
11802 	struct lpfc_hba *phba = vport->phba;
11803 	struct lpfc_io_buf *lpfc_cmd;
11804 	struct lpfc_iocbq *abtsiocbq;
11805 	struct lpfc_nodelist *ndlp;
11806 	struct lpfc_iocbq *iocbq;
11807 	IOCB_t *icmd;
11808 	int sum, i, ret_val;
11809 	unsigned long iflags;
11810 	struct lpfc_sli_ring *pring_s4 = NULL;
11811 
11812 	spin_lock_irqsave(&phba->hbalock, iflags);
11813 
11814 	/* all I/Os are in process of being flushed */
11815 	if (phba->hba_flag & HBA_IOQ_FLUSH) {
11816 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11817 		return 0;
11818 	}
11819 	sum = 0;
11820 
11821 	for (i = 1; i <= phba->sli.last_iotag; i++) {
11822 		iocbq = phba->sli.iocbq_lookup[i];
11823 
11824 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
11825 					       cmd) != 0)
11826 			continue;
11827 
11828 		/* Guard against IO completion being called at same time */
11829 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
11830 		spin_lock(&lpfc_cmd->buf_lock);
11831 
11832 		if (!lpfc_cmd->pCmd) {
11833 			spin_unlock(&lpfc_cmd->buf_lock);
11834 			continue;
11835 		}
11836 
11837 		if (phba->sli_rev == LPFC_SLI_REV4) {
11838 			pring_s4 =
11839 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
11840 			if (!pring_s4) {
11841 				spin_unlock(&lpfc_cmd->buf_lock);
11842 				continue;
11843 			}
11844 			/* Note: both hbalock and ring_lock must be set here */
11845 			spin_lock(&pring_s4->ring_lock);
11846 		}
11847 
11848 		/*
11849 		 * If the iocbq is already being aborted, don't take a second
11850 		 * action, but do count it.
11851 		 */
11852 		if ((iocbq->iocb_flag & LPFC_DRIVER_ABORTED) ||
11853 		    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ)) {
11854 			if (phba->sli_rev == LPFC_SLI_REV4)
11855 				spin_unlock(&pring_s4->ring_lock);
11856 			spin_unlock(&lpfc_cmd->buf_lock);
11857 			continue;
11858 		}
11859 
11860 		/* issue ABTS for this IOCB based on iotag */
11861 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
11862 		if (!abtsiocbq) {
11863 			if (phba->sli_rev == LPFC_SLI_REV4)
11864 				spin_unlock(&pring_s4->ring_lock);
11865 			spin_unlock(&lpfc_cmd->buf_lock);
11866 			continue;
11867 		}
11868 
11869 		icmd = &iocbq->iocb;
11870 		abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
11871 		abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
11872 		if (phba->sli_rev == LPFC_SLI_REV4)
11873 			abtsiocbq->iocb.un.acxri.abortIoTag =
11874 							 iocbq->sli4_xritag;
11875 		else
11876 			abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
11877 		abtsiocbq->iocb.ulpLe = 1;
11878 		abtsiocbq->iocb.ulpClass = icmd->ulpClass;
11879 		abtsiocbq->vport = vport;
11880 
11881 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11882 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
11883 		if (iocbq->iocb_flag & LPFC_IO_FCP)
11884 			abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
11885 		if (iocbq->iocb_flag & LPFC_IO_FOF)
11886 			abtsiocbq->iocb_flag |= LPFC_IO_FOF;
11887 
11888 		ndlp = lpfc_cmd->rdata->pnode;
11889 
11890 		if (lpfc_is_link_up(phba) &&
11891 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
11892 			abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
11893 		else
11894 			abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
11895 
11896 		/* Setup callback routine and issue the command. */
11897 		abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
11898 
11899 		/*
11900 		 * Indicate the IO is being aborted by the driver and set
11901 		 * the caller's flag into the aborted IO.
11902 		 */
11903 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
11904 
11905 		if (phba->sli_rev == LPFC_SLI_REV4) {
11906 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
11907 							abtsiocbq, 0);
11908 			spin_unlock(&pring_s4->ring_lock);
11909 		} else {
11910 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
11911 							abtsiocbq, 0);
11912 		}
11913 
11914 		spin_unlock(&lpfc_cmd->buf_lock);
11915 
11916 		if (ret_val == IOCB_ERROR)
11917 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
11918 		else
11919 			sum++;
11920 	}
11921 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11922 	return sum;
11923 }
11924 
11925 /**
11926  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
11927  * @phba: Pointer to HBA context object.
11928  * @cmdiocbq: Pointer to command iocb.
11929  * @rspiocbq: Pointer to response iocb.
11930  *
11931  * This function is the completion handler for iocbs issued using
11932  * lpfc_sli_issue_iocb_wait function. This function is called by the
11933  * ring event handler function without any lock held. This function
11934  * can be called from both worker thread context and interrupt
11935  * context. This function also can be called from other thread which
11936  * cleans up the SLI layer objects.
11937  * This function copy the contents of the response iocb to the
11938  * response iocb memory object provided by the caller of
11939  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
11940  * sleeps for the iocb completion.
11941  **/
11942 static void
11943 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
11944 			struct lpfc_iocbq *cmdiocbq,
11945 			struct lpfc_iocbq *rspiocbq)
11946 {
11947 	wait_queue_head_t *pdone_q;
11948 	unsigned long iflags;
11949 	struct lpfc_io_buf *lpfc_cmd;
11950 
11951 	spin_lock_irqsave(&phba->hbalock, iflags);
11952 	if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
11953 
11954 		/*
11955 		 * A time out has occurred for the iocb.  If a time out
11956 		 * completion handler has been supplied, call it.  Otherwise,
11957 		 * just free the iocbq.
11958 		 */
11959 
11960 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11961 		cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
11962 		cmdiocbq->wait_iocb_cmpl = NULL;
11963 		if (cmdiocbq->iocb_cmpl)
11964 			(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
11965 		else
11966 			lpfc_sli_release_iocbq(phba, cmdiocbq);
11967 		return;
11968 	}
11969 
11970 	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
11971 	if (cmdiocbq->context2 && rspiocbq)
11972 		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
11973 		       &rspiocbq->iocb, sizeof(IOCB_t));
11974 
11975 	/* Set the exchange busy flag for task management commands */
11976 	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
11977 		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
11978 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
11979 			cur_iocbq);
11980 		if (rspiocbq && (rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY))
11981 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
11982 		else
11983 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
11984 	}
11985 
11986 	pdone_q = cmdiocbq->context_un.wait_queue;
11987 	if (pdone_q)
11988 		wake_up(pdone_q);
11989 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11990 	return;
11991 }
11992 
11993 /**
11994  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
11995  * @phba: Pointer to HBA context object..
11996  * @piocbq: Pointer to command iocb.
11997  * @flag: Flag to test.
11998  *
11999  * This routine grabs the hbalock and then test the iocb_flag to
12000  * see if the passed in flag is set.
12001  * Returns:
12002  * 1 if flag is set.
12003  * 0 if flag is not set.
12004  **/
12005 static int
12006 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
12007 		 struct lpfc_iocbq *piocbq, uint32_t flag)
12008 {
12009 	unsigned long iflags;
12010 	int ret;
12011 
12012 	spin_lock_irqsave(&phba->hbalock, iflags);
12013 	ret = piocbq->iocb_flag & flag;
12014 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12015 	return ret;
12016 
12017 }
12018 
12019 /**
12020  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
12021  * @phba: Pointer to HBA context object..
12022  * @ring_number: Ring number
12023  * @piocb: Pointer to command iocb.
12024  * @prspiocbq: Pointer to response iocb.
12025  * @timeout: Timeout in number of seconds.
12026  *
12027  * This function issues the iocb to firmware and waits for the
12028  * iocb to complete. The iocb_cmpl field of the shall be used
12029  * to handle iocbs which time out. If the field is NULL, the
12030  * function shall free the iocbq structure.  If more clean up is
12031  * needed, the caller is expected to provide a completion function
12032  * that will provide the needed clean up.  If the iocb command is
12033  * not completed within timeout seconds, the function will either
12034  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
12035  * completion function set in the iocb_cmpl field and then return
12036  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
12037  * resources if this function returns IOCB_TIMEDOUT.
12038  * The function waits for the iocb completion using an
12039  * non-interruptible wait.
12040  * This function will sleep while waiting for iocb completion.
12041  * So, this function should not be called from any context which
12042  * does not allow sleeping. Due to the same reason, this function
12043  * cannot be called with interrupt disabled.
12044  * This function assumes that the iocb completions occur while
12045  * this function sleep. So, this function cannot be called from
12046  * the thread which process iocb completion for this ring.
12047  * This function clears the iocb_flag of the iocb object before
12048  * issuing the iocb and the iocb completion handler sets this
12049  * flag and wakes this thread when the iocb completes.
12050  * The contents of the response iocb will be copied to prspiocbq
12051  * by the completion handler when the command completes.
12052  * This function returns IOCB_SUCCESS when success.
12053  * This function is called with no lock held.
12054  **/
12055 int
12056 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
12057 			 uint32_t ring_number,
12058 			 struct lpfc_iocbq *piocb,
12059 			 struct lpfc_iocbq *prspiocbq,
12060 			 uint32_t timeout)
12061 {
12062 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
12063 	long timeleft, timeout_req = 0;
12064 	int retval = IOCB_SUCCESS;
12065 	uint32_t creg_val;
12066 	struct lpfc_iocbq *iocb;
12067 	int txq_cnt = 0;
12068 	int txcmplq_cnt = 0;
12069 	struct lpfc_sli_ring *pring;
12070 	unsigned long iflags;
12071 	bool iocb_completed = true;
12072 
12073 	if (phba->sli_rev >= LPFC_SLI_REV4)
12074 		pring = lpfc_sli4_calc_ring(phba, piocb);
12075 	else
12076 		pring = &phba->sli.sli3_ring[ring_number];
12077 	/*
12078 	 * If the caller has provided a response iocbq buffer, then context2
12079 	 * is NULL or its an error.
12080 	 */
12081 	if (prspiocbq) {
12082 		if (piocb->context2)
12083 			return IOCB_ERROR;
12084 		piocb->context2 = prspiocbq;
12085 	}
12086 
12087 	piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
12088 	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
12089 	piocb->context_un.wait_queue = &done_q;
12090 	piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
12091 
12092 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12093 		if (lpfc_readl(phba->HCregaddr, &creg_val))
12094 			return IOCB_ERROR;
12095 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
12096 		writel(creg_val, phba->HCregaddr);
12097 		readl(phba->HCregaddr); /* flush */
12098 	}
12099 
12100 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
12101 				     SLI_IOCB_RET_IOCB);
12102 	if (retval == IOCB_SUCCESS) {
12103 		timeout_req = msecs_to_jiffies(timeout * 1000);
12104 		timeleft = wait_event_timeout(done_q,
12105 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
12106 				timeout_req);
12107 		spin_lock_irqsave(&phba->hbalock, iflags);
12108 		if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
12109 
12110 			/*
12111 			 * IOCB timed out.  Inform the wake iocb wait
12112 			 * completion function and set local status
12113 			 */
12114 
12115 			iocb_completed = false;
12116 			piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
12117 		}
12118 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12119 		if (iocb_completed) {
12120 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12121 					"0331 IOCB wake signaled\n");
12122 			/* Note: we are not indicating if the IOCB has a success
12123 			 * status or not - that's for the caller to check.
12124 			 * IOCB_SUCCESS means just that the command was sent and
12125 			 * completed. Not that it completed successfully.
12126 			 * */
12127 		} else if (timeleft == 0) {
12128 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12129 					"0338 IOCB wait timeout error - no "
12130 					"wake response Data x%x\n", timeout);
12131 			retval = IOCB_TIMEDOUT;
12132 		} else {
12133 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12134 					"0330 IOCB wake NOT set, "
12135 					"Data x%x x%lx\n",
12136 					timeout, (timeleft / jiffies));
12137 			retval = IOCB_TIMEDOUT;
12138 		}
12139 	} else if (retval == IOCB_BUSY) {
12140 		if (phba->cfg_log_verbose & LOG_SLI) {
12141 			list_for_each_entry(iocb, &pring->txq, list) {
12142 				txq_cnt++;
12143 			}
12144 			list_for_each_entry(iocb, &pring->txcmplq, list) {
12145 				txcmplq_cnt++;
12146 			}
12147 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12148 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
12149 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
12150 		}
12151 		return retval;
12152 	} else {
12153 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12154 				"0332 IOCB wait issue failed, Data x%x\n",
12155 				retval);
12156 		retval = IOCB_ERROR;
12157 	}
12158 
12159 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12160 		if (lpfc_readl(phba->HCregaddr, &creg_val))
12161 			return IOCB_ERROR;
12162 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
12163 		writel(creg_val, phba->HCregaddr);
12164 		readl(phba->HCregaddr); /* flush */
12165 	}
12166 
12167 	if (prspiocbq)
12168 		piocb->context2 = NULL;
12169 
12170 	piocb->context_un.wait_queue = NULL;
12171 	piocb->iocb_cmpl = NULL;
12172 	return retval;
12173 }
12174 
12175 /**
12176  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
12177  * @phba: Pointer to HBA context object.
12178  * @pmboxq: Pointer to driver mailbox object.
12179  * @timeout: Timeout in number of seconds.
12180  *
12181  * This function issues the mailbox to firmware and waits for the
12182  * mailbox command to complete. If the mailbox command is not
12183  * completed within timeout seconds, it returns MBX_TIMEOUT.
12184  * The function waits for the mailbox completion using an
12185  * interruptible wait. If the thread is woken up due to a
12186  * signal, MBX_TIMEOUT error is returned to the caller. Caller
12187  * should not free the mailbox resources, if this function returns
12188  * MBX_TIMEOUT.
12189  * This function will sleep while waiting for mailbox completion.
12190  * So, this function should not be called from any context which
12191  * does not allow sleeping. Due to the same reason, this function
12192  * cannot be called with interrupt disabled.
12193  * This function assumes that the mailbox completion occurs while
12194  * this function sleep. So, this function cannot be called from
12195  * the worker thread which processes mailbox completion.
12196  * This function is called in the context of HBA management
12197  * applications.
12198  * This function returns MBX_SUCCESS when successful.
12199  * This function is called with no lock held.
12200  **/
12201 int
12202 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
12203 			 uint32_t timeout)
12204 {
12205 	struct completion mbox_done;
12206 	int retval;
12207 	unsigned long flag;
12208 
12209 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
12210 	/* setup wake call as IOCB callback */
12211 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
12212 
12213 	/* setup context3 field to pass wait_queue pointer to wake function  */
12214 	init_completion(&mbox_done);
12215 	pmboxq->context3 = &mbox_done;
12216 	/* now issue the command */
12217 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
12218 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
12219 		wait_for_completion_timeout(&mbox_done,
12220 					    msecs_to_jiffies(timeout * 1000));
12221 
12222 		spin_lock_irqsave(&phba->hbalock, flag);
12223 		pmboxq->context3 = NULL;
12224 		/*
12225 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
12226 		 * else do not free the resources.
12227 		 */
12228 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
12229 			retval = MBX_SUCCESS;
12230 		} else {
12231 			retval = MBX_TIMEOUT;
12232 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
12233 		}
12234 		spin_unlock_irqrestore(&phba->hbalock, flag);
12235 	}
12236 	return retval;
12237 }
12238 
12239 /**
12240  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
12241  * @phba: Pointer to HBA context.
12242  * @mbx_action: Mailbox shutdown options.
12243  *
12244  * This function is called to shutdown the driver's mailbox sub-system.
12245  * It first marks the mailbox sub-system is in a block state to prevent
12246  * the asynchronous mailbox command from issued off the pending mailbox
12247  * command queue. If the mailbox command sub-system shutdown is due to
12248  * HBA error conditions such as EEH or ERATT, this routine shall invoke
12249  * the mailbox sub-system flush routine to forcefully bring down the
12250  * mailbox sub-system. Otherwise, if it is due to normal condition (such
12251  * as with offline or HBA function reset), this routine will wait for the
12252  * outstanding mailbox command to complete before invoking the mailbox
12253  * sub-system flush routine to gracefully bring down mailbox sub-system.
12254  **/
12255 void
12256 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
12257 {
12258 	struct lpfc_sli *psli = &phba->sli;
12259 	unsigned long timeout;
12260 
12261 	if (mbx_action == LPFC_MBX_NO_WAIT) {
12262 		/* delay 100ms for port state */
12263 		msleep(100);
12264 		lpfc_sli_mbox_sys_flush(phba);
12265 		return;
12266 	}
12267 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
12268 
12269 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12270 	local_bh_disable();
12271 
12272 	spin_lock_irq(&phba->hbalock);
12273 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
12274 
12275 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
12276 		/* Determine how long we might wait for the active mailbox
12277 		 * command to be gracefully completed by firmware.
12278 		 */
12279 		if (phba->sli.mbox_active)
12280 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
12281 						phba->sli.mbox_active) *
12282 						1000) + jiffies;
12283 		spin_unlock_irq(&phba->hbalock);
12284 
12285 		/* Enable softirqs again, done with phba->hbalock */
12286 		local_bh_enable();
12287 
12288 		while (phba->sli.mbox_active) {
12289 			/* Check active mailbox complete status every 2ms */
12290 			msleep(2);
12291 			if (time_after(jiffies, timeout))
12292 				/* Timeout, let the mailbox flush routine to
12293 				 * forcefully release active mailbox command
12294 				 */
12295 				break;
12296 		}
12297 	} else {
12298 		spin_unlock_irq(&phba->hbalock);
12299 
12300 		/* Enable softirqs again, done with phba->hbalock */
12301 		local_bh_enable();
12302 	}
12303 
12304 	lpfc_sli_mbox_sys_flush(phba);
12305 }
12306 
12307 /**
12308  * lpfc_sli_eratt_read - read sli-3 error attention events
12309  * @phba: Pointer to HBA context.
12310  *
12311  * This function is called to read the SLI3 device error attention registers
12312  * for possible error attention events. The caller must hold the hostlock
12313  * with spin_lock_irq().
12314  *
12315  * This function returns 1 when there is Error Attention in the Host Attention
12316  * Register and returns 0 otherwise.
12317  **/
12318 static int
12319 lpfc_sli_eratt_read(struct lpfc_hba *phba)
12320 {
12321 	uint32_t ha_copy;
12322 
12323 	/* Read chip Host Attention (HA) register */
12324 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
12325 		goto unplug_err;
12326 
12327 	if (ha_copy & HA_ERATT) {
12328 		/* Read host status register to retrieve error event */
12329 		if (lpfc_sli_read_hs(phba))
12330 			goto unplug_err;
12331 
12332 		/* Check if there is a deferred error condition is active */
12333 		if ((HS_FFER1 & phba->work_hs) &&
12334 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12335 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
12336 			phba->hba_flag |= DEFER_ERATT;
12337 			/* Clear all interrupt enable conditions */
12338 			writel(0, phba->HCregaddr);
12339 			readl(phba->HCregaddr);
12340 		}
12341 
12342 		/* Set the driver HA work bitmap */
12343 		phba->work_ha |= HA_ERATT;
12344 		/* Indicate polling handles this ERATT */
12345 		phba->hba_flag |= HBA_ERATT_HANDLED;
12346 		return 1;
12347 	}
12348 	return 0;
12349 
12350 unplug_err:
12351 	/* Set the driver HS work bitmap */
12352 	phba->work_hs |= UNPLUG_ERR;
12353 	/* Set the driver HA work bitmap */
12354 	phba->work_ha |= HA_ERATT;
12355 	/* Indicate polling handles this ERATT */
12356 	phba->hba_flag |= HBA_ERATT_HANDLED;
12357 	return 1;
12358 }
12359 
12360 /**
12361  * lpfc_sli4_eratt_read - read sli-4 error attention events
12362  * @phba: Pointer to HBA context.
12363  *
12364  * This function is called to read the SLI4 device error attention registers
12365  * for possible error attention events. The caller must hold the hostlock
12366  * with spin_lock_irq().
12367  *
12368  * This function returns 1 when there is Error Attention in the Host Attention
12369  * Register and returns 0 otherwise.
12370  **/
12371 static int
12372 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
12373 {
12374 	uint32_t uerr_sta_hi, uerr_sta_lo;
12375 	uint32_t if_type, portsmphr;
12376 	struct lpfc_register portstat_reg;
12377 
12378 	/*
12379 	 * For now, use the SLI4 device internal unrecoverable error
12380 	 * registers for error attention. This can be changed later.
12381 	 */
12382 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12383 	switch (if_type) {
12384 	case LPFC_SLI_INTF_IF_TYPE_0:
12385 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
12386 			&uerr_sta_lo) ||
12387 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
12388 			&uerr_sta_hi)) {
12389 			phba->work_hs |= UNPLUG_ERR;
12390 			phba->work_ha |= HA_ERATT;
12391 			phba->hba_flag |= HBA_ERATT_HANDLED;
12392 			return 1;
12393 		}
12394 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
12395 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
12396 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12397 					"1423 HBA Unrecoverable error: "
12398 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
12399 					"ue_mask_lo_reg=0x%x, "
12400 					"ue_mask_hi_reg=0x%x\n",
12401 					uerr_sta_lo, uerr_sta_hi,
12402 					phba->sli4_hba.ue_mask_lo,
12403 					phba->sli4_hba.ue_mask_hi);
12404 			phba->work_status[0] = uerr_sta_lo;
12405 			phba->work_status[1] = uerr_sta_hi;
12406 			phba->work_ha |= HA_ERATT;
12407 			phba->hba_flag |= HBA_ERATT_HANDLED;
12408 			return 1;
12409 		}
12410 		break;
12411 	case LPFC_SLI_INTF_IF_TYPE_2:
12412 	case LPFC_SLI_INTF_IF_TYPE_6:
12413 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
12414 			&portstat_reg.word0) ||
12415 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
12416 			&portsmphr)){
12417 			phba->work_hs |= UNPLUG_ERR;
12418 			phba->work_ha |= HA_ERATT;
12419 			phba->hba_flag |= HBA_ERATT_HANDLED;
12420 			return 1;
12421 		}
12422 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
12423 			phba->work_status[0] =
12424 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
12425 			phba->work_status[1] =
12426 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
12427 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12428 					"2885 Port Status Event: "
12429 					"port status reg 0x%x, "
12430 					"port smphr reg 0x%x, "
12431 					"error 1=0x%x, error 2=0x%x\n",
12432 					portstat_reg.word0,
12433 					portsmphr,
12434 					phba->work_status[0],
12435 					phba->work_status[1]);
12436 			phba->work_ha |= HA_ERATT;
12437 			phba->hba_flag |= HBA_ERATT_HANDLED;
12438 			return 1;
12439 		}
12440 		break;
12441 	case LPFC_SLI_INTF_IF_TYPE_1:
12442 	default:
12443 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12444 				"2886 HBA Error Attention on unsupported "
12445 				"if type %d.", if_type);
12446 		return 1;
12447 	}
12448 
12449 	return 0;
12450 }
12451 
12452 /**
12453  * lpfc_sli_check_eratt - check error attention events
12454  * @phba: Pointer to HBA context.
12455  *
12456  * This function is called from timer soft interrupt context to check HBA's
12457  * error attention register bit for error attention events.
12458  *
12459  * This function returns 1 when there is Error Attention in the Host Attention
12460  * Register and returns 0 otherwise.
12461  **/
12462 int
12463 lpfc_sli_check_eratt(struct lpfc_hba *phba)
12464 {
12465 	uint32_t ha_copy;
12466 
12467 	/* If somebody is waiting to handle an eratt, don't process it
12468 	 * here. The brdkill function will do this.
12469 	 */
12470 	if (phba->link_flag & LS_IGNORE_ERATT)
12471 		return 0;
12472 
12473 	/* Check if interrupt handler handles this ERATT */
12474 	spin_lock_irq(&phba->hbalock);
12475 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
12476 		/* Interrupt handler has handled ERATT */
12477 		spin_unlock_irq(&phba->hbalock);
12478 		return 0;
12479 	}
12480 
12481 	/*
12482 	 * If there is deferred error attention, do not check for error
12483 	 * attention
12484 	 */
12485 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12486 		spin_unlock_irq(&phba->hbalock);
12487 		return 0;
12488 	}
12489 
12490 	/* If PCI channel is offline, don't process it */
12491 	if (unlikely(pci_channel_offline(phba->pcidev))) {
12492 		spin_unlock_irq(&phba->hbalock);
12493 		return 0;
12494 	}
12495 
12496 	switch (phba->sli_rev) {
12497 	case LPFC_SLI_REV2:
12498 	case LPFC_SLI_REV3:
12499 		/* Read chip Host Attention (HA) register */
12500 		ha_copy = lpfc_sli_eratt_read(phba);
12501 		break;
12502 	case LPFC_SLI_REV4:
12503 		/* Read device Uncoverable Error (UERR) registers */
12504 		ha_copy = lpfc_sli4_eratt_read(phba);
12505 		break;
12506 	default:
12507 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12508 				"0299 Invalid SLI revision (%d)\n",
12509 				phba->sli_rev);
12510 		ha_copy = 0;
12511 		break;
12512 	}
12513 	spin_unlock_irq(&phba->hbalock);
12514 
12515 	return ha_copy;
12516 }
12517 
12518 /**
12519  * lpfc_intr_state_check - Check device state for interrupt handling
12520  * @phba: Pointer to HBA context.
12521  *
12522  * This inline routine checks whether a device or its PCI slot is in a state
12523  * that the interrupt should be handled.
12524  *
12525  * This function returns 0 if the device or the PCI slot is in a state that
12526  * interrupt should be handled, otherwise -EIO.
12527  */
12528 static inline int
12529 lpfc_intr_state_check(struct lpfc_hba *phba)
12530 {
12531 	/* If the pci channel is offline, ignore all the interrupts */
12532 	if (unlikely(pci_channel_offline(phba->pcidev)))
12533 		return -EIO;
12534 
12535 	/* Update device level interrupt statistics */
12536 	phba->sli.slistat.sli_intr++;
12537 
12538 	/* Ignore all interrupts during initialization. */
12539 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
12540 		return -EIO;
12541 
12542 	return 0;
12543 }
12544 
12545 /**
12546  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
12547  * @irq: Interrupt number.
12548  * @dev_id: The device context pointer.
12549  *
12550  * This function is directly called from the PCI layer as an interrupt
12551  * service routine when device with SLI-3 interface spec is enabled with
12552  * MSI-X multi-message interrupt mode and there are slow-path events in
12553  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
12554  * interrupt mode, this function is called as part of the device-level
12555  * interrupt handler. When the PCI slot is in error recovery or the HBA
12556  * is undergoing initialization, the interrupt handler will not process
12557  * the interrupt. The link attention and ELS ring attention events are
12558  * handled by the worker thread. The interrupt handler signals the worker
12559  * thread and returns for these events. This function is called without
12560  * any lock held. It gets the hbalock to access and update SLI data
12561  * structures.
12562  *
12563  * This function returns IRQ_HANDLED when interrupt is handled else it
12564  * returns IRQ_NONE.
12565  **/
12566 irqreturn_t
12567 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
12568 {
12569 	struct lpfc_hba  *phba;
12570 	uint32_t ha_copy, hc_copy;
12571 	uint32_t work_ha_copy;
12572 	unsigned long status;
12573 	unsigned long iflag;
12574 	uint32_t control;
12575 
12576 	MAILBOX_t *mbox, *pmbox;
12577 	struct lpfc_vport *vport;
12578 	struct lpfc_nodelist *ndlp;
12579 	struct lpfc_dmabuf *mp;
12580 	LPFC_MBOXQ_t *pmb;
12581 	int rc;
12582 
12583 	/*
12584 	 * Get the driver's phba structure from the dev_id and
12585 	 * assume the HBA is not interrupting.
12586 	 */
12587 	phba = (struct lpfc_hba *)dev_id;
12588 
12589 	if (unlikely(!phba))
12590 		return IRQ_NONE;
12591 
12592 	/*
12593 	 * Stuff needs to be attented to when this function is invoked as an
12594 	 * individual interrupt handler in MSI-X multi-message interrupt mode
12595 	 */
12596 	if (phba->intr_type == MSIX) {
12597 		/* Check device state for handling interrupt */
12598 		if (lpfc_intr_state_check(phba))
12599 			return IRQ_NONE;
12600 		/* Need to read HA REG for slow-path events */
12601 		spin_lock_irqsave(&phba->hbalock, iflag);
12602 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
12603 			goto unplug_error;
12604 		/* If somebody is waiting to handle an eratt don't process it
12605 		 * here. The brdkill function will do this.
12606 		 */
12607 		if (phba->link_flag & LS_IGNORE_ERATT)
12608 			ha_copy &= ~HA_ERATT;
12609 		/* Check the need for handling ERATT in interrupt handler */
12610 		if (ha_copy & HA_ERATT) {
12611 			if (phba->hba_flag & HBA_ERATT_HANDLED)
12612 				/* ERATT polling has handled ERATT */
12613 				ha_copy &= ~HA_ERATT;
12614 			else
12615 				/* Indicate interrupt handler handles ERATT */
12616 				phba->hba_flag |= HBA_ERATT_HANDLED;
12617 		}
12618 
12619 		/*
12620 		 * If there is deferred error attention, do not check for any
12621 		 * interrupt.
12622 		 */
12623 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12624 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12625 			return IRQ_NONE;
12626 		}
12627 
12628 		/* Clear up only attention source related to slow-path */
12629 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
12630 			goto unplug_error;
12631 
12632 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
12633 			HC_LAINT_ENA | HC_ERINT_ENA),
12634 			phba->HCregaddr);
12635 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
12636 			phba->HAregaddr);
12637 		writel(hc_copy, phba->HCregaddr);
12638 		readl(phba->HAregaddr); /* flush */
12639 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12640 	} else
12641 		ha_copy = phba->ha_copy;
12642 
12643 	work_ha_copy = ha_copy & phba->work_ha_mask;
12644 
12645 	if (work_ha_copy) {
12646 		if (work_ha_copy & HA_LATT) {
12647 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
12648 				/*
12649 				 * Turn off Link Attention interrupts
12650 				 * until CLEAR_LA done
12651 				 */
12652 				spin_lock_irqsave(&phba->hbalock, iflag);
12653 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
12654 				if (lpfc_readl(phba->HCregaddr, &control))
12655 					goto unplug_error;
12656 				control &= ~HC_LAINT_ENA;
12657 				writel(control, phba->HCregaddr);
12658 				readl(phba->HCregaddr); /* flush */
12659 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12660 			}
12661 			else
12662 				work_ha_copy &= ~HA_LATT;
12663 		}
12664 
12665 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
12666 			/*
12667 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
12668 			 * the only slow ring.
12669 			 */
12670 			status = (work_ha_copy &
12671 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
12672 			status >>= (4*LPFC_ELS_RING);
12673 			if (status & HA_RXMASK) {
12674 				spin_lock_irqsave(&phba->hbalock, iflag);
12675 				if (lpfc_readl(phba->HCregaddr, &control))
12676 					goto unplug_error;
12677 
12678 				lpfc_debugfs_slow_ring_trc(phba,
12679 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
12680 				control, status,
12681 				(uint32_t)phba->sli.slistat.sli_intr);
12682 
12683 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
12684 					lpfc_debugfs_slow_ring_trc(phba,
12685 						"ISR Disable ring:"
12686 						"pwork:x%x hawork:x%x wait:x%x",
12687 						phba->work_ha, work_ha_copy,
12688 						(uint32_t)((unsigned long)
12689 						&phba->work_waitq));
12690 
12691 					control &=
12692 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
12693 					writel(control, phba->HCregaddr);
12694 					readl(phba->HCregaddr); /* flush */
12695 				}
12696 				else {
12697 					lpfc_debugfs_slow_ring_trc(phba,
12698 						"ISR slow ring:   pwork:"
12699 						"x%x hawork:x%x wait:x%x",
12700 						phba->work_ha, work_ha_copy,
12701 						(uint32_t)((unsigned long)
12702 						&phba->work_waitq));
12703 				}
12704 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12705 			}
12706 		}
12707 		spin_lock_irqsave(&phba->hbalock, iflag);
12708 		if (work_ha_copy & HA_ERATT) {
12709 			if (lpfc_sli_read_hs(phba))
12710 				goto unplug_error;
12711 			/*
12712 			 * Check if there is a deferred error condition
12713 			 * is active
12714 			 */
12715 			if ((HS_FFER1 & phba->work_hs) &&
12716 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12717 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
12718 				  phba->work_hs)) {
12719 				phba->hba_flag |= DEFER_ERATT;
12720 				/* Clear all interrupt enable conditions */
12721 				writel(0, phba->HCregaddr);
12722 				readl(phba->HCregaddr);
12723 			}
12724 		}
12725 
12726 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
12727 			pmb = phba->sli.mbox_active;
12728 			pmbox = &pmb->u.mb;
12729 			mbox = phba->mbox;
12730 			vport = pmb->vport;
12731 
12732 			/* First check out the status word */
12733 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
12734 			if (pmbox->mbxOwner != OWN_HOST) {
12735 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12736 				/*
12737 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
12738 				 * mbxStatus <status>
12739 				 */
12740 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12741 						"(%d):0304 Stray Mailbox "
12742 						"Interrupt mbxCommand x%x "
12743 						"mbxStatus x%x\n",
12744 						(vport ? vport->vpi : 0),
12745 						pmbox->mbxCommand,
12746 						pmbox->mbxStatus);
12747 				/* clear mailbox attention bit */
12748 				work_ha_copy &= ~HA_MBATT;
12749 			} else {
12750 				phba->sli.mbox_active = NULL;
12751 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12752 				phba->last_completion_time = jiffies;
12753 				del_timer(&phba->sli.mbox_tmo);
12754 				if (pmb->mbox_cmpl) {
12755 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
12756 							MAILBOX_CMD_SIZE);
12757 					if (pmb->out_ext_byte_len &&
12758 						pmb->ctx_buf)
12759 						lpfc_sli_pcimem_bcopy(
12760 						phba->mbox_ext,
12761 						pmb->ctx_buf,
12762 						pmb->out_ext_byte_len);
12763 				}
12764 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
12765 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
12766 
12767 					lpfc_debugfs_disc_trc(vport,
12768 						LPFC_DISC_TRC_MBOX_VPORT,
12769 						"MBOX dflt rpi: : "
12770 						"status:x%x rpi:x%x",
12771 						(uint32_t)pmbox->mbxStatus,
12772 						pmbox->un.varWords[0], 0);
12773 
12774 					if (!pmbox->mbxStatus) {
12775 						mp = (struct lpfc_dmabuf *)
12776 							(pmb->ctx_buf);
12777 						ndlp = (struct lpfc_nodelist *)
12778 							pmb->ctx_ndlp;
12779 
12780 						/* Reg_LOGIN of dflt RPI was
12781 						 * successful. new lets get
12782 						 * rid of the RPI using the
12783 						 * same mbox buffer.
12784 						 */
12785 						lpfc_unreg_login(phba,
12786 							vport->vpi,
12787 							pmbox->un.varWords[0],
12788 							pmb);
12789 						pmb->mbox_cmpl =
12790 							lpfc_mbx_cmpl_dflt_rpi;
12791 						pmb->ctx_buf = mp;
12792 						pmb->ctx_ndlp = ndlp;
12793 						pmb->vport = vport;
12794 						rc = lpfc_sli_issue_mbox(phba,
12795 								pmb,
12796 								MBX_NOWAIT);
12797 						if (rc != MBX_BUSY)
12798 							lpfc_printf_log(phba,
12799 							KERN_ERR,
12800 							LOG_TRACE_EVENT,
12801 							"0350 rc should have"
12802 							"been MBX_BUSY\n");
12803 						if (rc != MBX_NOT_FINISHED)
12804 							goto send_current_mbox;
12805 					}
12806 				}
12807 				spin_lock_irqsave(
12808 						&phba->pport->work_port_lock,
12809 						iflag);
12810 				phba->pport->work_port_events &=
12811 					~WORKER_MBOX_TMO;
12812 				spin_unlock_irqrestore(
12813 						&phba->pport->work_port_lock,
12814 						iflag);
12815 				lpfc_mbox_cmpl_put(phba, pmb);
12816 			}
12817 		} else
12818 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12819 
12820 		if ((work_ha_copy & HA_MBATT) &&
12821 		    (phba->sli.mbox_active == NULL)) {
12822 send_current_mbox:
12823 			/* Process next mailbox command if there is one */
12824 			do {
12825 				rc = lpfc_sli_issue_mbox(phba, NULL,
12826 							 MBX_NOWAIT);
12827 			} while (rc == MBX_NOT_FINISHED);
12828 			if (rc != MBX_SUCCESS)
12829 				lpfc_printf_log(phba, KERN_ERR,
12830 						LOG_TRACE_EVENT,
12831 						"0349 rc should be "
12832 						"MBX_SUCCESS\n");
12833 		}
12834 
12835 		spin_lock_irqsave(&phba->hbalock, iflag);
12836 		phba->work_ha |= work_ha_copy;
12837 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12838 		lpfc_worker_wake_up(phba);
12839 	}
12840 	return IRQ_HANDLED;
12841 unplug_error:
12842 	spin_unlock_irqrestore(&phba->hbalock, iflag);
12843 	return IRQ_HANDLED;
12844 
12845 } /* lpfc_sli_sp_intr_handler */
12846 
12847 /**
12848  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
12849  * @irq: Interrupt number.
12850  * @dev_id: The device context pointer.
12851  *
12852  * This function is directly called from the PCI layer as an interrupt
12853  * service routine when device with SLI-3 interface spec is enabled with
12854  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
12855  * ring event in the HBA. However, when the device is enabled with either
12856  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
12857  * device-level interrupt handler. When the PCI slot is in error recovery
12858  * or the HBA is undergoing initialization, the interrupt handler will not
12859  * process the interrupt. The SCSI FCP fast-path ring event are handled in
12860  * the intrrupt context. This function is called without any lock held.
12861  * It gets the hbalock to access and update SLI data structures.
12862  *
12863  * This function returns IRQ_HANDLED when interrupt is handled else it
12864  * returns IRQ_NONE.
12865  **/
12866 irqreturn_t
12867 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
12868 {
12869 	struct lpfc_hba  *phba;
12870 	uint32_t ha_copy;
12871 	unsigned long status;
12872 	unsigned long iflag;
12873 	struct lpfc_sli_ring *pring;
12874 
12875 	/* Get the driver's phba structure from the dev_id and
12876 	 * assume the HBA is not interrupting.
12877 	 */
12878 	phba = (struct lpfc_hba *) dev_id;
12879 
12880 	if (unlikely(!phba))
12881 		return IRQ_NONE;
12882 
12883 	/*
12884 	 * Stuff needs to be attented to when this function is invoked as an
12885 	 * individual interrupt handler in MSI-X multi-message interrupt mode
12886 	 */
12887 	if (phba->intr_type == MSIX) {
12888 		/* Check device state for handling interrupt */
12889 		if (lpfc_intr_state_check(phba))
12890 			return IRQ_NONE;
12891 		/* Need to read HA REG for FCP ring and other ring events */
12892 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
12893 			return IRQ_HANDLED;
12894 		/* Clear up only attention source related to fast-path */
12895 		spin_lock_irqsave(&phba->hbalock, iflag);
12896 		/*
12897 		 * If there is deferred error attention, do not check for
12898 		 * any interrupt.
12899 		 */
12900 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12901 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12902 			return IRQ_NONE;
12903 		}
12904 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
12905 			phba->HAregaddr);
12906 		readl(phba->HAregaddr); /* flush */
12907 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12908 	} else
12909 		ha_copy = phba->ha_copy;
12910 
12911 	/*
12912 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
12913 	 */
12914 	ha_copy &= ~(phba->work_ha_mask);
12915 
12916 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
12917 	status >>= (4*LPFC_FCP_RING);
12918 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12919 	if (status & HA_RXMASK)
12920 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
12921 
12922 	if (phba->cfg_multi_ring_support == 2) {
12923 		/*
12924 		 * Process all events on extra ring. Take the optimized path
12925 		 * for extra ring IO.
12926 		 */
12927 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
12928 		status >>= (4*LPFC_EXTRA_RING);
12929 		if (status & HA_RXMASK) {
12930 			lpfc_sli_handle_fast_ring_event(phba,
12931 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
12932 					status);
12933 		}
12934 	}
12935 	return IRQ_HANDLED;
12936 }  /* lpfc_sli_fp_intr_handler */
12937 
12938 /**
12939  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
12940  * @irq: Interrupt number.
12941  * @dev_id: The device context pointer.
12942  *
12943  * This function is the HBA device-level interrupt handler to device with
12944  * SLI-3 interface spec, called from the PCI layer when either MSI or
12945  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
12946  * requires driver attention. This function invokes the slow-path interrupt
12947  * attention handling function and fast-path interrupt attention handling
12948  * function in turn to process the relevant HBA attention events. This
12949  * function is called without any lock held. It gets the hbalock to access
12950  * and update SLI data structures.
12951  *
12952  * This function returns IRQ_HANDLED when interrupt is handled, else it
12953  * returns IRQ_NONE.
12954  **/
12955 irqreturn_t
12956 lpfc_sli_intr_handler(int irq, void *dev_id)
12957 {
12958 	struct lpfc_hba  *phba;
12959 	irqreturn_t sp_irq_rc, fp_irq_rc;
12960 	unsigned long status1, status2;
12961 	uint32_t hc_copy;
12962 
12963 	/*
12964 	 * Get the driver's phba structure from the dev_id and
12965 	 * assume the HBA is not interrupting.
12966 	 */
12967 	phba = (struct lpfc_hba *) dev_id;
12968 
12969 	if (unlikely(!phba))
12970 		return IRQ_NONE;
12971 
12972 	/* Check device state for handling interrupt */
12973 	if (lpfc_intr_state_check(phba))
12974 		return IRQ_NONE;
12975 
12976 	spin_lock(&phba->hbalock);
12977 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
12978 		spin_unlock(&phba->hbalock);
12979 		return IRQ_HANDLED;
12980 	}
12981 
12982 	if (unlikely(!phba->ha_copy)) {
12983 		spin_unlock(&phba->hbalock);
12984 		return IRQ_NONE;
12985 	} else if (phba->ha_copy & HA_ERATT) {
12986 		if (phba->hba_flag & HBA_ERATT_HANDLED)
12987 			/* ERATT polling has handled ERATT */
12988 			phba->ha_copy &= ~HA_ERATT;
12989 		else
12990 			/* Indicate interrupt handler handles ERATT */
12991 			phba->hba_flag |= HBA_ERATT_HANDLED;
12992 	}
12993 
12994 	/*
12995 	 * If there is deferred error attention, do not check for any interrupt.
12996 	 */
12997 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12998 		spin_unlock(&phba->hbalock);
12999 		return IRQ_NONE;
13000 	}
13001 
13002 	/* Clear attention sources except link and error attentions */
13003 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
13004 		spin_unlock(&phba->hbalock);
13005 		return IRQ_HANDLED;
13006 	}
13007 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
13008 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
13009 		phba->HCregaddr);
13010 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
13011 	writel(hc_copy, phba->HCregaddr);
13012 	readl(phba->HAregaddr); /* flush */
13013 	spin_unlock(&phba->hbalock);
13014 
13015 	/*
13016 	 * Invokes slow-path host attention interrupt handling as appropriate.
13017 	 */
13018 
13019 	/* status of events with mailbox and link attention */
13020 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
13021 
13022 	/* status of events with ELS ring */
13023 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
13024 	status2 >>= (4*LPFC_ELS_RING);
13025 
13026 	if (status1 || (status2 & HA_RXMASK))
13027 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
13028 	else
13029 		sp_irq_rc = IRQ_NONE;
13030 
13031 	/*
13032 	 * Invoke fast-path host attention interrupt handling as appropriate.
13033 	 */
13034 
13035 	/* status of events with FCP ring */
13036 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13037 	status1 >>= (4*LPFC_FCP_RING);
13038 
13039 	/* status of events with extra ring */
13040 	if (phba->cfg_multi_ring_support == 2) {
13041 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13042 		status2 >>= (4*LPFC_EXTRA_RING);
13043 	} else
13044 		status2 = 0;
13045 
13046 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
13047 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
13048 	else
13049 		fp_irq_rc = IRQ_NONE;
13050 
13051 	/* Return device-level interrupt handling status */
13052 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
13053 }  /* lpfc_sli_intr_handler */
13054 
13055 /**
13056  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
13057  * @phba: pointer to lpfc hba data structure.
13058  *
13059  * This routine is invoked by the worker thread to process all the pending
13060  * SLI4 els abort xri events.
13061  **/
13062 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
13063 {
13064 	struct lpfc_cq_event *cq_event;
13065 
13066 	/* First, declare the els xri abort event has been handled */
13067 	spin_lock_irq(&phba->hbalock);
13068 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
13069 	spin_unlock_irq(&phba->hbalock);
13070 	/* Now, handle all the els xri abort events */
13071 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
13072 		/* Get the first event from the head of the event queue */
13073 		spin_lock_irq(&phba->hbalock);
13074 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
13075 				 cq_event, struct lpfc_cq_event, list);
13076 		spin_unlock_irq(&phba->hbalock);
13077 		/* Notify aborted XRI for ELS work queue */
13078 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
13079 		/* Free the event processed back to the free pool */
13080 		lpfc_sli4_cq_event_release(phba, cq_event);
13081 	}
13082 }
13083 
13084 /**
13085  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
13086  * @phba: pointer to lpfc hba data structure
13087  * @pIocbIn: pointer to the rspiocbq
13088  * @pIocbOut: pointer to the cmdiocbq
13089  * @wcqe: pointer to the complete wcqe
13090  *
13091  * This routine transfers the fields of a command iocbq to a response iocbq
13092  * by copying all the IOCB fields from command iocbq and transferring the
13093  * completion status information from the complete wcqe.
13094  **/
13095 static void
13096 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
13097 			      struct lpfc_iocbq *pIocbIn,
13098 			      struct lpfc_iocbq *pIocbOut,
13099 			      struct lpfc_wcqe_complete *wcqe)
13100 {
13101 	int numBdes, i;
13102 	unsigned long iflags;
13103 	uint32_t status, max_response;
13104 	struct lpfc_dmabuf *dmabuf;
13105 	struct ulp_bde64 *bpl, bde;
13106 	size_t offset = offsetof(struct lpfc_iocbq, iocb);
13107 
13108 	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
13109 	       sizeof(struct lpfc_iocbq) - offset);
13110 	/* Map WCQE parameters into irspiocb parameters */
13111 	status = bf_get(lpfc_wcqe_c_status, wcqe);
13112 	pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
13113 	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
13114 		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
13115 			pIocbIn->iocb.un.fcpi.fcpi_parm =
13116 					pIocbOut->iocb.un.fcpi.fcpi_parm -
13117 					wcqe->total_data_placed;
13118 		else
13119 			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
13120 	else {
13121 		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
13122 		switch (pIocbOut->iocb.ulpCommand) {
13123 		case CMD_ELS_REQUEST64_CR:
13124 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
13125 			bpl  = (struct ulp_bde64 *)dmabuf->virt;
13126 			bde.tus.w = le32_to_cpu(bpl[1].tus.w);
13127 			max_response = bde.tus.f.bdeSize;
13128 			break;
13129 		case CMD_GEN_REQUEST64_CR:
13130 			max_response = 0;
13131 			if (!pIocbOut->context3)
13132 				break;
13133 			numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
13134 					sizeof(struct ulp_bde64);
13135 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
13136 			bpl = (struct ulp_bde64 *)dmabuf->virt;
13137 			for (i = 0; i < numBdes; i++) {
13138 				bde.tus.w = le32_to_cpu(bpl[i].tus.w);
13139 				if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
13140 					max_response += bde.tus.f.bdeSize;
13141 			}
13142 			break;
13143 		default:
13144 			max_response = wcqe->total_data_placed;
13145 			break;
13146 		}
13147 		if (max_response < wcqe->total_data_placed)
13148 			pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
13149 		else
13150 			pIocbIn->iocb.un.genreq64.bdl.bdeSize =
13151 				wcqe->total_data_placed;
13152 	}
13153 
13154 	/* Convert BG errors for completion status */
13155 	if (status == CQE_STATUS_DI_ERROR) {
13156 		pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
13157 
13158 		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
13159 			pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
13160 		else
13161 			pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
13162 
13163 		pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
13164 		if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
13165 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13166 				BGS_GUARD_ERR_MASK;
13167 		if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
13168 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13169 				BGS_APPTAG_ERR_MASK;
13170 		if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
13171 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13172 				BGS_REFTAG_ERR_MASK;
13173 
13174 		/* Check to see if there was any good data before the error */
13175 		if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
13176 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13177 				BGS_HI_WATER_MARK_PRESENT_MASK;
13178 			pIocbIn->iocb.unsli3.sli3_bg.bghm =
13179 				wcqe->total_data_placed;
13180 		}
13181 
13182 		/*
13183 		* Set ALL the error bits to indicate we don't know what
13184 		* type of error it is.
13185 		*/
13186 		if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
13187 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13188 				(BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
13189 				BGS_GUARD_ERR_MASK);
13190 	}
13191 
13192 	/* Pick up HBA exchange busy condition */
13193 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
13194 		spin_lock_irqsave(&phba->hbalock, iflags);
13195 		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
13196 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13197 	}
13198 }
13199 
13200 /**
13201  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
13202  * @phba: Pointer to HBA context object.
13203  * @irspiocbq: Pointer to work-queue completion queue entry.
13204  *
13205  * This routine handles an ELS work-queue completion event and construct
13206  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
13207  * discovery engine to handle.
13208  *
13209  * Return: Pointer to the receive IOCBQ, NULL otherwise.
13210  **/
13211 static struct lpfc_iocbq *
13212 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
13213 			       struct lpfc_iocbq *irspiocbq)
13214 {
13215 	struct lpfc_sli_ring *pring;
13216 	struct lpfc_iocbq *cmdiocbq;
13217 	struct lpfc_wcqe_complete *wcqe;
13218 	unsigned long iflags;
13219 
13220 	pring = lpfc_phba_elsring(phba);
13221 	if (unlikely(!pring))
13222 		return NULL;
13223 
13224 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
13225 	pring->stats.iocb_event++;
13226 	/* Look up the ELS command IOCB and create pseudo response IOCB */
13227 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
13228 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13229 	if (unlikely(!cmdiocbq)) {
13230 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13231 				"0386 ELS complete with no corresponding "
13232 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
13233 				wcqe->word0, wcqe->total_data_placed,
13234 				wcqe->parameter, wcqe->word3);
13235 		lpfc_sli_release_iocbq(phba, irspiocbq);
13236 		return NULL;
13237 	}
13238 
13239 	spin_lock_irqsave(&pring->ring_lock, iflags);
13240 	/* Put the iocb back on the txcmplq */
13241 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
13242 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
13243 
13244 	/* Fake the irspiocbq and copy necessary response information */
13245 	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
13246 
13247 	return irspiocbq;
13248 }
13249 
13250 inline struct lpfc_cq_event *
13251 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
13252 {
13253 	struct lpfc_cq_event *cq_event;
13254 
13255 	/* Allocate a new internal CQ_EVENT entry */
13256 	cq_event = lpfc_sli4_cq_event_alloc(phba);
13257 	if (!cq_event) {
13258 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13259 				"0602 Failed to alloc CQ_EVENT entry\n");
13260 		return NULL;
13261 	}
13262 
13263 	/* Move the CQE into the event */
13264 	memcpy(&cq_event->cqe, entry, size);
13265 	return cq_event;
13266 }
13267 
13268 /**
13269  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
13270  * @phba: Pointer to HBA context object.
13271  * @mcqe: Pointer to mailbox completion queue entry.
13272  *
13273  * This routine process a mailbox completion queue entry with asynchronous
13274  * event.
13275  *
13276  * Return: true if work posted to worker thread, otherwise false.
13277  **/
13278 static bool
13279 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13280 {
13281 	struct lpfc_cq_event *cq_event;
13282 	unsigned long iflags;
13283 
13284 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13285 			"0392 Async Event: word0:x%x, word1:x%x, "
13286 			"word2:x%x, word3:x%x\n", mcqe->word0,
13287 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
13288 
13289 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
13290 	if (!cq_event)
13291 		return false;
13292 	spin_lock_irqsave(&phba->hbalock, iflags);
13293 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
13294 	/* Set the async event flag */
13295 	phba->hba_flag |= ASYNC_EVENT;
13296 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13297 
13298 	return true;
13299 }
13300 
13301 /**
13302  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
13303  * @phba: Pointer to HBA context object.
13304  * @mcqe: Pointer to mailbox completion queue entry.
13305  *
13306  * This routine process a mailbox completion queue entry with mailbox
13307  * completion event.
13308  *
13309  * Return: true if work posted to worker thread, otherwise false.
13310  **/
13311 static bool
13312 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13313 {
13314 	uint32_t mcqe_status;
13315 	MAILBOX_t *mbox, *pmbox;
13316 	struct lpfc_mqe *mqe;
13317 	struct lpfc_vport *vport;
13318 	struct lpfc_nodelist *ndlp;
13319 	struct lpfc_dmabuf *mp;
13320 	unsigned long iflags;
13321 	LPFC_MBOXQ_t *pmb;
13322 	bool workposted = false;
13323 	int rc;
13324 
13325 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
13326 	if (!bf_get(lpfc_trailer_completed, mcqe))
13327 		goto out_no_mqe_complete;
13328 
13329 	/* Get the reference to the active mbox command */
13330 	spin_lock_irqsave(&phba->hbalock, iflags);
13331 	pmb = phba->sli.mbox_active;
13332 	if (unlikely(!pmb)) {
13333 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13334 				"1832 No pending MBOX command to handle\n");
13335 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13336 		goto out_no_mqe_complete;
13337 	}
13338 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13339 	mqe = &pmb->u.mqe;
13340 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
13341 	mbox = phba->mbox;
13342 	vport = pmb->vport;
13343 
13344 	/* Reset heartbeat timer */
13345 	phba->last_completion_time = jiffies;
13346 	del_timer(&phba->sli.mbox_tmo);
13347 
13348 	/* Move mbox data to caller's mailbox region, do endian swapping */
13349 	if (pmb->mbox_cmpl && mbox)
13350 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
13351 
13352 	/*
13353 	 * For mcqe errors, conditionally move a modified error code to
13354 	 * the mbox so that the error will not be missed.
13355 	 */
13356 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
13357 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
13358 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
13359 			bf_set(lpfc_mqe_status, mqe,
13360 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
13361 	}
13362 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13363 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13364 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
13365 				      "MBOX dflt rpi: status:x%x rpi:x%x",
13366 				      mcqe_status,
13367 				      pmbox->un.varWords[0], 0);
13368 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
13369 			mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
13370 			ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
13371 			/* Reg_LOGIN of dflt RPI was successful. Now lets get
13372 			 * RID of the PPI using the same mbox buffer.
13373 			 */
13374 			lpfc_unreg_login(phba, vport->vpi,
13375 					 pmbox->un.varWords[0], pmb);
13376 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
13377 			pmb->ctx_buf = mp;
13378 			pmb->ctx_ndlp = ndlp;
13379 			pmb->vport = vport;
13380 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
13381 			if (rc != MBX_BUSY)
13382 				lpfc_printf_log(phba, KERN_ERR,
13383 						LOG_TRACE_EVENT,
13384 						"0385 rc should "
13385 						"have been MBX_BUSY\n");
13386 			if (rc != MBX_NOT_FINISHED)
13387 				goto send_current_mbox;
13388 		}
13389 	}
13390 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
13391 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
13392 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
13393 
13394 	/* There is mailbox completion work to do */
13395 	spin_lock_irqsave(&phba->hbalock, iflags);
13396 	__lpfc_mbox_cmpl_put(phba, pmb);
13397 	phba->work_ha |= HA_MBATT;
13398 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13399 	workposted = true;
13400 
13401 send_current_mbox:
13402 	spin_lock_irqsave(&phba->hbalock, iflags);
13403 	/* Release the mailbox command posting token */
13404 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13405 	/* Setting active mailbox pointer need to be in sync to flag clear */
13406 	phba->sli.mbox_active = NULL;
13407 	if (bf_get(lpfc_trailer_consumed, mcqe))
13408 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13409 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13410 	/* Wake up worker thread to post the next pending mailbox command */
13411 	lpfc_worker_wake_up(phba);
13412 	return workposted;
13413 
13414 out_no_mqe_complete:
13415 	spin_lock_irqsave(&phba->hbalock, iflags);
13416 	if (bf_get(lpfc_trailer_consumed, mcqe))
13417 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13418 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13419 	return false;
13420 }
13421 
13422 /**
13423  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
13424  * @phba: Pointer to HBA context object.
13425  * @cq: Pointer to associated CQ
13426  * @cqe: Pointer to mailbox completion queue entry.
13427  *
13428  * This routine process a mailbox completion queue entry, it invokes the
13429  * proper mailbox complete handling or asynchronous event handling routine
13430  * according to the MCQE's async bit.
13431  *
13432  * Return: true if work posted to worker thread, otherwise false.
13433  **/
13434 static bool
13435 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13436 			 struct lpfc_cqe *cqe)
13437 {
13438 	struct lpfc_mcqe mcqe;
13439 	bool workposted;
13440 
13441 	cq->CQ_mbox++;
13442 
13443 	/* Copy the mailbox MCQE and convert endian order as needed */
13444 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
13445 
13446 	/* Invoke the proper event handling routine */
13447 	if (!bf_get(lpfc_trailer_async, &mcqe))
13448 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
13449 	else
13450 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
13451 	return workposted;
13452 }
13453 
13454 /**
13455  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
13456  * @phba: Pointer to HBA context object.
13457  * @cq: Pointer to associated CQ
13458  * @wcqe: Pointer to work-queue completion queue entry.
13459  *
13460  * This routine handles an ELS work-queue completion event.
13461  *
13462  * Return: true if work posted to worker thread, otherwise false.
13463  **/
13464 static bool
13465 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13466 			     struct lpfc_wcqe_complete *wcqe)
13467 {
13468 	struct lpfc_iocbq *irspiocbq;
13469 	unsigned long iflags;
13470 	struct lpfc_sli_ring *pring = cq->pring;
13471 	int txq_cnt = 0;
13472 	int txcmplq_cnt = 0;
13473 
13474 	/* Check for response status */
13475 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
13476 		/* Log the error status */
13477 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13478 				"0357 ELS CQE error: status=x%x: "
13479 				"CQE: %08x %08x %08x %08x\n",
13480 				bf_get(lpfc_wcqe_c_status, wcqe),
13481 				wcqe->word0, wcqe->total_data_placed,
13482 				wcqe->parameter, wcqe->word3);
13483 	}
13484 
13485 	/* Get an irspiocbq for later ELS response processing use */
13486 	irspiocbq = lpfc_sli_get_iocbq(phba);
13487 	if (!irspiocbq) {
13488 		if (!list_empty(&pring->txq))
13489 			txq_cnt++;
13490 		if (!list_empty(&pring->txcmplq))
13491 			txcmplq_cnt++;
13492 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13493 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
13494 			"els_txcmplq_cnt=%d\n",
13495 			txq_cnt, phba->iocb_cnt,
13496 			txcmplq_cnt);
13497 		return false;
13498 	}
13499 
13500 	/* Save off the slow-path queue event for work thread to process */
13501 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
13502 	spin_lock_irqsave(&phba->hbalock, iflags);
13503 	list_add_tail(&irspiocbq->cq_event.list,
13504 		      &phba->sli4_hba.sp_queue_event);
13505 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
13506 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13507 
13508 	return true;
13509 }
13510 
13511 /**
13512  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
13513  * @phba: Pointer to HBA context object.
13514  * @wcqe: Pointer to work-queue completion queue entry.
13515  *
13516  * This routine handles slow-path WQ entry consumed event by invoking the
13517  * proper WQ release routine to the slow-path WQ.
13518  **/
13519 static void
13520 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
13521 			     struct lpfc_wcqe_release *wcqe)
13522 {
13523 	/* sanity check on queue memory */
13524 	if (unlikely(!phba->sli4_hba.els_wq))
13525 		return;
13526 	/* Check for the slow-path ELS work queue */
13527 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
13528 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
13529 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
13530 	else
13531 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13532 				"2579 Slow-path wqe consume event carries "
13533 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
13534 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
13535 				phba->sli4_hba.els_wq->queue_id);
13536 }
13537 
13538 /**
13539  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
13540  * @phba: Pointer to HBA context object.
13541  * @cq: Pointer to a WQ completion queue.
13542  * @wcqe: Pointer to work-queue completion queue entry.
13543  *
13544  * This routine handles an XRI abort event.
13545  *
13546  * Return: true if work posted to worker thread, otherwise false.
13547  **/
13548 static bool
13549 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
13550 				   struct lpfc_queue *cq,
13551 				   struct sli4_wcqe_xri_aborted *wcqe)
13552 {
13553 	bool workposted = false;
13554 	struct lpfc_cq_event *cq_event;
13555 	unsigned long iflags;
13556 
13557 	switch (cq->subtype) {
13558 	case LPFC_IO:
13559 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
13560 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13561 			/* Notify aborted XRI for NVME work queue */
13562 			if (phba->nvmet_support)
13563 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
13564 		}
13565 		workposted = false;
13566 		break;
13567 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
13568 	case LPFC_ELS:
13569 		cq_event = lpfc_cq_event_setup(
13570 			phba, wcqe, sizeof(struct sli4_wcqe_xri_aborted));
13571 		if (!cq_event)
13572 			return false;
13573 		cq_event->hdwq = cq->hdwq;
13574 		spin_lock_irqsave(&phba->hbalock, iflags);
13575 		list_add_tail(&cq_event->list,
13576 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
13577 		/* Set the els xri abort event flag */
13578 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
13579 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13580 		workposted = true;
13581 		break;
13582 	default:
13583 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13584 				"0603 Invalid CQ subtype %d: "
13585 				"%08x %08x %08x %08x\n",
13586 				cq->subtype, wcqe->word0, wcqe->parameter,
13587 				wcqe->word2, wcqe->word3);
13588 		workposted = false;
13589 		break;
13590 	}
13591 	return workposted;
13592 }
13593 
13594 #define FC_RCTL_MDS_DIAGS	0xF4
13595 
13596 /**
13597  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
13598  * @phba: Pointer to HBA context object.
13599  * @rcqe: Pointer to receive-queue completion queue entry.
13600  *
13601  * This routine process a receive-queue completion queue entry.
13602  *
13603  * Return: true if work posted to worker thread, otherwise false.
13604  **/
13605 static bool
13606 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
13607 {
13608 	bool workposted = false;
13609 	struct fc_frame_header *fc_hdr;
13610 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
13611 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
13612 	struct lpfc_nvmet_tgtport *tgtp;
13613 	struct hbq_dmabuf *dma_buf;
13614 	uint32_t status, rq_id;
13615 	unsigned long iflags;
13616 
13617 	/* sanity check on queue memory */
13618 	if (unlikely(!hrq) || unlikely(!drq))
13619 		return workposted;
13620 
13621 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
13622 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
13623 	else
13624 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
13625 	if (rq_id != hrq->queue_id)
13626 		goto out;
13627 
13628 	status = bf_get(lpfc_rcqe_status, rcqe);
13629 	switch (status) {
13630 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
13631 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13632 				"2537 Receive Frame Truncated!!\n");
13633 		/* fall through */
13634 	case FC_STATUS_RQ_SUCCESS:
13635 		spin_lock_irqsave(&phba->hbalock, iflags);
13636 		lpfc_sli4_rq_release(hrq, drq);
13637 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
13638 		if (!dma_buf) {
13639 			hrq->RQ_no_buf_found++;
13640 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13641 			goto out;
13642 		}
13643 		hrq->RQ_rcv_buf++;
13644 		hrq->RQ_buf_posted--;
13645 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
13646 
13647 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
13648 
13649 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
13650 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
13651 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13652 			/* Handle MDS Loopback frames */
13653 			lpfc_sli4_handle_mds_loopback(phba->pport, dma_buf);
13654 			break;
13655 		}
13656 
13657 		/* save off the frame for the work thread to process */
13658 		list_add_tail(&dma_buf->cq_event.list,
13659 			      &phba->sli4_hba.sp_queue_event);
13660 		/* Frame received */
13661 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
13662 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13663 		workposted = true;
13664 		break;
13665 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
13666 		if (phba->nvmet_support) {
13667 			tgtp = phba->targetport->private;
13668 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13669 					"6402 RQE Error x%x, posted %d err_cnt "
13670 					"%d: %x %x %x\n",
13671 					status, hrq->RQ_buf_posted,
13672 					hrq->RQ_no_posted_buf,
13673 					atomic_read(&tgtp->rcv_fcp_cmd_in),
13674 					atomic_read(&tgtp->rcv_fcp_cmd_out),
13675 					atomic_read(&tgtp->xmt_fcp_release));
13676 		}
13677 		/* fallthrough */
13678 
13679 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
13680 		hrq->RQ_no_posted_buf++;
13681 		/* Post more buffers if possible */
13682 		spin_lock_irqsave(&phba->hbalock, iflags);
13683 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
13684 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13685 		workposted = true;
13686 		break;
13687 	}
13688 out:
13689 	return workposted;
13690 }
13691 
13692 /**
13693  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
13694  * @phba: Pointer to HBA context object.
13695  * @cq: Pointer to the completion queue.
13696  * @cqe: Pointer to a completion queue entry.
13697  *
13698  * This routine process a slow-path work-queue or receive queue completion queue
13699  * entry.
13700  *
13701  * Return: true if work posted to worker thread, otherwise false.
13702  **/
13703 static bool
13704 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13705 			 struct lpfc_cqe *cqe)
13706 {
13707 	struct lpfc_cqe cqevt;
13708 	bool workposted = false;
13709 
13710 	/* Copy the work queue CQE and convert endian order if needed */
13711 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
13712 
13713 	/* Check and process for different type of WCQE and dispatch */
13714 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
13715 	case CQE_CODE_COMPL_WQE:
13716 		/* Process the WQ/RQ complete event */
13717 		phba->last_completion_time = jiffies;
13718 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
13719 				(struct lpfc_wcqe_complete *)&cqevt);
13720 		break;
13721 	case CQE_CODE_RELEASE_WQE:
13722 		/* Process the WQ release event */
13723 		lpfc_sli4_sp_handle_rel_wcqe(phba,
13724 				(struct lpfc_wcqe_release *)&cqevt);
13725 		break;
13726 	case CQE_CODE_XRI_ABORTED:
13727 		/* Process the WQ XRI abort event */
13728 		phba->last_completion_time = jiffies;
13729 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
13730 				(struct sli4_wcqe_xri_aborted *)&cqevt);
13731 		break;
13732 	case CQE_CODE_RECEIVE:
13733 	case CQE_CODE_RECEIVE_V1:
13734 		/* Process the RQ event */
13735 		phba->last_completion_time = jiffies;
13736 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
13737 				(struct lpfc_rcqe *)&cqevt);
13738 		break;
13739 	default:
13740 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13741 				"0388 Not a valid WCQE code: x%x\n",
13742 				bf_get(lpfc_cqe_code, &cqevt));
13743 		break;
13744 	}
13745 	return workposted;
13746 }
13747 
13748 /**
13749  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
13750  * @phba: Pointer to HBA context object.
13751  * @eqe: Pointer to fast-path event queue entry.
13752  * @speq: Pointer to slow-path event queue.
13753  *
13754  * This routine process a event queue entry from the slow-path event queue.
13755  * It will check the MajorCode and MinorCode to determine this is for a
13756  * completion event on a completion queue, if not, an error shall be logged
13757  * and just return. Otherwise, it will get to the corresponding completion
13758  * queue and process all the entries on that completion queue, rearm the
13759  * completion queue, and then return.
13760  *
13761  **/
13762 static void
13763 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
13764 	struct lpfc_queue *speq)
13765 {
13766 	struct lpfc_queue *cq = NULL, *childq;
13767 	uint16_t cqid;
13768 	int ret = 0;
13769 
13770 	/* Get the reference to the corresponding CQ */
13771 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
13772 
13773 	list_for_each_entry(childq, &speq->child_list, list) {
13774 		if (childq->queue_id == cqid) {
13775 			cq = childq;
13776 			break;
13777 		}
13778 	}
13779 	if (unlikely(!cq)) {
13780 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
13781 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13782 					"0365 Slow-path CQ identifier "
13783 					"(%d) does not exist\n", cqid);
13784 		return;
13785 	}
13786 
13787 	/* Save EQ associated with this CQ */
13788 	cq->assoc_qp = speq;
13789 
13790 	if (is_kdump_kernel())
13791 		ret = queue_work(phba->wq, &cq->spwork);
13792 	else
13793 		ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
13794 
13795 	if (!ret)
13796 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13797 				"0390 Cannot schedule queue work "
13798 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
13799 				cqid, cq->queue_id, raw_smp_processor_id());
13800 }
13801 
13802 /**
13803  * __lpfc_sli4_process_cq - Process elements of a CQ
13804  * @phba: Pointer to HBA context object.
13805  * @cq: Pointer to CQ to be processed
13806  * @handler: Routine to process each cqe
13807  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
13808  * @poll_mode: Polling mode we were called from
13809  *
13810  * This routine processes completion queue entries in a CQ. While a valid
13811  * queue element is found, the handler is called. During processing checks
13812  * are made for periodic doorbell writes to let the hardware know of
13813  * element consumption.
13814  *
13815  * If the max limit on cqes to process is hit, or there are no more valid
13816  * entries, the loop stops. If we processed a sufficient number of elements,
13817  * meaning there is sufficient load, rather than rearming and generating
13818  * another interrupt, a cq rescheduling delay will be set. A delay of 0
13819  * indicates no rescheduling.
13820  *
13821  * Returns True if work scheduled, False otherwise.
13822  **/
13823 static bool
13824 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
13825 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
13826 			struct lpfc_cqe *), unsigned long *delay,
13827 			enum lpfc_poll_mode poll_mode)
13828 {
13829 	struct lpfc_cqe *cqe;
13830 	bool workposted = false;
13831 	int count = 0, consumed = 0;
13832 	bool arm = true;
13833 
13834 	/* default - no reschedule */
13835 	*delay = 0;
13836 
13837 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
13838 		goto rearm_and_exit;
13839 
13840 	/* Process all the entries to the CQ */
13841 	cq->q_flag = 0;
13842 	cqe = lpfc_sli4_cq_get(cq);
13843 	while (cqe) {
13844 		workposted |= handler(phba, cq, cqe);
13845 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
13846 
13847 		consumed++;
13848 		if (!(++count % cq->max_proc_limit))
13849 			break;
13850 
13851 		if (!(count % cq->notify_interval)) {
13852 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
13853 						LPFC_QUEUE_NOARM);
13854 			consumed = 0;
13855 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
13856 		}
13857 
13858 		if (count == LPFC_NVMET_CQ_NOTIFY)
13859 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
13860 
13861 		cqe = lpfc_sli4_cq_get(cq);
13862 	}
13863 	if (count >= phba->cfg_cq_poll_threshold) {
13864 		*delay = 1;
13865 		arm = false;
13866 	}
13867 
13868 	/* Note: complete the irq_poll softirq before rearming CQ */
13869 	if (poll_mode == LPFC_IRQ_POLL)
13870 		irq_poll_complete(&cq->iop);
13871 
13872 	/* Track the max number of CQEs processed in 1 EQ */
13873 	if (count > cq->CQ_max_cqe)
13874 		cq->CQ_max_cqe = count;
13875 
13876 	cq->assoc_qp->EQ_cqe_cnt += count;
13877 
13878 	/* Catch the no cq entry condition */
13879 	if (unlikely(count == 0))
13880 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13881 				"0369 No entry from completion queue "
13882 				"qid=%d\n", cq->queue_id);
13883 
13884 	xchg(&cq->queue_claimed, 0);
13885 
13886 rearm_and_exit:
13887 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
13888 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
13889 
13890 	return workposted;
13891 }
13892 
13893 /**
13894  * lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
13895  * @cq: pointer to CQ to process
13896  *
13897  * This routine calls the cq processing routine with a handler specific
13898  * to the type of queue bound to it.
13899  *
13900  * The CQ routine returns two values: the first is the calling status,
13901  * which indicates whether work was queued to the  background discovery
13902  * thread. If true, the routine should wakeup the discovery thread;
13903  * the second is the delay parameter. If non-zero, rather than rearming
13904  * the CQ and yet another interrupt, the CQ handler should be queued so
13905  * that it is processed in a subsequent polling action. The value of
13906  * the delay indicates when to reschedule it.
13907  **/
13908 static void
13909 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
13910 {
13911 	struct lpfc_hba *phba = cq->phba;
13912 	unsigned long delay;
13913 	bool workposted = false;
13914 	int ret = 0;
13915 
13916 	/* Process and rearm the CQ */
13917 	switch (cq->type) {
13918 	case LPFC_MCQ:
13919 		workposted |= __lpfc_sli4_process_cq(phba, cq,
13920 						lpfc_sli4_sp_handle_mcqe,
13921 						&delay, LPFC_QUEUE_WORK);
13922 		break;
13923 	case LPFC_WCQ:
13924 		if (cq->subtype == LPFC_IO)
13925 			workposted |= __lpfc_sli4_process_cq(phba, cq,
13926 						lpfc_sli4_fp_handle_cqe,
13927 						&delay, LPFC_QUEUE_WORK);
13928 		else
13929 			workposted |= __lpfc_sli4_process_cq(phba, cq,
13930 						lpfc_sli4_sp_handle_cqe,
13931 						&delay, LPFC_QUEUE_WORK);
13932 		break;
13933 	default:
13934 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13935 				"0370 Invalid completion queue type (%d)\n",
13936 				cq->type);
13937 		return;
13938 	}
13939 
13940 	if (delay) {
13941 		if (is_kdump_kernel())
13942 			ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
13943 						delay);
13944 		else
13945 			ret = queue_delayed_work_on(cq->chann, phba->wq,
13946 						&cq->sched_spwork, delay);
13947 		if (!ret)
13948 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13949 				"0394 Cannot schedule queue work "
13950 				"for cqid=%d on CPU %d\n",
13951 				cq->queue_id, cq->chann);
13952 	}
13953 
13954 	/* wake up worker thread if there are works to be done */
13955 	if (workposted)
13956 		lpfc_worker_wake_up(phba);
13957 }
13958 
13959 /**
13960  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
13961  *   interrupt
13962  * @work: pointer to work element
13963  *
13964  * translates from the work handler and calls the slow-path handler.
13965  **/
13966 static void
13967 lpfc_sli4_sp_process_cq(struct work_struct *work)
13968 {
13969 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
13970 
13971 	__lpfc_sli4_sp_process_cq(cq);
13972 }
13973 
13974 /**
13975  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
13976  * @work: pointer to work element
13977  *
13978  * translates from the work handler and calls the slow-path handler.
13979  **/
13980 static void
13981 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
13982 {
13983 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
13984 					struct lpfc_queue, sched_spwork);
13985 
13986 	__lpfc_sli4_sp_process_cq(cq);
13987 }
13988 
13989 /**
13990  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
13991  * @phba: Pointer to HBA context object.
13992  * @cq: Pointer to associated CQ
13993  * @wcqe: Pointer to work-queue completion queue entry.
13994  *
13995  * This routine process a fast-path work queue completion entry from fast-path
13996  * event queue for FCP command response completion.
13997  **/
13998 static void
13999 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14000 			     struct lpfc_wcqe_complete *wcqe)
14001 {
14002 	struct lpfc_sli_ring *pring = cq->pring;
14003 	struct lpfc_iocbq *cmdiocbq;
14004 	struct lpfc_iocbq irspiocbq;
14005 	unsigned long iflags;
14006 
14007 	/* Check for response status */
14008 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14009 		/* If resource errors reported from HBA, reduce queue
14010 		 * depth of the SCSI device.
14011 		 */
14012 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
14013 		     IOSTAT_LOCAL_REJECT)) &&
14014 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
14015 		     IOERR_NO_RESOURCES))
14016 			phba->lpfc_rampdown_queue_depth(phba);
14017 
14018 		/* Log the cmpl status */
14019 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14020 				"0373 FCP CQE cmpl: status=x%x: "
14021 				"CQE: %08x %08x %08x %08x\n",
14022 				bf_get(lpfc_wcqe_c_status, wcqe),
14023 				wcqe->word0, wcqe->total_data_placed,
14024 				wcqe->parameter, wcqe->word3);
14025 	}
14026 
14027 	/* Look up the FCP command IOCB and create pseudo response IOCB */
14028 	spin_lock_irqsave(&pring->ring_lock, iflags);
14029 	pring->stats.iocb_event++;
14030 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
14031 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14032 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14033 	if (unlikely(!cmdiocbq)) {
14034 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14035 				"0374 FCP complete with no corresponding "
14036 				"cmdiocb: iotag (%d)\n",
14037 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14038 		return;
14039 	}
14040 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
14041 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
14042 #endif
14043 	if (cmdiocbq->iocb_cmpl == NULL) {
14044 		if (cmdiocbq->wqe_cmpl) {
14045 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
14046 				spin_lock_irqsave(&phba->hbalock, iflags);
14047 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
14048 				spin_unlock_irqrestore(&phba->hbalock, iflags);
14049 			}
14050 
14051 			/* Pass the cmd_iocb and the wcqe to the upper layer */
14052 			(cmdiocbq->wqe_cmpl)(phba, cmdiocbq, wcqe);
14053 			return;
14054 		}
14055 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14056 				"0375 FCP cmdiocb not callback function "
14057 				"iotag: (%d)\n",
14058 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14059 		return;
14060 	}
14061 
14062 	/* Fake the irspiocb and copy necessary response information */
14063 	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
14064 
14065 	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
14066 		spin_lock_irqsave(&phba->hbalock, iflags);
14067 		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
14068 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14069 	}
14070 
14071 	/* Pass the cmd_iocb and the rsp state to the upper layer */
14072 	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
14073 }
14074 
14075 /**
14076  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
14077  * @phba: Pointer to HBA context object.
14078  * @cq: Pointer to completion queue.
14079  * @wcqe: Pointer to work-queue completion queue entry.
14080  *
14081  * This routine handles an fast-path WQ entry consumed event by invoking the
14082  * proper WQ release routine to the slow-path WQ.
14083  **/
14084 static void
14085 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14086 			     struct lpfc_wcqe_release *wcqe)
14087 {
14088 	struct lpfc_queue *childwq;
14089 	bool wqid_matched = false;
14090 	uint16_t hba_wqid;
14091 
14092 	/* Check for fast-path FCP work queue release */
14093 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
14094 	list_for_each_entry(childwq, &cq->child_list, list) {
14095 		if (childwq->queue_id == hba_wqid) {
14096 			lpfc_sli4_wq_release(childwq,
14097 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14098 			if (childwq->q_flag & HBA_NVMET_WQFULL)
14099 				lpfc_nvmet_wqfull_process(phba, childwq);
14100 			wqid_matched = true;
14101 			break;
14102 		}
14103 	}
14104 	/* Report warning log message if no match found */
14105 	if (wqid_matched != true)
14106 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14107 				"2580 Fast-path wqe consume event carries "
14108 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
14109 }
14110 
14111 /**
14112  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
14113  * @phba: Pointer to HBA context object.
14114  * @cq: Pointer to completion queue.
14115  * @rcqe: Pointer to receive-queue completion queue entry.
14116  *
14117  * This routine process a receive-queue completion queue entry.
14118  *
14119  * Return: true if work posted to worker thread, otherwise false.
14120  **/
14121 static bool
14122 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14123 			    struct lpfc_rcqe *rcqe)
14124 {
14125 	bool workposted = false;
14126 	struct lpfc_queue *hrq;
14127 	struct lpfc_queue *drq;
14128 	struct rqb_dmabuf *dma_buf;
14129 	struct fc_frame_header *fc_hdr;
14130 	struct lpfc_nvmet_tgtport *tgtp;
14131 	uint32_t status, rq_id;
14132 	unsigned long iflags;
14133 	uint32_t fctl, idx;
14134 
14135 	if ((phba->nvmet_support == 0) ||
14136 	    (phba->sli4_hba.nvmet_cqset == NULL))
14137 		return workposted;
14138 
14139 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
14140 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
14141 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
14142 
14143 	/* sanity check on queue memory */
14144 	if (unlikely(!hrq) || unlikely(!drq))
14145 		return workposted;
14146 
14147 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14148 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14149 	else
14150 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14151 
14152 	if ((phba->nvmet_support == 0) ||
14153 	    (rq_id != hrq->queue_id))
14154 		return workposted;
14155 
14156 	status = bf_get(lpfc_rcqe_status, rcqe);
14157 	switch (status) {
14158 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14159 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14160 				"6126 Receive Frame Truncated!!\n");
14161 		/* fall through */
14162 	case FC_STATUS_RQ_SUCCESS:
14163 		spin_lock_irqsave(&phba->hbalock, iflags);
14164 		lpfc_sli4_rq_release(hrq, drq);
14165 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
14166 		if (!dma_buf) {
14167 			hrq->RQ_no_buf_found++;
14168 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14169 			goto out;
14170 		}
14171 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14172 		hrq->RQ_rcv_buf++;
14173 		hrq->RQ_buf_posted--;
14174 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14175 
14176 		/* Just some basic sanity checks on FCP Command frame */
14177 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
14178 			fc_hdr->fh_f_ctl[1] << 8 |
14179 			fc_hdr->fh_f_ctl[2]);
14180 		if (((fctl &
14181 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
14182 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
14183 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
14184 			goto drop;
14185 
14186 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
14187 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
14188 			lpfc_nvmet_unsol_fcp_event(
14189 				phba, idx, dma_buf, cq->isr_timestamp,
14190 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
14191 			return false;
14192 		}
14193 drop:
14194 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
14195 		break;
14196 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14197 		if (phba->nvmet_support) {
14198 			tgtp = phba->targetport->private;
14199 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14200 					"6401 RQE Error x%x, posted %d err_cnt "
14201 					"%d: %x %x %x\n",
14202 					status, hrq->RQ_buf_posted,
14203 					hrq->RQ_no_posted_buf,
14204 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14205 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14206 					atomic_read(&tgtp->xmt_fcp_release));
14207 		}
14208 		/* fallthrough */
14209 
14210 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14211 		hrq->RQ_no_posted_buf++;
14212 		/* Post more buffers if possible */
14213 		break;
14214 	}
14215 out:
14216 	return workposted;
14217 }
14218 
14219 /**
14220  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
14221  * @phba: adapter with cq
14222  * @cq: Pointer to the completion queue.
14223  * @cqe: Pointer to fast-path completion queue entry.
14224  *
14225  * This routine process a fast-path work queue completion entry from fast-path
14226  * event queue for FCP command response completion.
14227  *
14228  * Return: true if work posted to worker thread, otherwise false.
14229  **/
14230 static bool
14231 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14232 			 struct lpfc_cqe *cqe)
14233 {
14234 	struct lpfc_wcqe_release wcqe;
14235 	bool workposted = false;
14236 
14237 	/* Copy the work queue CQE and convert endian order if needed */
14238 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
14239 
14240 	/* Check and process for different type of WCQE and dispatch */
14241 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
14242 	case CQE_CODE_COMPL_WQE:
14243 	case CQE_CODE_NVME_ERSP:
14244 		cq->CQ_wq++;
14245 		/* Process the WQ complete event */
14246 		phba->last_completion_time = jiffies;
14247 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
14248 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
14249 				(struct lpfc_wcqe_complete *)&wcqe);
14250 		break;
14251 	case CQE_CODE_RELEASE_WQE:
14252 		cq->CQ_release_wqe++;
14253 		/* Process the WQ release event */
14254 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
14255 				(struct lpfc_wcqe_release *)&wcqe);
14256 		break;
14257 	case CQE_CODE_XRI_ABORTED:
14258 		cq->CQ_xri_aborted++;
14259 		/* Process the WQ XRI abort event */
14260 		phba->last_completion_time = jiffies;
14261 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14262 				(struct sli4_wcqe_xri_aborted *)&wcqe);
14263 		break;
14264 	case CQE_CODE_RECEIVE_V1:
14265 	case CQE_CODE_RECEIVE:
14266 		phba->last_completion_time = jiffies;
14267 		if (cq->subtype == LPFC_NVMET) {
14268 			workposted = lpfc_sli4_nvmet_handle_rcqe(
14269 				phba, cq, (struct lpfc_rcqe *)&wcqe);
14270 		}
14271 		break;
14272 	default:
14273 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14274 				"0144 Not a valid CQE code: x%x\n",
14275 				bf_get(lpfc_wcqe_c_code, &wcqe));
14276 		break;
14277 	}
14278 	return workposted;
14279 }
14280 
14281 /**
14282  * lpfc_sli4_sched_cq_work - Schedules cq work
14283  * @phba: Pointer to HBA context object.
14284  * @cq: Pointer to CQ
14285  * @cqid: CQ ID
14286  *
14287  * This routine checks the poll mode of the CQ corresponding to
14288  * cq->chann, then either schedules a softirq or queue_work to complete
14289  * cq work.
14290  *
14291  * queue_work path is taken if in NVMET mode, or if poll_mode is in
14292  * LPFC_QUEUE_WORK mode.  Otherwise, softirq path is taken.
14293  *
14294  **/
14295 static void lpfc_sli4_sched_cq_work(struct lpfc_hba *phba,
14296 				    struct lpfc_queue *cq, uint16_t cqid)
14297 {
14298 	int ret = 0;
14299 
14300 	switch (cq->poll_mode) {
14301 	case LPFC_IRQ_POLL:
14302 		irq_poll_sched(&cq->iop);
14303 		break;
14304 	case LPFC_QUEUE_WORK:
14305 	default:
14306 		if (is_kdump_kernel())
14307 			ret = queue_work(phba->wq, &cq->irqwork);
14308 		else
14309 			ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
14310 		if (!ret)
14311 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14312 					"0383 Cannot schedule queue work "
14313 					"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14314 					cqid, cq->queue_id,
14315 					raw_smp_processor_id());
14316 	}
14317 }
14318 
14319 /**
14320  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
14321  * @phba: Pointer to HBA context object.
14322  * @eq: Pointer to the queue structure.
14323  * @eqe: Pointer to fast-path event queue entry.
14324  *
14325  * This routine process a event queue entry from the fast-path event queue.
14326  * It will check the MajorCode and MinorCode to determine this is for a
14327  * completion event on a completion queue, if not, an error shall be logged
14328  * and just return. Otherwise, it will get to the corresponding completion
14329  * queue and process all the entries on the completion queue, rearm the
14330  * completion queue, and then return.
14331  **/
14332 static void
14333 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
14334 			 struct lpfc_eqe *eqe)
14335 {
14336 	struct lpfc_queue *cq = NULL;
14337 	uint32_t qidx = eq->hdwq;
14338 	uint16_t cqid, id;
14339 
14340 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
14341 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14342 				"0366 Not a valid completion "
14343 				"event: majorcode=x%x, minorcode=x%x\n",
14344 				bf_get_le32(lpfc_eqe_major_code, eqe),
14345 				bf_get_le32(lpfc_eqe_minor_code, eqe));
14346 		return;
14347 	}
14348 
14349 	/* Get the reference to the corresponding CQ */
14350 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14351 
14352 	/* Use the fast lookup method first */
14353 	if (cqid <= phba->sli4_hba.cq_max) {
14354 		cq = phba->sli4_hba.cq_lookup[cqid];
14355 		if (cq)
14356 			goto  work_cq;
14357 	}
14358 
14359 	/* Next check for NVMET completion */
14360 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
14361 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
14362 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
14363 			/* Process NVMET unsol rcv */
14364 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
14365 			goto  process_cq;
14366 		}
14367 	}
14368 
14369 	if (phba->sli4_hba.nvmels_cq &&
14370 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
14371 		/* Process NVME unsol rcv */
14372 		cq = phba->sli4_hba.nvmels_cq;
14373 	}
14374 
14375 	/* Otherwise this is a Slow path event */
14376 	if (cq == NULL) {
14377 		lpfc_sli4_sp_handle_eqe(phba, eqe,
14378 					phba->sli4_hba.hdwq[qidx].hba_eq);
14379 		return;
14380 	}
14381 
14382 process_cq:
14383 	if (unlikely(cqid != cq->queue_id)) {
14384 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14385 				"0368 Miss-matched fast-path completion "
14386 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
14387 				cqid, cq->queue_id);
14388 		return;
14389 	}
14390 
14391 work_cq:
14392 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
14393 	if (phba->ktime_on)
14394 		cq->isr_timestamp = ktime_get_ns();
14395 	else
14396 		cq->isr_timestamp = 0;
14397 #endif
14398 	lpfc_sli4_sched_cq_work(phba, cq, cqid);
14399 }
14400 
14401 /**
14402  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
14403  * @cq: Pointer to CQ to be processed
14404  * @poll_mode: Enum lpfc_poll_state to determine poll mode
14405  *
14406  * This routine calls the cq processing routine with the handler for
14407  * fast path CQEs.
14408  *
14409  * The CQ routine returns two values: the first is the calling status,
14410  * which indicates whether work was queued to the  background discovery
14411  * thread. If true, the routine should wakeup the discovery thread;
14412  * the second is the delay parameter. If non-zero, rather than rearming
14413  * the CQ and yet another interrupt, the CQ handler should be queued so
14414  * that it is processed in a subsequent polling action. The value of
14415  * the delay indicates when to reschedule it.
14416  **/
14417 static void
14418 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq,
14419 			   enum lpfc_poll_mode poll_mode)
14420 {
14421 	struct lpfc_hba *phba = cq->phba;
14422 	unsigned long delay;
14423 	bool workposted = false;
14424 	int ret = 0;
14425 
14426 	/* process and rearm the CQ */
14427 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
14428 					     &delay, poll_mode);
14429 
14430 	if (delay) {
14431 		if (is_kdump_kernel())
14432 			ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
14433 						delay);
14434 		else
14435 			ret = queue_delayed_work_on(cq->chann, phba->wq,
14436 						&cq->sched_irqwork, delay);
14437 		if (!ret)
14438 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14439 					"0367 Cannot schedule queue work "
14440 					"for cqid=%d on CPU %d\n",
14441 					cq->queue_id, cq->chann);
14442 	}
14443 
14444 	/* wake up worker thread if there are works to be done */
14445 	if (workposted)
14446 		lpfc_worker_wake_up(phba);
14447 }
14448 
14449 /**
14450  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
14451  *   interrupt
14452  * @work: pointer to work element
14453  *
14454  * translates from the work handler and calls the fast-path handler.
14455  **/
14456 static void
14457 lpfc_sli4_hba_process_cq(struct work_struct *work)
14458 {
14459 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
14460 
14461 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
14462 }
14463 
14464 /**
14465  * lpfc_sli4_hba_process_cq - fast-path work handler when started by timer
14466  * @work: pointer to work element
14467  *
14468  * translates from the work handler and calls the fast-path handler.
14469  **/
14470 static void
14471 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
14472 {
14473 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
14474 					struct lpfc_queue, sched_irqwork);
14475 
14476 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
14477 }
14478 
14479 /**
14480  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
14481  * @irq: Interrupt number.
14482  * @dev_id: The device context pointer.
14483  *
14484  * This function is directly called from the PCI layer as an interrupt
14485  * service routine when device with SLI-4 interface spec is enabled with
14486  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
14487  * ring event in the HBA. However, when the device is enabled with either
14488  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
14489  * device-level interrupt handler. When the PCI slot is in error recovery
14490  * or the HBA is undergoing initialization, the interrupt handler will not
14491  * process the interrupt. The SCSI FCP fast-path ring event are handled in
14492  * the intrrupt context. This function is called without any lock held.
14493  * It gets the hbalock to access and update SLI data structures. Note that,
14494  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
14495  * equal to that of FCP CQ index.
14496  *
14497  * The link attention and ELS ring attention events are handled
14498  * by the worker thread. The interrupt handler signals the worker thread
14499  * and returns for these events. This function is called without any lock
14500  * held. It gets the hbalock to access and update SLI data structures.
14501  *
14502  * This function returns IRQ_HANDLED when interrupt is handled else it
14503  * returns IRQ_NONE.
14504  **/
14505 irqreturn_t
14506 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
14507 {
14508 	struct lpfc_hba *phba;
14509 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
14510 	struct lpfc_queue *fpeq;
14511 	unsigned long iflag;
14512 	int ecount = 0;
14513 	int hba_eqidx;
14514 	struct lpfc_eq_intr_info *eqi;
14515 
14516 	/* Get the driver's phba structure from the dev_id */
14517 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
14518 	phba = hba_eq_hdl->phba;
14519 	hba_eqidx = hba_eq_hdl->idx;
14520 
14521 	if (unlikely(!phba))
14522 		return IRQ_NONE;
14523 	if (unlikely(!phba->sli4_hba.hdwq))
14524 		return IRQ_NONE;
14525 
14526 	/* Get to the EQ struct associated with this vector */
14527 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
14528 	if (unlikely(!fpeq))
14529 		return IRQ_NONE;
14530 
14531 	/* Check device state for handling interrupt */
14532 	if (unlikely(lpfc_intr_state_check(phba))) {
14533 		/* Check again for link_state with lock held */
14534 		spin_lock_irqsave(&phba->hbalock, iflag);
14535 		if (phba->link_state < LPFC_LINK_DOWN)
14536 			/* Flush, clear interrupt, and rearm the EQ */
14537 			lpfc_sli4_eqcq_flush(phba, fpeq);
14538 		spin_unlock_irqrestore(&phba->hbalock, iflag);
14539 		return IRQ_NONE;
14540 	}
14541 
14542 	eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
14543 	eqi->icnt++;
14544 
14545 	fpeq->last_cpu = raw_smp_processor_id();
14546 
14547 	if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
14548 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
14549 	    phba->cfg_auto_imax &&
14550 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
14551 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
14552 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
14553 
14554 	/* process and rearm the EQ */
14555 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
14556 
14557 	if (unlikely(ecount == 0)) {
14558 		fpeq->EQ_no_entry++;
14559 		if (phba->intr_type == MSIX)
14560 			/* MSI-X treated interrupt served as no EQ share INT */
14561 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14562 					"0358 MSI-X interrupt with no EQE\n");
14563 		else
14564 			/* Non MSI-X treated on interrupt as EQ share INT */
14565 			return IRQ_NONE;
14566 	}
14567 
14568 	return IRQ_HANDLED;
14569 } /* lpfc_sli4_fp_intr_handler */
14570 
14571 /**
14572  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
14573  * @irq: Interrupt number.
14574  * @dev_id: The device context pointer.
14575  *
14576  * This function is the device-level interrupt handler to device with SLI-4
14577  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
14578  * interrupt mode is enabled and there is an event in the HBA which requires
14579  * driver attention. This function invokes the slow-path interrupt attention
14580  * handling function and fast-path interrupt attention handling function in
14581  * turn to process the relevant HBA attention events. This function is called
14582  * without any lock held. It gets the hbalock to access and update SLI data
14583  * structures.
14584  *
14585  * This function returns IRQ_HANDLED when interrupt is handled, else it
14586  * returns IRQ_NONE.
14587  **/
14588 irqreturn_t
14589 lpfc_sli4_intr_handler(int irq, void *dev_id)
14590 {
14591 	struct lpfc_hba  *phba;
14592 	irqreturn_t hba_irq_rc;
14593 	bool hba_handled = false;
14594 	int qidx;
14595 
14596 	/* Get the driver's phba structure from the dev_id */
14597 	phba = (struct lpfc_hba *)dev_id;
14598 
14599 	if (unlikely(!phba))
14600 		return IRQ_NONE;
14601 
14602 	/*
14603 	 * Invoke fast-path host attention interrupt handling as appropriate.
14604 	 */
14605 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
14606 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
14607 					&phba->sli4_hba.hba_eq_hdl[qidx]);
14608 		if (hba_irq_rc == IRQ_HANDLED)
14609 			hba_handled |= true;
14610 	}
14611 
14612 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
14613 } /* lpfc_sli4_intr_handler */
14614 
14615 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
14616 {
14617 	struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
14618 	struct lpfc_queue *eq;
14619 	int i = 0;
14620 
14621 	rcu_read_lock();
14622 
14623 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
14624 		i += lpfc_sli4_poll_eq(eq, LPFC_POLL_SLOWPATH);
14625 	if (!list_empty(&phba->poll_list))
14626 		mod_timer(&phba->cpuhp_poll_timer,
14627 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
14628 
14629 	rcu_read_unlock();
14630 }
14631 
14632 inline int lpfc_sli4_poll_eq(struct lpfc_queue *eq, uint8_t path)
14633 {
14634 	struct lpfc_hba *phba = eq->phba;
14635 	int i = 0;
14636 
14637 	/*
14638 	 * Unlocking an irq is one of the entry point to check
14639 	 * for re-schedule, but we are good for io submission
14640 	 * path as midlayer does a get_cpu to glue us in. Flush
14641 	 * out the invalidate queue so we can see the updated
14642 	 * value for flag.
14643 	 */
14644 	smp_rmb();
14645 
14646 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
14647 		/* We will not likely get the completion for the caller
14648 		 * during this iteration but i guess that's fine.
14649 		 * Future io's coming on this eq should be able to
14650 		 * pick it up.  As for the case of single io's, they
14651 		 * will be handled through a sched from polling timer
14652 		 * function which is currently triggered every 1msec.
14653 		 */
14654 		i = lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM);
14655 
14656 	return i;
14657 }
14658 
14659 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
14660 {
14661 	struct lpfc_hba *phba = eq->phba;
14662 
14663 	/* kickstart slowpath processing if needed */
14664 	if (list_empty(&phba->poll_list))
14665 		mod_timer(&phba->cpuhp_poll_timer,
14666 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
14667 
14668 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
14669 	synchronize_rcu();
14670 }
14671 
14672 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
14673 {
14674 	struct lpfc_hba *phba = eq->phba;
14675 
14676 	/* Disable slowpath processing for this eq.  Kick start the eq
14677 	 * by RE-ARMING the eq's ASAP
14678 	 */
14679 	list_del_rcu(&eq->_poll_list);
14680 	synchronize_rcu();
14681 
14682 	if (list_empty(&phba->poll_list))
14683 		del_timer_sync(&phba->cpuhp_poll_timer);
14684 }
14685 
14686 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
14687 {
14688 	struct lpfc_queue *eq, *next;
14689 
14690 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
14691 		list_del(&eq->_poll_list);
14692 
14693 	INIT_LIST_HEAD(&phba->poll_list);
14694 	synchronize_rcu();
14695 }
14696 
14697 static inline void
14698 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
14699 {
14700 	if (mode == eq->mode)
14701 		return;
14702 	/*
14703 	 * currently this function is only called during a hotplug
14704 	 * event and the cpu on which this function is executing
14705 	 * is going offline.  By now the hotplug has instructed
14706 	 * the scheduler to remove this cpu from cpu active mask.
14707 	 * So we don't need to work about being put aside by the
14708 	 * scheduler for a high priority process.  Yes, the inte-
14709 	 * rrupts could come but they are known to retire ASAP.
14710 	 */
14711 
14712 	/* Disable polling in the fastpath */
14713 	WRITE_ONCE(eq->mode, mode);
14714 	/* flush out the store buffer */
14715 	smp_wmb();
14716 
14717 	/*
14718 	 * Add this eq to the polling list and start polling. For
14719 	 * a grace period both interrupt handler and poller will
14720 	 * try to process the eq _but_ that's fine.  We have a
14721 	 * synchronization mechanism in place (queue_claimed) to
14722 	 * deal with it.  This is just a draining phase for int-
14723 	 * errupt handler (not eq's) as we have guranteed through
14724 	 * barrier that all the CPUs have seen the new CQ_POLLED
14725 	 * state. which will effectively disable the REARMING of
14726 	 * the EQ.  The whole idea is eq's die off eventually as
14727 	 * we are not rearming EQ's anymore.
14728 	 */
14729 	mode ? lpfc_sli4_add_to_poll_list(eq) :
14730 	       lpfc_sli4_remove_from_poll_list(eq);
14731 }
14732 
14733 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
14734 {
14735 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
14736 }
14737 
14738 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
14739 {
14740 	struct lpfc_hba *phba = eq->phba;
14741 
14742 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
14743 
14744 	/* Kick start for the pending io's in h/w.
14745 	 * Once we switch back to interrupt processing on a eq
14746 	 * the io path completion will only arm eq's when it
14747 	 * receives a completion.  But since eq's are in disa-
14748 	 * rmed state it doesn't receive a completion.  This
14749 	 * creates a deadlock scenaro.
14750 	 */
14751 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
14752 }
14753 
14754 /**
14755  * lpfc_sli4_queue_free - free a queue structure and associated memory
14756  * @queue: The queue structure to free.
14757  *
14758  * This function frees a queue structure and the DMAable memory used for
14759  * the host resident queue. This function must be called after destroying the
14760  * queue on the HBA.
14761  **/
14762 void
14763 lpfc_sli4_queue_free(struct lpfc_queue *queue)
14764 {
14765 	struct lpfc_dmabuf *dmabuf;
14766 
14767 	if (!queue)
14768 		return;
14769 
14770 	if (!list_empty(&queue->wq_list))
14771 		list_del(&queue->wq_list);
14772 
14773 	while (!list_empty(&queue->page_list)) {
14774 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
14775 				 list);
14776 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
14777 				  dmabuf->virt, dmabuf->phys);
14778 		kfree(dmabuf);
14779 	}
14780 	if (queue->rqbp) {
14781 		lpfc_free_rq_buffer(queue->phba, queue);
14782 		kfree(queue->rqbp);
14783 	}
14784 
14785 	if (!list_empty(&queue->cpu_list))
14786 		list_del(&queue->cpu_list);
14787 
14788 	kfree(queue);
14789 	return;
14790 }
14791 
14792 /**
14793  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
14794  * @phba: The HBA that this queue is being created on.
14795  * @page_size: The size of a queue page
14796  * @entry_size: The size of each queue entry for this queue.
14797  * @entry_count: The number of entries that this queue will handle.
14798  * @cpu: The cpu that will primarily utilize this queue.
14799  *
14800  * This function allocates a queue structure and the DMAable memory used for
14801  * the host resident queue. This function must be called before creating the
14802  * queue on the HBA.
14803  **/
14804 struct lpfc_queue *
14805 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
14806 		      uint32_t entry_size, uint32_t entry_count, int cpu)
14807 {
14808 	struct lpfc_queue *queue;
14809 	struct lpfc_dmabuf *dmabuf;
14810 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14811 	uint16_t x, pgcnt;
14812 
14813 	if (!phba->sli4_hba.pc_sli4_params.supported)
14814 		hw_page_size = page_size;
14815 
14816 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
14817 
14818 	/* If needed, Adjust page count to match the max the adapter supports */
14819 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
14820 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
14821 
14822 	queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
14823 			     GFP_KERNEL, cpu_to_node(cpu));
14824 	if (!queue)
14825 		return NULL;
14826 
14827 	INIT_LIST_HEAD(&queue->list);
14828 	INIT_LIST_HEAD(&queue->_poll_list);
14829 	INIT_LIST_HEAD(&queue->wq_list);
14830 	INIT_LIST_HEAD(&queue->wqfull_list);
14831 	INIT_LIST_HEAD(&queue->page_list);
14832 	INIT_LIST_HEAD(&queue->child_list);
14833 	INIT_LIST_HEAD(&queue->cpu_list);
14834 
14835 	/* Set queue parameters now.  If the system cannot provide memory
14836 	 * resources, the free routine needs to know what was allocated.
14837 	 */
14838 	queue->page_count = pgcnt;
14839 	queue->q_pgs = (void **)&queue[1];
14840 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
14841 	queue->entry_size = entry_size;
14842 	queue->entry_count = entry_count;
14843 	queue->page_size = hw_page_size;
14844 	queue->phba = phba;
14845 
14846 	for (x = 0; x < queue->page_count; x++) {
14847 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
14848 				      dev_to_node(&phba->pcidev->dev));
14849 		if (!dmabuf)
14850 			goto out_fail;
14851 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14852 						  hw_page_size, &dmabuf->phys,
14853 						  GFP_KERNEL);
14854 		if (!dmabuf->virt) {
14855 			kfree(dmabuf);
14856 			goto out_fail;
14857 		}
14858 		dmabuf->buffer_tag = x;
14859 		list_add_tail(&dmabuf->list, &queue->page_list);
14860 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
14861 		queue->q_pgs[x] = dmabuf->virt;
14862 	}
14863 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
14864 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
14865 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
14866 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
14867 
14868 	/* notify_interval will be set during q creation */
14869 
14870 	return queue;
14871 out_fail:
14872 	lpfc_sli4_queue_free(queue);
14873 	return NULL;
14874 }
14875 
14876 /**
14877  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
14878  * @phba: HBA structure that indicates port to create a queue on.
14879  * @pci_barset: PCI BAR set flag.
14880  *
14881  * This function shall perform iomap of the specified PCI BAR address to host
14882  * memory address if not already done so and return it. The returned host
14883  * memory address can be NULL.
14884  */
14885 static void __iomem *
14886 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
14887 {
14888 	if (!phba->pcidev)
14889 		return NULL;
14890 
14891 	switch (pci_barset) {
14892 	case WQ_PCI_BAR_0_AND_1:
14893 		return phba->pci_bar0_memmap_p;
14894 	case WQ_PCI_BAR_2_AND_3:
14895 		return phba->pci_bar2_memmap_p;
14896 	case WQ_PCI_BAR_4_AND_5:
14897 		return phba->pci_bar4_memmap_p;
14898 	default:
14899 		break;
14900 	}
14901 	return NULL;
14902 }
14903 
14904 /**
14905  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
14906  * @phba: HBA structure that EQs are on.
14907  * @startq: The starting EQ index to modify
14908  * @numq: The number of EQs (consecutive indexes) to modify
14909  * @usdelay: amount of delay
14910  *
14911  * This function revises the EQ delay on 1 or more EQs. The EQ delay
14912  * is set either by writing to a register (if supported by the SLI Port)
14913  * or by mailbox command. The mailbox command allows several EQs to be
14914  * updated at once.
14915  *
14916  * The @phba struct is used to send a mailbox command to HBA. The @startq
14917  * is used to get the starting EQ index to change. The @numq value is
14918  * used to specify how many consecutive EQ indexes, starting at EQ index,
14919  * are to be changed. This function is asynchronous and will wait for any
14920  * mailbox commands to finish before returning.
14921  *
14922  * On success this function will return a zero. If unable to allocate
14923  * enough memory this function will return -ENOMEM. If a mailbox command
14924  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
14925  * have had their delay multipler changed.
14926  **/
14927 void
14928 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
14929 			 uint32_t numq, uint32_t usdelay)
14930 {
14931 	struct lpfc_mbx_modify_eq_delay *eq_delay;
14932 	LPFC_MBOXQ_t *mbox;
14933 	struct lpfc_queue *eq;
14934 	int cnt = 0, rc, length;
14935 	uint32_t shdr_status, shdr_add_status;
14936 	uint32_t dmult;
14937 	int qidx;
14938 	union lpfc_sli4_cfg_shdr *shdr;
14939 
14940 	if (startq >= phba->cfg_irq_chann)
14941 		return;
14942 
14943 	if (usdelay > 0xFFFF) {
14944 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
14945 				"6429 usdelay %d too large. Scaled down to "
14946 				"0xFFFF.\n", usdelay);
14947 		usdelay = 0xFFFF;
14948 	}
14949 
14950 	/* set values by EQ_DELAY register if supported */
14951 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
14952 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
14953 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
14954 			if (!eq)
14955 				continue;
14956 
14957 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
14958 
14959 			if (++cnt >= numq)
14960 				break;
14961 		}
14962 		return;
14963 	}
14964 
14965 	/* Otherwise, set values by mailbox cmd */
14966 
14967 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14968 	if (!mbox) {
14969 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14970 				"6428 Failed allocating mailbox cmd buffer."
14971 				" EQ delay was not set.\n");
14972 		return;
14973 	}
14974 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
14975 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14976 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14977 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
14978 			 length, LPFC_SLI4_MBX_EMBED);
14979 	eq_delay = &mbox->u.mqe.un.eq_delay;
14980 
14981 	/* Calculate delay multiper from maximum interrupt per second */
14982 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
14983 	if (dmult)
14984 		dmult--;
14985 	if (dmult > LPFC_DMULT_MAX)
14986 		dmult = LPFC_DMULT_MAX;
14987 
14988 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
14989 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
14990 		if (!eq)
14991 			continue;
14992 		eq->q_mode = usdelay;
14993 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
14994 		eq_delay->u.request.eq[cnt].phase = 0;
14995 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
14996 
14997 		if (++cnt >= numq)
14998 			break;
14999 	}
15000 	eq_delay->u.request.num_eq = cnt;
15001 
15002 	mbox->vport = phba->pport;
15003 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15004 	mbox->ctx_buf = NULL;
15005 	mbox->ctx_ndlp = NULL;
15006 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15007 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
15008 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15009 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15010 	if (shdr_status || shdr_add_status || rc) {
15011 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15012 				"2512 MODIFY_EQ_DELAY mailbox failed with "
15013 				"status x%x add_status x%x, mbx status x%x\n",
15014 				shdr_status, shdr_add_status, rc);
15015 	}
15016 	mempool_free(mbox, phba->mbox_mem_pool);
15017 	return;
15018 }
15019 
15020 /**
15021  * lpfc_eq_create - Create an Event Queue on the HBA
15022  * @phba: HBA structure that indicates port to create a queue on.
15023  * @eq: The queue structure to use to create the event queue.
15024  * @imax: The maximum interrupt per second limit.
15025  *
15026  * This function creates an event queue, as detailed in @eq, on a port,
15027  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
15028  *
15029  * The @phba struct is used to send mailbox command to HBA. The @eq struct
15030  * is used to get the entry count and entry size that are necessary to
15031  * determine the number of pages to allocate and use for this queue. This
15032  * function will send the EQ_CREATE mailbox command to the HBA to setup the
15033  * event queue. This function is asynchronous and will wait for the mailbox
15034  * command to finish before continuing.
15035  *
15036  * On success this function will return a zero. If unable to allocate enough
15037  * memory this function will return -ENOMEM. If the queue create mailbox command
15038  * fails this function will return -ENXIO.
15039  **/
15040 int
15041 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
15042 {
15043 	struct lpfc_mbx_eq_create *eq_create;
15044 	LPFC_MBOXQ_t *mbox;
15045 	int rc, length, status = 0;
15046 	struct lpfc_dmabuf *dmabuf;
15047 	uint32_t shdr_status, shdr_add_status;
15048 	union lpfc_sli4_cfg_shdr *shdr;
15049 	uint16_t dmult;
15050 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15051 
15052 	/* sanity check on queue memory */
15053 	if (!eq)
15054 		return -ENODEV;
15055 	if (!phba->sli4_hba.pc_sli4_params.supported)
15056 		hw_page_size = SLI4_PAGE_SIZE;
15057 
15058 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15059 	if (!mbox)
15060 		return -ENOMEM;
15061 	length = (sizeof(struct lpfc_mbx_eq_create) -
15062 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15063 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15064 			 LPFC_MBOX_OPCODE_EQ_CREATE,
15065 			 length, LPFC_SLI4_MBX_EMBED);
15066 	eq_create = &mbox->u.mqe.un.eq_create;
15067 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
15068 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
15069 	       eq->page_count);
15070 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
15071 	       LPFC_EQE_SIZE);
15072 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
15073 
15074 	/* Use version 2 of CREATE_EQ if eqav is set */
15075 	if (phba->sli4_hba.pc_sli4_params.eqav) {
15076 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
15077 		       LPFC_Q_CREATE_VERSION_2);
15078 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
15079 		       phba->sli4_hba.pc_sli4_params.eqav);
15080 	}
15081 
15082 	/* don't setup delay multiplier using EQ_CREATE */
15083 	dmult = 0;
15084 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
15085 	       dmult);
15086 	switch (eq->entry_count) {
15087 	default:
15088 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15089 				"0360 Unsupported EQ count. (%d)\n",
15090 				eq->entry_count);
15091 		if (eq->entry_count < 256) {
15092 			status = -EINVAL;
15093 			goto out;
15094 		}
15095 		/* fall through - otherwise default to smallest count */
15096 	case 256:
15097 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15098 		       LPFC_EQ_CNT_256);
15099 		break;
15100 	case 512:
15101 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15102 		       LPFC_EQ_CNT_512);
15103 		break;
15104 	case 1024:
15105 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15106 		       LPFC_EQ_CNT_1024);
15107 		break;
15108 	case 2048:
15109 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15110 		       LPFC_EQ_CNT_2048);
15111 		break;
15112 	case 4096:
15113 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15114 		       LPFC_EQ_CNT_4096);
15115 		break;
15116 	}
15117 	list_for_each_entry(dmabuf, &eq->page_list, list) {
15118 		memset(dmabuf->virt, 0, hw_page_size);
15119 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15120 					putPaddrLow(dmabuf->phys);
15121 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15122 					putPaddrHigh(dmabuf->phys);
15123 	}
15124 	mbox->vport = phba->pport;
15125 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15126 	mbox->ctx_buf = NULL;
15127 	mbox->ctx_ndlp = NULL;
15128 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15129 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15130 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15131 	if (shdr_status || shdr_add_status || rc) {
15132 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15133 				"2500 EQ_CREATE mailbox failed with "
15134 				"status x%x add_status x%x, mbx status x%x\n",
15135 				shdr_status, shdr_add_status, rc);
15136 		status = -ENXIO;
15137 	}
15138 	eq->type = LPFC_EQ;
15139 	eq->subtype = LPFC_NONE;
15140 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
15141 	if (eq->queue_id == 0xFFFF)
15142 		status = -ENXIO;
15143 	eq->host_index = 0;
15144 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
15145 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
15146 out:
15147 	mempool_free(mbox, phba->mbox_mem_pool);
15148 	return status;
15149 }
15150 
15151 static int lpfc_cq_poll_hdler(struct irq_poll *iop, int budget)
15152 {
15153 	struct lpfc_queue *cq = container_of(iop, struct lpfc_queue, iop);
15154 
15155 	__lpfc_sli4_hba_process_cq(cq, LPFC_IRQ_POLL);
15156 
15157 	return 1;
15158 }
15159 
15160 /**
15161  * lpfc_cq_create - Create a Completion Queue on the HBA
15162  * @phba: HBA structure that indicates port to create a queue on.
15163  * @cq: The queue structure to use to create the completion queue.
15164  * @eq: The event queue to bind this completion queue to.
15165  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
15166  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
15167  *
15168  * This function creates a completion queue, as detailed in @wq, on a port,
15169  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
15170  *
15171  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15172  * is used to get the entry count and entry size that are necessary to
15173  * determine the number of pages to allocate and use for this queue. The @eq
15174  * is used to indicate which event queue to bind this completion queue to. This
15175  * function will send the CQ_CREATE mailbox command to the HBA to setup the
15176  * completion queue. This function is asynchronous and will wait for the mailbox
15177  * command to finish before continuing.
15178  *
15179  * On success this function will return a zero. If unable to allocate enough
15180  * memory this function will return -ENOMEM. If the queue create mailbox command
15181  * fails this function will return -ENXIO.
15182  **/
15183 int
15184 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
15185 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
15186 {
15187 	struct lpfc_mbx_cq_create *cq_create;
15188 	struct lpfc_dmabuf *dmabuf;
15189 	LPFC_MBOXQ_t *mbox;
15190 	int rc, length, status = 0;
15191 	uint32_t shdr_status, shdr_add_status;
15192 	union lpfc_sli4_cfg_shdr *shdr;
15193 
15194 	/* sanity check on queue memory */
15195 	if (!cq || !eq)
15196 		return -ENODEV;
15197 
15198 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15199 	if (!mbox)
15200 		return -ENOMEM;
15201 	length = (sizeof(struct lpfc_mbx_cq_create) -
15202 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15203 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15204 			 LPFC_MBOX_OPCODE_CQ_CREATE,
15205 			 length, LPFC_SLI4_MBX_EMBED);
15206 	cq_create = &mbox->u.mqe.un.cq_create;
15207 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
15208 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
15209 		    cq->page_count);
15210 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
15211 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
15212 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15213 	       phba->sli4_hba.pc_sli4_params.cqv);
15214 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
15215 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
15216 		       (cq->page_size / SLI4_PAGE_SIZE));
15217 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
15218 		       eq->queue_id);
15219 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
15220 		       phba->sli4_hba.pc_sli4_params.cqav);
15221 	} else {
15222 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
15223 		       eq->queue_id);
15224 	}
15225 	switch (cq->entry_count) {
15226 	case 2048:
15227 	case 4096:
15228 		if (phba->sli4_hba.pc_sli4_params.cqv ==
15229 		    LPFC_Q_CREATE_VERSION_2) {
15230 			cq_create->u.request.context.lpfc_cq_context_count =
15231 				cq->entry_count;
15232 			bf_set(lpfc_cq_context_count,
15233 			       &cq_create->u.request.context,
15234 			       LPFC_CQ_CNT_WORD7);
15235 			break;
15236 		}
15237 		/* fall through */
15238 	default:
15239 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15240 				"0361 Unsupported CQ count: "
15241 				"entry cnt %d sz %d pg cnt %d\n",
15242 				cq->entry_count, cq->entry_size,
15243 				cq->page_count);
15244 		if (cq->entry_count < 256) {
15245 			status = -EINVAL;
15246 			goto out;
15247 		}
15248 		/* fall through - otherwise default to smallest count */
15249 	case 256:
15250 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15251 		       LPFC_CQ_CNT_256);
15252 		break;
15253 	case 512:
15254 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15255 		       LPFC_CQ_CNT_512);
15256 		break;
15257 	case 1024:
15258 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15259 		       LPFC_CQ_CNT_1024);
15260 		break;
15261 	}
15262 	list_for_each_entry(dmabuf, &cq->page_list, list) {
15263 		memset(dmabuf->virt, 0, cq->page_size);
15264 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15265 					putPaddrLow(dmabuf->phys);
15266 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15267 					putPaddrHigh(dmabuf->phys);
15268 	}
15269 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15270 
15271 	/* The IOCTL status is embedded in the mailbox subheader. */
15272 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15273 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15274 	if (shdr_status || shdr_add_status || rc) {
15275 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15276 				"2501 CQ_CREATE mailbox failed with "
15277 				"status x%x add_status x%x, mbx status x%x\n",
15278 				shdr_status, shdr_add_status, rc);
15279 		status = -ENXIO;
15280 		goto out;
15281 	}
15282 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15283 	if (cq->queue_id == 0xFFFF) {
15284 		status = -ENXIO;
15285 		goto out;
15286 	}
15287 	/* link the cq onto the parent eq child list */
15288 	list_add_tail(&cq->list, &eq->child_list);
15289 	/* Set up completion queue's type and subtype */
15290 	cq->type = type;
15291 	cq->subtype = subtype;
15292 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15293 	cq->assoc_qid = eq->queue_id;
15294 	cq->assoc_qp = eq;
15295 	cq->host_index = 0;
15296 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15297 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
15298 
15299 	if (cq->queue_id > phba->sli4_hba.cq_max)
15300 		phba->sli4_hba.cq_max = cq->queue_id;
15301 
15302 	irq_poll_init(&cq->iop, LPFC_IRQ_POLL_WEIGHT, lpfc_cq_poll_hdler);
15303 out:
15304 	mempool_free(mbox, phba->mbox_mem_pool);
15305 	return status;
15306 }
15307 
15308 /**
15309  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
15310  * @phba: HBA structure that indicates port to create a queue on.
15311  * @cqp: The queue structure array to use to create the completion queues.
15312  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
15313  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
15314  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
15315  *
15316  * This function creates a set of  completion queue, s to support MRQ
15317  * as detailed in @cqp, on a port,
15318  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
15319  *
15320  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15321  * is used to get the entry count and entry size that are necessary to
15322  * determine the number of pages to allocate and use for this queue. The @eq
15323  * is used to indicate which event queue to bind this completion queue to. This
15324  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
15325  * completion queue. This function is asynchronous and will wait for the mailbox
15326  * command to finish before continuing.
15327  *
15328  * On success this function will return a zero. If unable to allocate enough
15329  * memory this function will return -ENOMEM. If the queue create mailbox command
15330  * fails this function will return -ENXIO.
15331  **/
15332 int
15333 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
15334 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
15335 		   uint32_t subtype)
15336 {
15337 	struct lpfc_queue *cq;
15338 	struct lpfc_queue *eq;
15339 	struct lpfc_mbx_cq_create_set *cq_set;
15340 	struct lpfc_dmabuf *dmabuf;
15341 	LPFC_MBOXQ_t *mbox;
15342 	int rc, length, alloclen, status = 0;
15343 	int cnt, idx, numcq, page_idx = 0;
15344 	uint32_t shdr_status, shdr_add_status;
15345 	union lpfc_sli4_cfg_shdr *shdr;
15346 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15347 
15348 	/* sanity check on queue memory */
15349 	numcq = phba->cfg_nvmet_mrq;
15350 	if (!cqp || !hdwq || !numcq)
15351 		return -ENODEV;
15352 
15353 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15354 	if (!mbox)
15355 		return -ENOMEM;
15356 
15357 	length = sizeof(struct lpfc_mbx_cq_create_set);
15358 	length += ((numcq * cqp[0]->page_count) *
15359 		   sizeof(struct dma_address));
15360 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15361 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
15362 			LPFC_SLI4_MBX_NEMBED);
15363 	if (alloclen < length) {
15364 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15365 				"3098 Allocated DMA memory size (%d) is "
15366 				"less than the requested DMA memory size "
15367 				"(%d)\n", alloclen, length);
15368 		status = -ENOMEM;
15369 		goto out;
15370 	}
15371 	cq_set = mbox->sge_array->addr[0];
15372 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
15373 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
15374 
15375 	for (idx = 0; idx < numcq; idx++) {
15376 		cq = cqp[idx];
15377 		eq = hdwq[idx].hba_eq;
15378 		if (!cq || !eq) {
15379 			status = -ENOMEM;
15380 			goto out;
15381 		}
15382 		if (!phba->sli4_hba.pc_sli4_params.supported)
15383 			hw_page_size = cq->page_size;
15384 
15385 		switch (idx) {
15386 		case 0:
15387 			bf_set(lpfc_mbx_cq_create_set_page_size,
15388 			       &cq_set->u.request,
15389 			       (hw_page_size / SLI4_PAGE_SIZE));
15390 			bf_set(lpfc_mbx_cq_create_set_num_pages,
15391 			       &cq_set->u.request, cq->page_count);
15392 			bf_set(lpfc_mbx_cq_create_set_evt,
15393 			       &cq_set->u.request, 1);
15394 			bf_set(lpfc_mbx_cq_create_set_valid,
15395 			       &cq_set->u.request, 1);
15396 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
15397 			       &cq_set->u.request, 0);
15398 			bf_set(lpfc_mbx_cq_create_set_num_cq,
15399 			       &cq_set->u.request, numcq);
15400 			bf_set(lpfc_mbx_cq_create_set_autovalid,
15401 			       &cq_set->u.request,
15402 			       phba->sli4_hba.pc_sli4_params.cqav);
15403 			switch (cq->entry_count) {
15404 			case 2048:
15405 			case 4096:
15406 				if (phba->sli4_hba.pc_sli4_params.cqv ==
15407 				    LPFC_Q_CREATE_VERSION_2) {
15408 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15409 					       &cq_set->u.request,
15410 						cq->entry_count);
15411 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15412 					       &cq_set->u.request,
15413 					       LPFC_CQ_CNT_WORD7);
15414 					break;
15415 				}
15416 				/* fall through */
15417 			default:
15418 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15419 						"3118 Bad CQ count. (%d)\n",
15420 						cq->entry_count);
15421 				if (cq->entry_count < 256) {
15422 					status = -EINVAL;
15423 					goto out;
15424 				}
15425 				/* fall through - otherwise default to smallest */
15426 			case 256:
15427 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15428 				       &cq_set->u.request, LPFC_CQ_CNT_256);
15429 				break;
15430 			case 512:
15431 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15432 				       &cq_set->u.request, LPFC_CQ_CNT_512);
15433 				break;
15434 			case 1024:
15435 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15436 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
15437 				break;
15438 			}
15439 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
15440 			       &cq_set->u.request, eq->queue_id);
15441 			break;
15442 		case 1:
15443 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
15444 			       &cq_set->u.request, eq->queue_id);
15445 			break;
15446 		case 2:
15447 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
15448 			       &cq_set->u.request, eq->queue_id);
15449 			break;
15450 		case 3:
15451 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
15452 			       &cq_set->u.request, eq->queue_id);
15453 			break;
15454 		case 4:
15455 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
15456 			       &cq_set->u.request, eq->queue_id);
15457 			break;
15458 		case 5:
15459 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
15460 			       &cq_set->u.request, eq->queue_id);
15461 			break;
15462 		case 6:
15463 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
15464 			       &cq_set->u.request, eq->queue_id);
15465 			break;
15466 		case 7:
15467 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
15468 			       &cq_set->u.request, eq->queue_id);
15469 			break;
15470 		case 8:
15471 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
15472 			       &cq_set->u.request, eq->queue_id);
15473 			break;
15474 		case 9:
15475 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
15476 			       &cq_set->u.request, eq->queue_id);
15477 			break;
15478 		case 10:
15479 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
15480 			       &cq_set->u.request, eq->queue_id);
15481 			break;
15482 		case 11:
15483 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
15484 			       &cq_set->u.request, eq->queue_id);
15485 			break;
15486 		case 12:
15487 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
15488 			       &cq_set->u.request, eq->queue_id);
15489 			break;
15490 		case 13:
15491 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
15492 			       &cq_set->u.request, eq->queue_id);
15493 			break;
15494 		case 14:
15495 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
15496 			       &cq_set->u.request, eq->queue_id);
15497 			break;
15498 		case 15:
15499 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
15500 			       &cq_set->u.request, eq->queue_id);
15501 			break;
15502 		}
15503 
15504 		/* link the cq onto the parent eq child list */
15505 		list_add_tail(&cq->list, &eq->child_list);
15506 		/* Set up completion queue's type and subtype */
15507 		cq->type = type;
15508 		cq->subtype = subtype;
15509 		cq->assoc_qid = eq->queue_id;
15510 		cq->assoc_qp = eq;
15511 		cq->host_index = 0;
15512 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15513 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
15514 					 cq->entry_count);
15515 		cq->chann = idx;
15516 
15517 		rc = 0;
15518 		list_for_each_entry(dmabuf, &cq->page_list, list) {
15519 			memset(dmabuf->virt, 0, hw_page_size);
15520 			cnt = page_idx + dmabuf->buffer_tag;
15521 			cq_set->u.request.page[cnt].addr_lo =
15522 					putPaddrLow(dmabuf->phys);
15523 			cq_set->u.request.page[cnt].addr_hi =
15524 					putPaddrHigh(dmabuf->phys);
15525 			rc++;
15526 		}
15527 		page_idx += rc;
15528 	}
15529 
15530 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15531 
15532 	/* The IOCTL status is embedded in the mailbox subheader. */
15533 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15534 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15535 	if (shdr_status || shdr_add_status || rc) {
15536 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15537 				"3119 CQ_CREATE_SET mailbox failed with "
15538 				"status x%x add_status x%x, mbx status x%x\n",
15539 				shdr_status, shdr_add_status, rc);
15540 		status = -ENXIO;
15541 		goto out;
15542 	}
15543 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
15544 	if (rc == 0xFFFF) {
15545 		status = -ENXIO;
15546 		goto out;
15547 	}
15548 
15549 	for (idx = 0; idx < numcq; idx++) {
15550 		cq = cqp[idx];
15551 		cq->queue_id = rc + idx;
15552 		if (cq->queue_id > phba->sli4_hba.cq_max)
15553 			phba->sli4_hba.cq_max = cq->queue_id;
15554 	}
15555 
15556 out:
15557 	lpfc_sli4_mbox_cmd_free(phba, mbox);
15558 	return status;
15559 }
15560 
15561 /**
15562  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
15563  * @phba: HBA structure that indicates port to create a queue on.
15564  * @mq: The queue structure to use to create the mailbox queue.
15565  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
15566  * @cq: The completion queue to associate with this cq.
15567  *
15568  * This function provides failback (fb) functionality when the
15569  * mq_create_ext fails on older FW generations.  It's purpose is identical
15570  * to mq_create_ext otherwise.
15571  *
15572  * This routine cannot fail as all attributes were previously accessed and
15573  * initialized in mq_create_ext.
15574  **/
15575 static void
15576 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
15577 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
15578 {
15579 	struct lpfc_mbx_mq_create *mq_create;
15580 	struct lpfc_dmabuf *dmabuf;
15581 	int length;
15582 
15583 	length = (sizeof(struct lpfc_mbx_mq_create) -
15584 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15585 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15586 			 LPFC_MBOX_OPCODE_MQ_CREATE,
15587 			 length, LPFC_SLI4_MBX_EMBED);
15588 	mq_create = &mbox->u.mqe.un.mq_create;
15589 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
15590 	       mq->page_count);
15591 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
15592 	       cq->queue_id);
15593 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
15594 	switch (mq->entry_count) {
15595 	case 16:
15596 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15597 		       LPFC_MQ_RING_SIZE_16);
15598 		break;
15599 	case 32:
15600 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15601 		       LPFC_MQ_RING_SIZE_32);
15602 		break;
15603 	case 64:
15604 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15605 		       LPFC_MQ_RING_SIZE_64);
15606 		break;
15607 	case 128:
15608 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15609 		       LPFC_MQ_RING_SIZE_128);
15610 		break;
15611 	}
15612 	list_for_each_entry(dmabuf, &mq->page_list, list) {
15613 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15614 			putPaddrLow(dmabuf->phys);
15615 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15616 			putPaddrHigh(dmabuf->phys);
15617 	}
15618 }
15619 
15620 /**
15621  * lpfc_mq_create - Create a mailbox Queue on the HBA
15622  * @phba: HBA structure that indicates port to create a queue on.
15623  * @mq: The queue structure to use to create the mailbox queue.
15624  * @cq: The completion queue to associate with this cq.
15625  * @subtype: The queue's subtype.
15626  *
15627  * This function creates a mailbox queue, as detailed in @mq, on a port,
15628  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
15629  *
15630  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15631  * is used to get the entry count and entry size that are necessary to
15632  * determine the number of pages to allocate and use for this queue. This
15633  * function will send the MQ_CREATE mailbox command to the HBA to setup the
15634  * mailbox queue. This function is asynchronous and will wait for the mailbox
15635  * command to finish before continuing.
15636  *
15637  * On success this function will return a zero. If unable to allocate enough
15638  * memory this function will return -ENOMEM. If the queue create mailbox command
15639  * fails this function will return -ENXIO.
15640  **/
15641 int32_t
15642 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
15643 	       struct lpfc_queue *cq, uint32_t subtype)
15644 {
15645 	struct lpfc_mbx_mq_create *mq_create;
15646 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
15647 	struct lpfc_dmabuf *dmabuf;
15648 	LPFC_MBOXQ_t *mbox;
15649 	int rc, length, status = 0;
15650 	uint32_t shdr_status, shdr_add_status;
15651 	union lpfc_sli4_cfg_shdr *shdr;
15652 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15653 
15654 	/* sanity check on queue memory */
15655 	if (!mq || !cq)
15656 		return -ENODEV;
15657 	if (!phba->sli4_hba.pc_sli4_params.supported)
15658 		hw_page_size = SLI4_PAGE_SIZE;
15659 
15660 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15661 	if (!mbox)
15662 		return -ENOMEM;
15663 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
15664 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15665 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15666 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
15667 			 length, LPFC_SLI4_MBX_EMBED);
15668 
15669 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
15670 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
15671 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
15672 	       &mq_create_ext->u.request, mq->page_count);
15673 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
15674 	       &mq_create_ext->u.request, 1);
15675 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
15676 	       &mq_create_ext->u.request, 1);
15677 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
15678 	       &mq_create_ext->u.request, 1);
15679 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
15680 	       &mq_create_ext->u.request, 1);
15681 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
15682 	       &mq_create_ext->u.request, 1);
15683 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
15684 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15685 	       phba->sli4_hba.pc_sli4_params.mqv);
15686 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
15687 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
15688 		       cq->queue_id);
15689 	else
15690 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
15691 		       cq->queue_id);
15692 	switch (mq->entry_count) {
15693 	default:
15694 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15695 				"0362 Unsupported MQ count. (%d)\n",
15696 				mq->entry_count);
15697 		if (mq->entry_count < 16) {
15698 			status = -EINVAL;
15699 			goto out;
15700 		}
15701 		/* fall through - otherwise default to smallest count */
15702 	case 16:
15703 		bf_set(lpfc_mq_context_ring_size,
15704 		       &mq_create_ext->u.request.context,
15705 		       LPFC_MQ_RING_SIZE_16);
15706 		break;
15707 	case 32:
15708 		bf_set(lpfc_mq_context_ring_size,
15709 		       &mq_create_ext->u.request.context,
15710 		       LPFC_MQ_RING_SIZE_32);
15711 		break;
15712 	case 64:
15713 		bf_set(lpfc_mq_context_ring_size,
15714 		       &mq_create_ext->u.request.context,
15715 		       LPFC_MQ_RING_SIZE_64);
15716 		break;
15717 	case 128:
15718 		bf_set(lpfc_mq_context_ring_size,
15719 		       &mq_create_ext->u.request.context,
15720 		       LPFC_MQ_RING_SIZE_128);
15721 		break;
15722 	}
15723 	list_for_each_entry(dmabuf, &mq->page_list, list) {
15724 		memset(dmabuf->virt, 0, hw_page_size);
15725 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
15726 					putPaddrLow(dmabuf->phys);
15727 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
15728 					putPaddrHigh(dmabuf->phys);
15729 	}
15730 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15731 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
15732 			      &mq_create_ext->u.response);
15733 	if (rc != MBX_SUCCESS) {
15734 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15735 				"2795 MQ_CREATE_EXT failed with "
15736 				"status x%x. Failback to MQ_CREATE.\n",
15737 				rc);
15738 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
15739 		mq_create = &mbox->u.mqe.un.mq_create;
15740 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15741 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
15742 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
15743 				      &mq_create->u.response);
15744 	}
15745 
15746 	/* The IOCTL status is embedded in the mailbox subheader. */
15747 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15748 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15749 	if (shdr_status || shdr_add_status || rc) {
15750 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15751 				"2502 MQ_CREATE mailbox failed with "
15752 				"status x%x add_status x%x, mbx status x%x\n",
15753 				shdr_status, shdr_add_status, rc);
15754 		status = -ENXIO;
15755 		goto out;
15756 	}
15757 	if (mq->queue_id == 0xFFFF) {
15758 		status = -ENXIO;
15759 		goto out;
15760 	}
15761 	mq->type = LPFC_MQ;
15762 	mq->assoc_qid = cq->queue_id;
15763 	mq->subtype = subtype;
15764 	mq->host_index = 0;
15765 	mq->hba_index = 0;
15766 
15767 	/* link the mq onto the parent cq child list */
15768 	list_add_tail(&mq->list, &cq->child_list);
15769 out:
15770 	mempool_free(mbox, phba->mbox_mem_pool);
15771 	return status;
15772 }
15773 
15774 /**
15775  * lpfc_wq_create - Create a Work Queue on the HBA
15776  * @phba: HBA structure that indicates port to create a queue on.
15777  * @wq: The queue structure to use to create the work queue.
15778  * @cq: The completion queue to bind this work queue to.
15779  * @subtype: The subtype of the work queue indicating its functionality.
15780  *
15781  * This function creates a work queue, as detailed in @wq, on a port, described
15782  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
15783  *
15784  * The @phba struct is used to send mailbox command to HBA. The @wq struct
15785  * is used to get the entry count and entry size that are necessary to
15786  * determine the number of pages to allocate and use for this queue. The @cq
15787  * is used to indicate which completion queue to bind this work queue to. This
15788  * function will send the WQ_CREATE mailbox command to the HBA to setup the
15789  * work queue. This function is asynchronous and will wait for the mailbox
15790  * command to finish before continuing.
15791  *
15792  * On success this function will return a zero. If unable to allocate enough
15793  * memory this function will return -ENOMEM. If the queue create mailbox command
15794  * fails this function will return -ENXIO.
15795  **/
15796 int
15797 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
15798 	       struct lpfc_queue *cq, uint32_t subtype)
15799 {
15800 	struct lpfc_mbx_wq_create *wq_create;
15801 	struct lpfc_dmabuf *dmabuf;
15802 	LPFC_MBOXQ_t *mbox;
15803 	int rc, length, status = 0;
15804 	uint32_t shdr_status, shdr_add_status;
15805 	union lpfc_sli4_cfg_shdr *shdr;
15806 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15807 	struct dma_address *page;
15808 	void __iomem *bar_memmap_p;
15809 	uint32_t db_offset;
15810 	uint16_t pci_barset;
15811 	uint8_t dpp_barset;
15812 	uint32_t dpp_offset;
15813 	uint8_t wq_create_version;
15814 #ifdef CONFIG_X86
15815 	unsigned long pg_addr;
15816 #endif
15817 
15818 	/* sanity check on queue memory */
15819 	if (!wq || !cq)
15820 		return -ENODEV;
15821 	if (!phba->sli4_hba.pc_sli4_params.supported)
15822 		hw_page_size = wq->page_size;
15823 
15824 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15825 	if (!mbox)
15826 		return -ENOMEM;
15827 	length = (sizeof(struct lpfc_mbx_wq_create) -
15828 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15829 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15830 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
15831 			 length, LPFC_SLI4_MBX_EMBED);
15832 	wq_create = &mbox->u.mqe.un.wq_create;
15833 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
15834 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
15835 		    wq->page_count);
15836 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
15837 		    cq->queue_id);
15838 
15839 	/* wqv is the earliest version supported, NOT the latest */
15840 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15841 	       phba->sli4_hba.pc_sli4_params.wqv);
15842 
15843 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
15844 	    (wq->page_size > SLI4_PAGE_SIZE))
15845 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
15846 	else
15847 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
15848 
15849 
15850 	if (phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT)
15851 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
15852 	else
15853 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
15854 
15855 	switch (wq_create_version) {
15856 	case LPFC_Q_CREATE_VERSION_1:
15857 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
15858 		       wq->entry_count);
15859 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
15860 		       LPFC_Q_CREATE_VERSION_1);
15861 
15862 		switch (wq->entry_size) {
15863 		default:
15864 		case 64:
15865 			bf_set(lpfc_mbx_wq_create_wqe_size,
15866 			       &wq_create->u.request_1,
15867 			       LPFC_WQ_WQE_SIZE_64);
15868 			break;
15869 		case 128:
15870 			bf_set(lpfc_mbx_wq_create_wqe_size,
15871 			       &wq_create->u.request_1,
15872 			       LPFC_WQ_WQE_SIZE_128);
15873 			break;
15874 		}
15875 		/* Request DPP by default */
15876 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
15877 		bf_set(lpfc_mbx_wq_create_page_size,
15878 		       &wq_create->u.request_1,
15879 		       (wq->page_size / SLI4_PAGE_SIZE));
15880 		page = wq_create->u.request_1.page;
15881 		break;
15882 	default:
15883 		page = wq_create->u.request.page;
15884 		break;
15885 	}
15886 
15887 	list_for_each_entry(dmabuf, &wq->page_list, list) {
15888 		memset(dmabuf->virt, 0, hw_page_size);
15889 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
15890 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
15891 	}
15892 
15893 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
15894 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
15895 
15896 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15897 	/* The IOCTL status is embedded in the mailbox subheader. */
15898 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15899 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15900 	if (shdr_status || shdr_add_status || rc) {
15901 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15902 				"2503 WQ_CREATE mailbox failed with "
15903 				"status x%x add_status x%x, mbx status x%x\n",
15904 				shdr_status, shdr_add_status, rc);
15905 		status = -ENXIO;
15906 		goto out;
15907 	}
15908 
15909 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
15910 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
15911 					&wq_create->u.response);
15912 	else
15913 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
15914 					&wq_create->u.response_1);
15915 
15916 	if (wq->queue_id == 0xFFFF) {
15917 		status = -ENXIO;
15918 		goto out;
15919 	}
15920 
15921 	wq->db_format = LPFC_DB_LIST_FORMAT;
15922 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
15923 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
15924 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
15925 					       &wq_create->u.response);
15926 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
15927 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
15928 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15929 						"3265 WQ[%d] doorbell format "
15930 						"not supported: x%x\n",
15931 						wq->queue_id, wq->db_format);
15932 				status = -EINVAL;
15933 				goto out;
15934 			}
15935 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
15936 					    &wq_create->u.response);
15937 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15938 								   pci_barset);
15939 			if (!bar_memmap_p) {
15940 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15941 						"3263 WQ[%d] failed to memmap "
15942 						"pci barset:x%x\n",
15943 						wq->queue_id, pci_barset);
15944 				status = -ENOMEM;
15945 				goto out;
15946 			}
15947 			db_offset = wq_create->u.response.doorbell_offset;
15948 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
15949 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
15950 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15951 						"3252 WQ[%d] doorbell offset "
15952 						"not supported: x%x\n",
15953 						wq->queue_id, db_offset);
15954 				status = -EINVAL;
15955 				goto out;
15956 			}
15957 			wq->db_regaddr = bar_memmap_p + db_offset;
15958 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15959 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
15960 					"format:x%x\n", wq->queue_id,
15961 					pci_barset, db_offset, wq->db_format);
15962 		} else
15963 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
15964 	} else {
15965 		/* Check if DPP was honored by the firmware */
15966 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
15967 				    &wq_create->u.response_1);
15968 		if (wq->dpp_enable) {
15969 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
15970 					    &wq_create->u.response_1);
15971 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15972 								   pci_barset);
15973 			if (!bar_memmap_p) {
15974 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15975 						"3267 WQ[%d] failed to memmap "
15976 						"pci barset:x%x\n",
15977 						wq->queue_id, pci_barset);
15978 				status = -ENOMEM;
15979 				goto out;
15980 			}
15981 			db_offset = wq_create->u.response_1.doorbell_offset;
15982 			wq->db_regaddr = bar_memmap_p + db_offset;
15983 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
15984 					    &wq_create->u.response_1);
15985 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
15986 					    &wq_create->u.response_1);
15987 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15988 								   dpp_barset);
15989 			if (!bar_memmap_p) {
15990 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15991 						"3268 WQ[%d] failed to memmap "
15992 						"pci barset:x%x\n",
15993 						wq->queue_id, dpp_barset);
15994 				status = -ENOMEM;
15995 				goto out;
15996 			}
15997 			dpp_offset = wq_create->u.response_1.dpp_offset;
15998 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
15999 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16000 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
16001 					"dpp_id:x%x dpp_barset:x%x "
16002 					"dpp_offset:x%x\n",
16003 					wq->queue_id, pci_barset, db_offset,
16004 					wq->dpp_id, dpp_barset, dpp_offset);
16005 
16006 #ifdef CONFIG_X86
16007 			/* Enable combined writes for DPP aperture */
16008 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
16009 			rc = set_memory_wc(pg_addr, 1);
16010 			if (rc) {
16011 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16012 					"3272 Cannot setup Combined "
16013 					"Write on WQ[%d] - disable DPP\n",
16014 					wq->queue_id);
16015 				phba->cfg_enable_dpp = 0;
16016 			}
16017 #else
16018 			phba->cfg_enable_dpp = 0;
16019 #endif
16020 		} else
16021 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
16022 	}
16023 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
16024 	if (wq->pring == NULL) {
16025 		status = -ENOMEM;
16026 		goto out;
16027 	}
16028 	wq->type = LPFC_WQ;
16029 	wq->assoc_qid = cq->queue_id;
16030 	wq->subtype = subtype;
16031 	wq->host_index = 0;
16032 	wq->hba_index = 0;
16033 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
16034 
16035 	/* link the wq onto the parent cq child list */
16036 	list_add_tail(&wq->list, &cq->child_list);
16037 out:
16038 	mempool_free(mbox, phba->mbox_mem_pool);
16039 	return status;
16040 }
16041 
16042 /**
16043  * lpfc_rq_create - Create a Receive Queue on the HBA
16044  * @phba: HBA structure that indicates port to create a queue on.
16045  * @hrq: The queue structure to use to create the header receive queue.
16046  * @drq: The queue structure to use to create the data receive queue.
16047  * @cq: The completion queue to bind this work queue to.
16048  * @subtype: The subtype of the work queue indicating its functionality.
16049  *
16050  * This function creates a receive buffer queue pair , as detailed in @hrq and
16051  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
16052  * to the HBA.
16053  *
16054  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
16055  * struct is used to get the entry count that is necessary to determine the
16056  * number of pages to use for this queue. The @cq is used to indicate which
16057  * completion queue to bind received buffers that are posted to these queues to.
16058  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
16059  * receive queue pair. This function is asynchronous and will wait for the
16060  * mailbox command to finish before continuing.
16061  *
16062  * On success this function will return a zero. If unable to allocate enough
16063  * memory this function will return -ENOMEM. If the queue create mailbox command
16064  * fails this function will return -ENXIO.
16065  **/
16066 int
16067 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
16068 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
16069 {
16070 	struct lpfc_mbx_rq_create *rq_create;
16071 	struct lpfc_dmabuf *dmabuf;
16072 	LPFC_MBOXQ_t *mbox;
16073 	int rc, length, status = 0;
16074 	uint32_t shdr_status, shdr_add_status;
16075 	union lpfc_sli4_cfg_shdr *shdr;
16076 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16077 	void __iomem *bar_memmap_p;
16078 	uint32_t db_offset;
16079 	uint16_t pci_barset;
16080 
16081 	/* sanity check on queue memory */
16082 	if (!hrq || !drq || !cq)
16083 		return -ENODEV;
16084 	if (!phba->sli4_hba.pc_sli4_params.supported)
16085 		hw_page_size = SLI4_PAGE_SIZE;
16086 
16087 	if (hrq->entry_count != drq->entry_count)
16088 		return -EINVAL;
16089 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16090 	if (!mbox)
16091 		return -ENOMEM;
16092 	length = (sizeof(struct lpfc_mbx_rq_create) -
16093 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16094 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16095 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
16096 			 length, LPFC_SLI4_MBX_EMBED);
16097 	rq_create = &mbox->u.mqe.un.rq_create;
16098 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
16099 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16100 	       phba->sli4_hba.pc_sli4_params.rqv);
16101 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
16102 		bf_set(lpfc_rq_context_rqe_count_1,
16103 		       &rq_create->u.request.context,
16104 		       hrq->entry_count);
16105 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
16106 		bf_set(lpfc_rq_context_rqe_size,
16107 		       &rq_create->u.request.context,
16108 		       LPFC_RQE_SIZE_8);
16109 		bf_set(lpfc_rq_context_page_size,
16110 		       &rq_create->u.request.context,
16111 		       LPFC_RQ_PAGE_SIZE_4096);
16112 	} else {
16113 		switch (hrq->entry_count) {
16114 		default:
16115 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16116 					"2535 Unsupported RQ count. (%d)\n",
16117 					hrq->entry_count);
16118 			if (hrq->entry_count < 512) {
16119 				status = -EINVAL;
16120 				goto out;
16121 			}
16122 			/* fall through - otherwise default to smallest count */
16123 		case 512:
16124 			bf_set(lpfc_rq_context_rqe_count,
16125 			       &rq_create->u.request.context,
16126 			       LPFC_RQ_RING_SIZE_512);
16127 			break;
16128 		case 1024:
16129 			bf_set(lpfc_rq_context_rqe_count,
16130 			       &rq_create->u.request.context,
16131 			       LPFC_RQ_RING_SIZE_1024);
16132 			break;
16133 		case 2048:
16134 			bf_set(lpfc_rq_context_rqe_count,
16135 			       &rq_create->u.request.context,
16136 			       LPFC_RQ_RING_SIZE_2048);
16137 			break;
16138 		case 4096:
16139 			bf_set(lpfc_rq_context_rqe_count,
16140 			       &rq_create->u.request.context,
16141 			       LPFC_RQ_RING_SIZE_4096);
16142 			break;
16143 		}
16144 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
16145 		       LPFC_HDR_BUF_SIZE);
16146 	}
16147 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16148 	       cq->queue_id);
16149 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16150 	       hrq->page_count);
16151 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
16152 		memset(dmabuf->virt, 0, hw_page_size);
16153 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16154 					putPaddrLow(dmabuf->phys);
16155 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16156 					putPaddrHigh(dmabuf->phys);
16157 	}
16158 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16159 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16160 
16161 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16162 	/* The IOCTL status is embedded in the mailbox subheader. */
16163 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16164 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16165 	if (shdr_status || shdr_add_status || rc) {
16166 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16167 				"2504 RQ_CREATE mailbox failed with "
16168 				"status x%x add_status x%x, mbx status x%x\n",
16169 				shdr_status, shdr_add_status, rc);
16170 		status = -ENXIO;
16171 		goto out;
16172 	}
16173 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16174 	if (hrq->queue_id == 0xFFFF) {
16175 		status = -ENXIO;
16176 		goto out;
16177 	}
16178 
16179 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16180 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
16181 					&rq_create->u.response);
16182 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
16183 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
16184 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16185 					"3262 RQ [%d] doorbell format not "
16186 					"supported: x%x\n", hrq->queue_id,
16187 					hrq->db_format);
16188 			status = -EINVAL;
16189 			goto out;
16190 		}
16191 
16192 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
16193 				    &rq_create->u.response);
16194 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
16195 		if (!bar_memmap_p) {
16196 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16197 					"3269 RQ[%d] failed to memmap pci "
16198 					"barset:x%x\n", hrq->queue_id,
16199 					pci_barset);
16200 			status = -ENOMEM;
16201 			goto out;
16202 		}
16203 
16204 		db_offset = rq_create->u.response.doorbell_offset;
16205 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
16206 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
16207 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16208 					"3270 RQ[%d] doorbell offset not "
16209 					"supported: x%x\n", hrq->queue_id,
16210 					db_offset);
16211 			status = -EINVAL;
16212 			goto out;
16213 		}
16214 		hrq->db_regaddr = bar_memmap_p + db_offset;
16215 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16216 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
16217 				"format:x%x\n", hrq->queue_id, pci_barset,
16218 				db_offset, hrq->db_format);
16219 	} else {
16220 		hrq->db_format = LPFC_DB_RING_FORMAT;
16221 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16222 	}
16223 	hrq->type = LPFC_HRQ;
16224 	hrq->assoc_qid = cq->queue_id;
16225 	hrq->subtype = subtype;
16226 	hrq->host_index = 0;
16227 	hrq->hba_index = 0;
16228 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16229 
16230 	/* now create the data queue */
16231 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16232 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
16233 			 length, LPFC_SLI4_MBX_EMBED);
16234 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16235 	       phba->sli4_hba.pc_sli4_params.rqv);
16236 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
16237 		bf_set(lpfc_rq_context_rqe_count_1,
16238 		       &rq_create->u.request.context, hrq->entry_count);
16239 		if (subtype == LPFC_NVMET)
16240 			rq_create->u.request.context.buffer_size =
16241 				LPFC_NVMET_DATA_BUF_SIZE;
16242 		else
16243 			rq_create->u.request.context.buffer_size =
16244 				LPFC_DATA_BUF_SIZE;
16245 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
16246 		       LPFC_RQE_SIZE_8);
16247 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
16248 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
16249 	} else {
16250 		switch (drq->entry_count) {
16251 		default:
16252 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16253 					"2536 Unsupported RQ count. (%d)\n",
16254 					drq->entry_count);
16255 			if (drq->entry_count < 512) {
16256 				status = -EINVAL;
16257 				goto out;
16258 			}
16259 			/* fall through - otherwise default to smallest count */
16260 		case 512:
16261 			bf_set(lpfc_rq_context_rqe_count,
16262 			       &rq_create->u.request.context,
16263 			       LPFC_RQ_RING_SIZE_512);
16264 			break;
16265 		case 1024:
16266 			bf_set(lpfc_rq_context_rqe_count,
16267 			       &rq_create->u.request.context,
16268 			       LPFC_RQ_RING_SIZE_1024);
16269 			break;
16270 		case 2048:
16271 			bf_set(lpfc_rq_context_rqe_count,
16272 			       &rq_create->u.request.context,
16273 			       LPFC_RQ_RING_SIZE_2048);
16274 			break;
16275 		case 4096:
16276 			bf_set(lpfc_rq_context_rqe_count,
16277 			       &rq_create->u.request.context,
16278 			       LPFC_RQ_RING_SIZE_4096);
16279 			break;
16280 		}
16281 		if (subtype == LPFC_NVMET)
16282 			bf_set(lpfc_rq_context_buf_size,
16283 			       &rq_create->u.request.context,
16284 			       LPFC_NVMET_DATA_BUF_SIZE);
16285 		else
16286 			bf_set(lpfc_rq_context_buf_size,
16287 			       &rq_create->u.request.context,
16288 			       LPFC_DATA_BUF_SIZE);
16289 	}
16290 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16291 	       cq->queue_id);
16292 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16293 	       drq->page_count);
16294 	list_for_each_entry(dmabuf, &drq->page_list, list) {
16295 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16296 					putPaddrLow(dmabuf->phys);
16297 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16298 					putPaddrHigh(dmabuf->phys);
16299 	}
16300 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16301 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16302 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16303 	/* The IOCTL status is embedded in the mailbox subheader. */
16304 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
16305 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16306 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16307 	if (shdr_status || shdr_add_status || rc) {
16308 		status = -ENXIO;
16309 		goto out;
16310 	}
16311 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16312 	if (drq->queue_id == 0xFFFF) {
16313 		status = -ENXIO;
16314 		goto out;
16315 	}
16316 	drq->type = LPFC_DRQ;
16317 	drq->assoc_qid = cq->queue_id;
16318 	drq->subtype = subtype;
16319 	drq->host_index = 0;
16320 	drq->hba_index = 0;
16321 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16322 
16323 	/* link the header and data RQs onto the parent cq child list */
16324 	list_add_tail(&hrq->list, &cq->child_list);
16325 	list_add_tail(&drq->list, &cq->child_list);
16326 
16327 out:
16328 	mempool_free(mbox, phba->mbox_mem_pool);
16329 	return status;
16330 }
16331 
16332 /**
16333  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
16334  * @phba: HBA structure that indicates port to create a queue on.
16335  * @hrqp: The queue structure array to use to create the header receive queues.
16336  * @drqp: The queue structure array to use to create the data receive queues.
16337  * @cqp: The completion queue array to bind these receive queues to.
16338  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16339  *
16340  * This function creates a receive buffer queue pair , as detailed in @hrq and
16341  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
16342  * to the HBA.
16343  *
16344  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
16345  * struct is used to get the entry count that is necessary to determine the
16346  * number of pages to use for this queue. The @cq is used to indicate which
16347  * completion queue to bind received buffers that are posted to these queues to.
16348  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
16349  * receive queue pair. This function is asynchronous and will wait for the
16350  * mailbox command to finish before continuing.
16351  *
16352  * On success this function will return a zero. If unable to allocate enough
16353  * memory this function will return -ENOMEM. If the queue create mailbox command
16354  * fails this function will return -ENXIO.
16355  **/
16356 int
16357 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
16358 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
16359 		uint32_t subtype)
16360 {
16361 	struct lpfc_queue *hrq, *drq, *cq;
16362 	struct lpfc_mbx_rq_create_v2 *rq_create;
16363 	struct lpfc_dmabuf *dmabuf;
16364 	LPFC_MBOXQ_t *mbox;
16365 	int rc, length, alloclen, status = 0;
16366 	int cnt, idx, numrq, page_idx = 0;
16367 	uint32_t shdr_status, shdr_add_status;
16368 	union lpfc_sli4_cfg_shdr *shdr;
16369 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16370 
16371 	numrq = phba->cfg_nvmet_mrq;
16372 	/* sanity check on array memory */
16373 	if (!hrqp || !drqp || !cqp || !numrq)
16374 		return -ENODEV;
16375 	if (!phba->sli4_hba.pc_sli4_params.supported)
16376 		hw_page_size = SLI4_PAGE_SIZE;
16377 
16378 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16379 	if (!mbox)
16380 		return -ENOMEM;
16381 
16382 	length = sizeof(struct lpfc_mbx_rq_create_v2);
16383 	length += ((2 * numrq * hrqp[0]->page_count) *
16384 		   sizeof(struct dma_address));
16385 
16386 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16387 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
16388 				    LPFC_SLI4_MBX_NEMBED);
16389 	if (alloclen < length) {
16390 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16391 				"3099 Allocated DMA memory size (%d) is "
16392 				"less than the requested DMA memory size "
16393 				"(%d)\n", alloclen, length);
16394 		status = -ENOMEM;
16395 		goto out;
16396 	}
16397 
16398 
16399 
16400 	rq_create = mbox->sge_array->addr[0];
16401 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
16402 
16403 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
16404 	cnt = 0;
16405 
16406 	for (idx = 0; idx < numrq; idx++) {
16407 		hrq = hrqp[idx];
16408 		drq = drqp[idx];
16409 		cq  = cqp[idx];
16410 
16411 		/* sanity check on queue memory */
16412 		if (!hrq || !drq || !cq) {
16413 			status = -ENODEV;
16414 			goto out;
16415 		}
16416 
16417 		if (hrq->entry_count != drq->entry_count) {
16418 			status = -EINVAL;
16419 			goto out;
16420 		}
16421 
16422 		if (idx == 0) {
16423 			bf_set(lpfc_mbx_rq_create_num_pages,
16424 			       &rq_create->u.request,
16425 			       hrq->page_count);
16426 			bf_set(lpfc_mbx_rq_create_rq_cnt,
16427 			       &rq_create->u.request, (numrq * 2));
16428 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
16429 			       1);
16430 			bf_set(lpfc_rq_context_base_cq,
16431 			       &rq_create->u.request.context,
16432 			       cq->queue_id);
16433 			bf_set(lpfc_rq_context_data_size,
16434 			       &rq_create->u.request.context,
16435 			       LPFC_NVMET_DATA_BUF_SIZE);
16436 			bf_set(lpfc_rq_context_hdr_size,
16437 			       &rq_create->u.request.context,
16438 			       LPFC_HDR_BUF_SIZE);
16439 			bf_set(lpfc_rq_context_rqe_count_1,
16440 			       &rq_create->u.request.context,
16441 			       hrq->entry_count);
16442 			bf_set(lpfc_rq_context_rqe_size,
16443 			       &rq_create->u.request.context,
16444 			       LPFC_RQE_SIZE_8);
16445 			bf_set(lpfc_rq_context_page_size,
16446 			       &rq_create->u.request.context,
16447 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
16448 		}
16449 		rc = 0;
16450 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
16451 			memset(dmabuf->virt, 0, hw_page_size);
16452 			cnt = page_idx + dmabuf->buffer_tag;
16453 			rq_create->u.request.page[cnt].addr_lo =
16454 					putPaddrLow(dmabuf->phys);
16455 			rq_create->u.request.page[cnt].addr_hi =
16456 					putPaddrHigh(dmabuf->phys);
16457 			rc++;
16458 		}
16459 		page_idx += rc;
16460 
16461 		rc = 0;
16462 		list_for_each_entry(dmabuf, &drq->page_list, list) {
16463 			memset(dmabuf->virt, 0, hw_page_size);
16464 			cnt = page_idx + dmabuf->buffer_tag;
16465 			rq_create->u.request.page[cnt].addr_lo =
16466 					putPaddrLow(dmabuf->phys);
16467 			rq_create->u.request.page[cnt].addr_hi =
16468 					putPaddrHigh(dmabuf->phys);
16469 			rc++;
16470 		}
16471 		page_idx += rc;
16472 
16473 		hrq->db_format = LPFC_DB_RING_FORMAT;
16474 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16475 		hrq->type = LPFC_HRQ;
16476 		hrq->assoc_qid = cq->queue_id;
16477 		hrq->subtype = subtype;
16478 		hrq->host_index = 0;
16479 		hrq->hba_index = 0;
16480 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16481 
16482 		drq->db_format = LPFC_DB_RING_FORMAT;
16483 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16484 		drq->type = LPFC_DRQ;
16485 		drq->assoc_qid = cq->queue_id;
16486 		drq->subtype = subtype;
16487 		drq->host_index = 0;
16488 		drq->hba_index = 0;
16489 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16490 
16491 		list_add_tail(&hrq->list, &cq->child_list);
16492 		list_add_tail(&drq->list, &cq->child_list);
16493 	}
16494 
16495 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16496 	/* The IOCTL status is embedded in the mailbox subheader. */
16497 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16498 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16499 	if (shdr_status || shdr_add_status || rc) {
16500 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16501 				"3120 RQ_CREATE mailbox failed with "
16502 				"status x%x add_status x%x, mbx status x%x\n",
16503 				shdr_status, shdr_add_status, rc);
16504 		status = -ENXIO;
16505 		goto out;
16506 	}
16507 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16508 	if (rc == 0xFFFF) {
16509 		status = -ENXIO;
16510 		goto out;
16511 	}
16512 
16513 	/* Initialize all RQs with associated queue id */
16514 	for (idx = 0; idx < numrq; idx++) {
16515 		hrq = hrqp[idx];
16516 		hrq->queue_id = rc + (2 * idx);
16517 		drq = drqp[idx];
16518 		drq->queue_id = rc + (2 * idx) + 1;
16519 	}
16520 
16521 out:
16522 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16523 	return status;
16524 }
16525 
16526 /**
16527  * lpfc_eq_destroy - Destroy an event Queue on the HBA
16528  * @phba: HBA structure that indicates port to destroy a queue on.
16529  * @eq: The queue structure associated with the queue to destroy.
16530  *
16531  * This function destroys a queue, as detailed in @eq by sending an mailbox
16532  * command, specific to the type of queue, to the HBA.
16533  *
16534  * The @eq struct is used to get the queue ID of the queue to destroy.
16535  *
16536  * On success this function will return a zero. If the queue destroy mailbox
16537  * command fails this function will return -ENXIO.
16538  **/
16539 int
16540 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
16541 {
16542 	LPFC_MBOXQ_t *mbox;
16543 	int rc, length, status = 0;
16544 	uint32_t shdr_status, shdr_add_status;
16545 	union lpfc_sli4_cfg_shdr *shdr;
16546 
16547 	/* sanity check on queue memory */
16548 	if (!eq)
16549 		return -ENODEV;
16550 
16551 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
16552 	if (!mbox)
16553 		return -ENOMEM;
16554 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
16555 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16556 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16557 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
16558 			 length, LPFC_SLI4_MBX_EMBED);
16559 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
16560 	       eq->queue_id);
16561 	mbox->vport = eq->phba->pport;
16562 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16563 
16564 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
16565 	/* The IOCTL status is embedded in the mailbox subheader. */
16566 	shdr = (union lpfc_sli4_cfg_shdr *)
16567 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
16568 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16569 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16570 	if (shdr_status || shdr_add_status || rc) {
16571 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16572 				"2505 EQ_DESTROY mailbox failed with "
16573 				"status x%x add_status x%x, mbx status x%x\n",
16574 				shdr_status, shdr_add_status, rc);
16575 		status = -ENXIO;
16576 	}
16577 
16578 	/* Remove eq from any list */
16579 	list_del_init(&eq->list);
16580 	mempool_free(mbox, eq->phba->mbox_mem_pool);
16581 	return status;
16582 }
16583 
16584 /**
16585  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
16586  * @phba: HBA structure that indicates port to destroy a queue on.
16587  * @cq: The queue structure associated with the queue to destroy.
16588  *
16589  * This function destroys a queue, as detailed in @cq by sending an mailbox
16590  * command, specific to the type of queue, to the HBA.
16591  *
16592  * The @cq struct is used to get the queue ID of the queue to destroy.
16593  *
16594  * On success this function will return a zero. If the queue destroy mailbox
16595  * command fails this function will return -ENXIO.
16596  **/
16597 int
16598 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
16599 {
16600 	LPFC_MBOXQ_t *mbox;
16601 	int rc, length, status = 0;
16602 	uint32_t shdr_status, shdr_add_status;
16603 	union lpfc_sli4_cfg_shdr *shdr;
16604 
16605 	/* sanity check on queue memory */
16606 	if (!cq)
16607 		return -ENODEV;
16608 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
16609 	if (!mbox)
16610 		return -ENOMEM;
16611 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
16612 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16613 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16614 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
16615 			 length, LPFC_SLI4_MBX_EMBED);
16616 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
16617 	       cq->queue_id);
16618 	mbox->vport = cq->phba->pport;
16619 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16620 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
16621 	/* The IOCTL status is embedded in the mailbox subheader. */
16622 	shdr = (union lpfc_sli4_cfg_shdr *)
16623 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
16624 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16625 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16626 	if (shdr_status || shdr_add_status || rc) {
16627 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16628 				"2506 CQ_DESTROY mailbox failed with "
16629 				"status x%x add_status x%x, mbx status x%x\n",
16630 				shdr_status, shdr_add_status, rc);
16631 		status = -ENXIO;
16632 	}
16633 	/* Remove cq from any list */
16634 	list_del_init(&cq->list);
16635 	mempool_free(mbox, cq->phba->mbox_mem_pool);
16636 	return status;
16637 }
16638 
16639 /**
16640  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
16641  * @phba: HBA structure that indicates port to destroy a queue on.
16642  * @mq: The queue structure associated with the queue to destroy.
16643  *
16644  * This function destroys a queue, as detailed in @mq by sending an mailbox
16645  * command, specific to the type of queue, to the HBA.
16646  *
16647  * The @mq struct is used to get the queue ID of the queue to destroy.
16648  *
16649  * On success this function will return a zero. If the queue destroy mailbox
16650  * command fails this function will return -ENXIO.
16651  **/
16652 int
16653 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
16654 {
16655 	LPFC_MBOXQ_t *mbox;
16656 	int rc, length, status = 0;
16657 	uint32_t shdr_status, shdr_add_status;
16658 	union lpfc_sli4_cfg_shdr *shdr;
16659 
16660 	/* sanity check on queue memory */
16661 	if (!mq)
16662 		return -ENODEV;
16663 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
16664 	if (!mbox)
16665 		return -ENOMEM;
16666 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
16667 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16668 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16669 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
16670 			 length, LPFC_SLI4_MBX_EMBED);
16671 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
16672 	       mq->queue_id);
16673 	mbox->vport = mq->phba->pport;
16674 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16675 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
16676 	/* The IOCTL status is embedded in the mailbox subheader. */
16677 	shdr = (union lpfc_sli4_cfg_shdr *)
16678 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
16679 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16680 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16681 	if (shdr_status || shdr_add_status || rc) {
16682 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16683 				"2507 MQ_DESTROY mailbox failed with "
16684 				"status x%x add_status x%x, mbx status x%x\n",
16685 				shdr_status, shdr_add_status, rc);
16686 		status = -ENXIO;
16687 	}
16688 	/* Remove mq from any list */
16689 	list_del_init(&mq->list);
16690 	mempool_free(mbox, mq->phba->mbox_mem_pool);
16691 	return status;
16692 }
16693 
16694 /**
16695  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
16696  * @phba: HBA structure that indicates port to destroy a queue on.
16697  * @wq: The queue structure associated with the queue to destroy.
16698  *
16699  * This function destroys a queue, as detailed in @wq by sending an mailbox
16700  * command, specific to the type of queue, to the HBA.
16701  *
16702  * The @wq struct is used to get the queue ID of the queue to destroy.
16703  *
16704  * On success this function will return a zero. If the queue destroy mailbox
16705  * command fails this function will return -ENXIO.
16706  **/
16707 int
16708 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
16709 {
16710 	LPFC_MBOXQ_t *mbox;
16711 	int rc, length, status = 0;
16712 	uint32_t shdr_status, shdr_add_status;
16713 	union lpfc_sli4_cfg_shdr *shdr;
16714 
16715 	/* sanity check on queue memory */
16716 	if (!wq)
16717 		return -ENODEV;
16718 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
16719 	if (!mbox)
16720 		return -ENOMEM;
16721 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
16722 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16723 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16724 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
16725 			 length, LPFC_SLI4_MBX_EMBED);
16726 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
16727 	       wq->queue_id);
16728 	mbox->vport = wq->phba->pport;
16729 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16730 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
16731 	shdr = (union lpfc_sli4_cfg_shdr *)
16732 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
16733 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16734 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16735 	if (shdr_status || shdr_add_status || rc) {
16736 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16737 				"2508 WQ_DESTROY mailbox failed with "
16738 				"status x%x add_status x%x, mbx status x%x\n",
16739 				shdr_status, shdr_add_status, rc);
16740 		status = -ENXIO;
16741 	}
16742 	/* Remove wq from any list */
16743 	list_del_init(&wq->list);
16744 	kfree(wq->pring);
16745 	wq->pring = NULL;
16746 	mempool_free(mbox, wq->phba->mbox_mem_pool);
16747 	return status;
16748 }
16749 
16750 /**
16751  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
16752  * @phba: HBA structure that indicates port to destroy a queue on.
16753  * @hrq: The queue structure associated with the queue to destroy.
16754  * @drq: The queue structure associated with the queue to destroy.
16755  *
16756  * This function destroys a queue, as detailed in @rq by sending an mailbox
16757  * command, specific to the type of queue, to the HBA.
16758  *
16759  * The @rq struct is used to get the queue ID of the queue to destroy.
16760  *
16761  * On success this function will return a zero. If the queue destroy mailbox
16762  * command fails this function will return -ENXIO.
16763  **/
16764 int
16765 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
16766 		struct lpfc_queue *drq)
16767 {
16768 	LPFC_MBOXQ_t *mbox;
16769 	int rc, length, status = 0;
16770 	uint32_t shdr_status, shdr_add_status;
16771 	union lpfc_sli4_cfg_shdr *shdr;
16772 
16773 	/* sanity check on queue memory */
16774 	if (!hrq || !drq)
16775 		return -ENODEV;
16776 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
16777 	if (!mbox)
16778 		return -ENOMEM;
16779 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
16780 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16781 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16782 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
16783 			 length, LPFC_SLI4_MBX_EMBED);
16784 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
16785 	       hrq->queue_id);
16786 	mbox->vport = hrq->phba->pport;
16787 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16788 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
16789 	/* The IOCTL status is embedded in the mailbox subheader. */
16790 	shdr = (union lpfc_sli4_cfg_shdr *)
16791 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
16792 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16793 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16794 	if (shdr_status || shdr_add_status || rc) {
16795 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16796 				"2509 RQ_DESTROY mailbox failed with "
16797 				"status x%x add_status x%x, mbx status x%x\n",
16798 				shdr_status, shdr_add_status, rc);
16799 		if (rc != MBX_TIMEOUT)
16800 			mempool_free(mbox, hrq->phba->mbox_mem_pool);
16801 		return -ENXIO;
16802 	}
16803 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
16804 	       drq->queue_id);
16805 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
16806 	shdr = (union lpfc_sli4_cfg_shdr *)
16807 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
16808 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16809 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16810 	if (shdr_status || shdr_add_status || rc) {
16811 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16812 				"2510 RQ_DESTROY mailbox failed with "
16813 				"status x%x add_status x%x, mbx status x%x\n",
16814 				shdr_status, shdr_add_status, rc);
16815 		status = -ENXIO;
16816 	}
16817 	list_del_init(&hrq->list);
16818 	list_del_init(&drq->list);
16819 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
16820 	return status;
16821 }
16822 
16823 /**
16824  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
16825  * @phba: The virtual port for which this call being executed.
16826  * @pdma_phys_addr0: Physical address of the 1st SGL page.
16827  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
16828  * @xritag: the xritag that ties this io to the SGL pages.
16829  *
16830  * This routine will post the sgl pages for the IO that has the xritag
16831  * that is in the iocbq structure. The xritag is assigned during iocbq
16832  * creation and persists for as long as the driver is loaded.
16833  * if the caller has fewer than 256 scatter gather segments to map then
16834  * pdma_phys_addr1 should be 0.
16835  * If the caller needs to map more than 256 scatter gather segment then
16836  * pdma_phys_addr1 should be a valid physical address.
16837  * physical address for SGLs must be 64 byte aligned.
16838  * If you are going to map 2 SGL's then the first one must have 256 entries
16839  * the second sgl can have between 1 and 256 entries.
16840  *
16841  * Return codes:
16842  * 	0 - Success
16843  * 	-ENXIO, -ENOMEM - Failure
16844  **/
16845 int
16846 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
16847 		dma_addr_t pdma_phys_addr0,
16848 		dma_addr_t pdma_phys_addr1,
16849 		uint16_t xritag)
16850 {
16851 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
16852 	LPFC_MBOXQ_t *mbox;
16853 	int rc;
16854 	uint32_t shdr_status, shdr_add_status;
16855 	uint32_t mbox_tmo;
16856 	union lpfc_sli4_cfg_shdr *shdr;
16857 
16858 	if (xritag == NO_XRI) {
16859 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16860 				"0364 Invalid param:\n");
16861 		return -EINVAL;
16862 	}
16863 
16864 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16865 	if (!mbox)
16866 		return -ENOMEM;
16867 
16868 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16869 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
16870 			sizeof(struct lpfc_mbx_post_sgl_pages) -
16871 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
16872 
16873 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
16874 				&mbox->u.mqe.un.post_sgl_pages;
16875 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
16876 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
16877 
16878 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
16879 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
16880 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
16881 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
16882 
16883 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
16884 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
16885 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
16886 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
16887 	if (!phba->sli4_hba.intr_enable)
16888 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16889 	else {
16890 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16891 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16892 	}
16893 	/* The IOCTL status is embedded in the mailbox subheader. */
16894 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
16895 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16896 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16897 	if (rc != MBX_TIMEOUT)
16898 		mempool_free(mbox, phba->mbox_mem_pool);
16899 	if (shdr_status || shdr_add_status || rc) {
16900 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16901 				"2511 POST_SGL mailbox failed with "
16902 				"status x%x add_status x%x, mbx status x%x\n",
16903 				shdr_status, shdr_add_status, rc);
16904 	}
16905 	return 0;
16906 }
16907 
16908 /**
16909  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
16910  * @phba: pointer to lpfc hba data structure.
16911  *
16912  * This routine is invoked to post rpi header templates to the
16913  * HBA consistent with the SLI-4 interface spec.  This routine
16914  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
16915  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
16916  *
16917  * Returns
16918  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
16919  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
16920  **/
16921 static uint16_t
16922 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
16923 {
16924 	unsigned long xri;
16925 
16926 	/*
16927 	 * Fetch the next logical xri.  Because this index is logical,
16928 	 * the driver starts at 0 each time.
16929 	 */
16930 	spin_lock_irq(&phba->hbalock);
16931 	xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
16932 				 phba->sli4_hba.max_cfg_param.max_xri, 0);
16933 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
16934 		spin_unlock_irq(&phba->hbalock);
16935 		return NO_XRI;
16936 	} else {
16937 		set_bit(xri, phba->sli4_hba.xri_bmask);
16938 		phba->sli4_hba.max_cfg_param.xri_used++;
16939 	}
16940 	spin_unlock_irq(&phba->hbalock);
16941 	return xri;
16942 }
16943 
16944 /**
16945  * lpfc_sli4_free_xri - Release an xri for reuse.
16946  * @phba: pointer to lpfc hba data structure.
16947  * @xri: xri to release.
16948  *
16949  * This routine is invoked to release an xri to the pool of
16950  * available rpis maintained by the driver.
16951  **/
16952 static void
16953 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
16954 {
16955 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
16956 		phba->sli4_hba.max_cfg_param.xri_used--;
16957 	}
16958 }
16959 
16960 /**
16961  * lpfc_sli4_free_xri - Release an xri for reuse.
16962  * @phba: pointer to lpfc hba data structure.
16963  * @xri: xri to release.
16964  *
16965  * This routine is invoked to release an xri to the pool of
16966  * available rpis maintained by the driver.
16967  **/
16968 void
16969 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
16970 {
16971 	spin_lock_irq(&phba->hbalock);
16972 	__lpfc_sli4_free_xri(phba, xri);
16973 	spin_unlock_irq(&phba->hbalock);
16974 }
16975 
16976 /**
16977  * lpfc_sli4_next_xritag - Get an xritag for the io
16978  * @phba: Pointer to HBA context object.
16979  *
16980  * This function gets an xritag for the iocb. If there is no unused xritag
16981  * it will return 0xffff.
16982  * The function returns the allocated xritag if successful, else returns zero.
16983  * Zero is not a valid xritag.
16984  * The caller is not required to hold any lock.
16985  **/
16986 uint16_t
16987 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
16988 {
16989 	uint16_t xri_index;
16990 
16991 	xri_index = lpfc_sli4_alloc_xri(phba);
16992 	if (xri_index == NO_XRI)
16993 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
16994 				"2004 Failed to allocate XRI.last XRITAG is %d"
16995 				" Max XRI is %d, Used XRI is %d\n",
16996 				xri_index,
16997 				phba->sli4_hba.max_cfg_param.max_xri,
16998 				phba->sli4_hba.max_cfg_param.xri_used);
16999 	return xri_index;
17000 }
17001 
17002 /**
17003  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
17004  * @phba: pointer to lpfc hba data structure.
17005  * @post_sgl_list: pointer to els sgl entry list.
17006  * @post_cnt: number of els sgl entries on the list.
17007  *
17008  * This routine is invoked to post a block of driver's sgl pages to the
17009  * HBA using non-embedded mailbox command. No Lock is held. This routine
17010  * is only called when the driver is loading and after all IO has been
17011  * stopped.
17012  **/
17013 static int
17014 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
17015 			    struct list_head *post_sgl_list,
17016 			    int post_cnt)
17017 {
17018 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
17019 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
17020 	struct sgl_page_pairs *sgl_pg_pairs;
17021 	void *viraddr;
17022 	LPFC_MBOXQ_t *mbox;
17023 	uint32_t reqlen, alloclen, pg_pairs;
17024 	uint32_t mbox_tmo;
17025 	uint16_t xritag_start = 0;
17026 	int rc = 0;
17027 	uint32_t shdr_status, shdr_add_status;
17028 	union lpfc_sli4_cfg_shdr *shdr;
17029 
17030 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
17031 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
17032 	if (reqlen > SLI4_PAGE_SIZE) {
17033 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17034 				"2559 Block sgl registration required DMA "
17035 				"size (%d) great than a page\n", reqlen);
17036 		return -ENOMEM;
17037 	}
17038 
17039 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17040 	if (!mbox)
17041 		return -ENOMEM;
17042 
17043 	/* Allocate DMA memory and set up the non-embedded mailbox command */
17044 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17045 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
17046 			 LPFC_SLI4_MBX_NEMBED);
17047 
17048 	if (alloclen < reqlen) {
17049 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17050 				"0285 Allocated DMA memory size (%d) is "
17051 				"less than the requested DMA memory "
17052 				"size (%d)\n", alloclen, reqlen);
17053 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17054 		return -ENOMEM;
17055 	}
17056 	/* Set up the SGL pages in the non-embedded DMA pages */
17057 	viraddr = mbox->sge_array->addr[0];
17058 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
17059 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
17060 
17061 	pg_pairs = 0;
17062 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
17063 		/* Set up the sge entry */
17064 		sgl_pg_pairs->sgl_pg0_addr_lo =
17065 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
17066 		sgl_pg_pairs->sgl_pg0_addr_hi =
17067 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
17068 		sgl_pg_pairs->sgl_pg1_addr_lo =
17069 				cpu_to_le32(putPaddrLow(0));
17070 		sgl_pg_pairs->sgl_pg1_addr_hi =
17071 				cpu_to_le32(putPaddrHigh(0));
17072 
17073 		/* Keep the first xritag on the list */
17074 		if (pg_pairs == 0)
17075 			xritag_start = sglq_entry->sli4_xritag;
17076 		sgl_pg_pairs++;
17077 		pg_pairs++;
17078 	}
17079 
17080 	/* Complete initialization and perform endian conversion. */
17081 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
17082 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
17083 	sgl->word0 = cpu_to_le32(sgl->word0);
17084 
17085 	if (!phba->sli4_hba.intr_enable)
17086 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17087 	else {
17088 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17089 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17090 	}
17091 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
17092 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17093 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17094 	if (rc != MBX_TIMEOUT)
17095 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17096 	if (shdr_status || shdr_add_status || rc) {
17097 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17098 				"2513 POST_SGL_BLOCK mailbox command failed "
17099 				"status x%x add_status x%x mbx status x%x\n",
17100 				shdr_status, shdr_add_status, rc);
17101 		rc = -ENXIO;
17102 	}
17103 	return rc;
17104 }
17105 
17106 /**
17107  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
17108  * @phba: pointer to lpfc hba data structure.
17109  * @nblist: pointer to nvme buffer list.
17110  * @count: number of scsi buffers on the list.
17111  *
17112  * This routine is invoked to post a block of @count scsi sgl pages from a
17113  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
17114  * No Lock is held.
17115  *
17116  **/
17117 static int
17118 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
17119 			    int count)
17120 {
17121 	struct lpfc_io_buf *lpfc_ncmd;
17122 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
17123 	struct sgl_page_pairs *sgl_pg_pairs;
17124 	void *viraddr;
17125 	LPFC_MBOXQ_t *mbox;
17126 	uint32_t reqlen, alloclen, pg_pairs;
17127 	uint32_t mbox_tmo;
17128 	uint16_t xritag_start = 0;
17129 	int rc = 0;
17130 	uint32_t shdr_status, shdr_add_status;
17131 	dma_addr_t pdma_phys_bpl1;
17132 	union lpfc_sli4_cfg_shdr *shdr;
17133 
17134 	/* Calculate the requested length of the dma memory */
17135 	reqlen = count * sizeof(struct sgl_page_pairs) +
17136 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
17137 	if (reqlen > SLI4_PAGE_SIZE) {
17138 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
17139 				"6118 Block sgl registration required DMA "
17140 				"size (%d) great than a page\n", reqlen);
17141 		return -ENOMEM;
17142 	}
17143 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17144 	if (!mbox) {
17145 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17146 				"6119 Failed to allocate mbox cmd memory\n");
17147 		return -ENOMEM;
17148 	}
17149 
17150 	/* Allocate DMA memory and set up the non-embedded mailbox command */
17151 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17152 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17153 				    reqlen, LPFC_SLI4_MBX_NEMBED);
17154 
17155 	if (alloclen < reqlen) {
17156 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17157 				"6120 Allocated DMA memory size (%d) is "
17158 				"less than the requested DMA memory "
17159 				"size (%d)\n", alloclen, reqlen);
17160 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17161 		return -ENOMEM;
17162 	}
17163 
17164 	/* Get the first SGE entry from the non-embedded DMA memory */
17165 	viraddr = mbox->sge_array->addr[0];
17166 
17167 	/* Set up the SGL pages in the non-embedded DMA pages */
17168 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
17169 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
17170 
17171 	pg_pairs = 0;
17172 	list_for_each_entry(lpfc_ncmd, nblist, list) {
17173 		/* Set up the sge entry */
17174 		sgl_pg_pairs->sgl_pg0_addr_lo =
17175 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
17176 		sgl_pg_pairs->sgl_pg0_addr_hi =
17177 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
17178 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
17179 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
17180 						SGL_PAGE_SIZE;
17181 		else
17182 			pdma_phys_bpl1 = 0;
17183 		sgl_pg_pairs->sgl_pg1_addr_lo =
17184 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
17185 		sgl_pg_pairs->sgl_pg1_addr_hi =
17186 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
17187 		/* Keep the first xritag on the list */
17188 		if (pg_pairs == 0)
17189 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
17190 		sgl_pg_pairs++;
17191 		pg_pairs++;
17192 	}
17193 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
17194 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
17195 	/* Perform endian conversion if necessary */
17196 	sgl->word0 = cpu_to_le32(sgl->word0);
17197 
17198 	if (!phba->sli4_hba.intr_enable) {
17199 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17200 	} else {
17201 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17202 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17203 	}
17204 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
17205 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17206 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17207 	if (rc != MBX_TIMEOUT)
17208 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17209 	if (shdr_status || shdr_add_status || rc) {
17210 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17211 				"6125 POST_SGL_BLOCK mailbox command failed "
17212 				"status x%x add_status x%x mbx status x%x\n",
17213 				shdr_status, shdr_add_status, rc);
17214 		rc = -ENXIO;
17215 	}
17216 	return rc;
17217 }
17218 
17219 /**
17220  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
17221  * @phba: pointer to lpfc hba data structure.
17222  * @post_nblist: pointer to the nvme buffer list.
17223  * @sb_count: number of nvme buffers.
17224  *
17225  * This routine walks a list of nvme buffers that was passed in. It attempts
17226  * to construct blocks of nvme buffer sgls which contains contiguous xris and
17227  * uses the non-embedded SGL block post mailbox commands to post to the port.
17228  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
17229  * embedded SGL post mailbox command for posting. The @post_nblist passed in
17230  * must be local list, thus no lock is needed when manipulate the list.
17231  *
17232  * Returns: 0 = failure, non-zero number of successfully posted buffers.
17233  **/
17234 int
17235 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
17236 			   struct list_head *post_nblist, int sb_count)
17237 {
17238 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
17239 	int status, sgl_size;
17240 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
17241 	dma_addr_t pdma_phys_sgl1;
17242 	int last_xritag = NO_XRI;
17243 	int cur_xritag;
17244 	LIST_HEAD(prep_nblist);
17245 	LIST_HEAD(blck_nblist);
17246 	LIST_HEAD(nvme_nblist);
17247 
17248 	/* sanity check */
17249 	if (sb_count <= 0)
17250 		return -EINVAL;
17251 
17252 	sgl_size = phba->cfg_sg_dma_buf_size;
17253 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
17254 		list_del_init(&lpfc_ncmd->list);
17255 		block_cnt++;
17256 		if ((last_xritag != NO_XRI) &&
17257 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
17258 			/* a hole in xri block, form a sgl posting block */
17259 			list_splice_init(&prep_nblist, &blck_nblist);
17260 			post_cnt = block_cnt - 1;
17261 			/* prepare list for next posting block */
17262 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17263 			block_cnt = 1;
17264 		} else {
17265 			/* prepare list for next posting block */
17266 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17267 			/* enough sgls for non-embed sgl mbox command */
17268 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
17269 				list_splice_init(&prep_nblist, &blck_nblist);
17270 				post_cnt = block_cnt;
17271 				block_cnt = 0;
17272 			}
17273 		}
17274 		num_posting++;
17275 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17276 
17277 		/* end of repost sgl list condition for NVME buffers */
17278 		if (num_posting == sb_count) {
17279 			if (post_cnt == 0) {
17280 				/* last sgl posting block */
17281 				list_splice_init(&prep_nblist, &blck_nblist);
17282 				post_cnt = block_cnt;
17283 			} else if (block_cnt == 1) {
17284 				/* last single sgl with non-contiguous xri */
17285 				if (sgl_size > SGL_PAGE_SIZE)
17286 					pdma_phys_sgl1 =
17287 						lpfc_ncmd->dma_phys_sgl +
17288 						SGL_PAGE_SIZE;
17289 				else
17290 					pdma_phys_sgl1 = 0;
17291 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17292 				status = lpfc_sli4_post_sgl(
17293 						phba, lpfc_ncmd->dma_phys_sgl,
17294 						pdma_phys_sgl1, cur_xritag);
17295 				if (status) {
17296 					/* Post error.  Buffer unavailable. */
17297 					lpfc_ncmd->flags |=
17298 						LPFC_SBUF_NOT_POSTED;
17299 				} else {
17300 					/* Post success. Bffer available. */
17301 					lpfc_ncmd->flags &=
17302 						~LPFC_SBUF_NOT_POSTED;
17303 					lpfc_ncmd->status = IOSTAT_SUCCESS;
17304 					num_posted++;
17305 				}
17306 				/* success, put on NVME buffer sgl list */
17307 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17308 			}
17309 		}
17310 
17311 		/* continue until a nembed page worth of sgls */
17312 		if (post_cnt == 0)
17313 			continue;
17314 
17315 		/* post block of NVME buffer list sgls */
17316 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
17317 						     post_cnt);
17318 
17319 		/* don't reset xirtag due to hole in xri block */
17320 		if (block_cnt == 0)
17321 			last_xritag = NO_XRI;
17322 
17323 		/* reset NVME buffer post count for next round of posting */
17324 		post_cnt = 0;
17325 
17326 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
17327 		while (!list_empty(&blck_nblist)) {
17328 			list_remove_head(&blck_nblist, lpfc_ncmd,
17329 					 struct lpfc_io_buf, list);
17330 			if (status) {
17331 				/* Post error.  Mark buffer unavailable. */
17332 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
17333 			} else {
17334 				/* Post success, Mark buffer available. */
17335 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
17336 				lpfc_ncmd->status = IOSTAT_SUCCESS;
17337 				num_posted++;
17338 			}
17339 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17340 		}
17341 	}
17342 	/* Push NVME buffers with sgl posted to the available list */
17343 	lpfc_io_buf_replenish(phba, &nvme_nblist);
17344 
17345 	return num_posted;
17346 }
17347 
17348 /**
17349  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
17350  * @phba: pointer to lpfc_hba struct that the frame was received on
17351  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17352  *
17353  * This function checks the fields in the @fc_hdr to see if the FC frame is a
17354  * valid type of frame that the LPFC driver will handle. This function will
17355  * return a zero if the frame is a valid frame or a non zero value when the
17356  * frame does not pass the check.
17357  **/
17358 static int
17359 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
17360 {
17361 	/*  make rctl_names static to save stack space */
17362 	struct fc_vft_header *fc_vft_hdr;
17363 	uint32_t *header = (uint32_t *) fc_hdr;
17364 
17365 #define FC_RCTL_MDS_DIAGS	0xF4
17366 
17367 	switch (fc_hdr->fh_r_ctl) {
17368 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
17369 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
17370 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
17371 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
17372 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
17373 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
17374 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
17375 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
17376 	case FC_RCTL_ELS_REQ:	/* extended link services request */
17377 	case FC_RCTL_ELS_REP:	/* extended link services reply */
17378 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
17379 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
17380 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
17381 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
17382 	case FC_RCTL_BA_RMC: 	/* remove connection */
17383 	case FC_RCTL_BA_ACC:	/* basic accept */
17384 	case FC_RCTL_BA_RJT:	/* basic reject */
17385 	case FC_RCTL_BA_PRMT:
17386 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
17387 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
17388 	case FC_RCTL_P_RJT:	/* port reject */
17389 	case FC_RCTL_F_RJT:	/* fabric reject */
17390 	case FC_RCTL_P_BSY:	/* port busy */
17391 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
17392 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
17393 	case FC_RCTL_LCR:	/* link credit reset */
17394 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
17395 	case FC_RCTL_END:	/* end */
17396 		break;
17397 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
17398 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17399 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
17400 		return lpfc_fc_frame_check(phba, fc_hdr);
17401 	default:
17402 		goto drop;
17403 	}
17404 
17405 	switch (fc_hdr->fh_type) {
17406 	case FC_TYPE_BLS:
17407 	case FC_TYPE_ELS:
17408 	case FC_TYPE_FCP:
17409 	case FC_TYPE_CT:
17410 	case FC_TYPE_NVME:
17411 		break;
17412 	case FC_TYPE_IP:
17413 	case FC_TYPE_ILS:
17414 	default:
17415 		goto drop;
17416 	}
17417 
17418 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
17419 			"2538 Received frame rctl:x%x, type:x%x, "
17420 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
17421 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
17422 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
17423 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
17424 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
17425 			be32_to_cpu(header[6]));
17426 	return 0;
17427 drop:
17428 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
17429 			"2539 Dropped frame rctl:x%x type:x%x\n",
17430 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17431 	return 1;
17432 }
17433 
17434 /**
17435  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
17436  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17437  *
17438  * This function processes the FC header to retrieve the VFI from the VF
17439  * header, if one exists. This function will return the VFI if one exists
17440  * or 0 if no VSAN Header exists.
17441  **/
17442 static uint32_t
17443 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
17444 {
17445 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17446 
17447 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
17448 		return 0;
17449 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
17450 }
17451 
17452 /**
17453  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
17454  * @phba: Pointer to the HBA structure to search for the vport on
17455  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17456  * @fcfi: The FC Fabric ID that the frame came from
17457  * @did: Destination ID to match against
17458  *
17459  * This function searches the @phba for a vport that matches the content of the
17460  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
17461  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
17462  * returns the matching vport pointer or NULL if unable to match frame to a
17463  * vport.
17464  **/
17465 static struct lpfc_vport *
17466 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
17467 		       uint16_t fcfi, uint32_t did)
17468 {
17469 	struct lpfc_vport **vports;
17470 	struct lpfc_vport *vport = NULL;
17471 	int i;
17472 
17473 	if (did == Fabric_DID)
17474 		return phba->pport;
17475 	if ((phba->pport->fc_flag & FC_PT2PT) &&
17476 		!(phba->link_state == LPFC_HBA_READY))
17477 		return phba->pport;
17478 
17479 	vports = lpfc_create_vport_work_array(phba);
17480 	if (vports != NULL) {
17481 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
17482 			if (phba->fcf.fcfi == fcfi &&
17483 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
17484 			    vports[i]->fc_myDID == did) {
17485 				vport = vports[i];
17486 				break;
17487 			}
17488 		}
17489 	}
17490 	lpfc_destroy_vport_work_array(phba, vports);
17491 	return vport;
17492 }
17493 
17494 /**
17495  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
17496  * @vport: The vport to work on.
17497  *
17498  * This function updates the receive sequence time stamp for this vport. The
17499  * receive sequence time stamp indicates the time that the last frame of the
17500  * the sequence that has been idle for the longest amount of time was received.
17501  * the driver uses this time stamp to indicate if any received sequences have
17502  * timed out.
17503  **/
17504 static void
17505 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
17506 {
17507 	struct lpfc_dmabuf *h_buf;
17508 	struct hbq_dmabuf *dmabuf = NULL;
17509 
17510 	/* get the oldest sequence on the rcv list */
17511 	h_buf = list_get_first(&vport->rcv_buffer_list,
17512 			       struct lpfc_dmabuf, list);
17513 	if (!h_buf)
17514 		return;
17515 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17516 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
17517 }
17518 
17519 /**
17520  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
17521  * @vport: The vport that the received sequences were sent to.
17522  *
17523  * This function cleans up all outstanding received sequences. This is called
17524  * by the driver when a link event or user action invalidates all the received
17525  * sequences.
17526  **/
17527 void
17528 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
17529 {
17530 	struct lpfc_dmabuf *h_buf, *hnext;
17531 	struct lpfc_dmabuf *d_buf, *dnext;
17532 	struct hbq_dmabuf *dmabuf = NULL;
17533 
17534 	/* start with the oldest sequence on the rcv list */
17535 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17536 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17537 		list_del_init(&dmabuf->hbuf.list);
17538 		list_for_each_entry_safe(d_buf, dnext,
17539 					 &dmabuf->dbuf.list, list) {
17540 			list_del_init(&d_buf->list);
17541 			lpfc_in_buf_free(vport->phba, d_buf);
17542 		}
17543 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17544 	}
17545 }
17546 
17547 /**
17548  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
17549  * @vport: The vport that the received sequences were sent to.
17550  *
17551  * This function determines whether any received sequences have timed out by
17552  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
17553  * indicates that there is at least one timed out sequence this routine will
17554  * go through the received sequences one at a time from most inactive to most
17555  * active to determine which ones need to be cleaned up. Once it has determined
17556  * that a sequence needs to be cleaned up it will simply free up the resources
17557  * without sending an abort.
17558  **/
17559 void
17560 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
17561 {
17562 	struct lpfc_dmabuf *h_buf, *hnext;
17563 	struct lpfc_dmabuf *d_buf, *dnext;
17564 	struct hbq_dmabuf *dmabuf = NULL;
17565 	unsigned long timeout;
17566 	int abort_count = 0;
17567 
17568 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17569 		   vport->rcv_buffer_time_stamp);
17570 	if (list_empty(&vport->rcv_buffer_list) ||
17571 	    time_before(jiffies, timeout))
17572 		return;
17573 	/* start with the oldest sequence on the rcv list */
17574 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17575 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17576 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17577 			   dmabuf->time_stamp);
17578 		if (time_before(jiffies, timeout))
17579 			break;
17580 		abort_count++;
17581 		list_del_init(&dmabuf->hbuf.list);
17582 		list_for_each_entry_safe(d_buf, dnext,
17583 					 &dmabuf->dbuf.list, list) {
17584 			list_del_init(&d_buf->list);
17585 			lpfc_in_buf_free(vport->phba, d_buf);
17586 		}
17587 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17588 	}
17589 	if (abort_count)
17590 		lpfc_update_rcv_time_stamp(vport);
17591 }
17592 
17593 /**
17594  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
17595  * @vport: pointer to a vitural port
17596  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
17597  *
17598  * This function searches through the existing incomplete sequences that have
17599  * been sent to this @vport. If the frame matches one of the incomplete
17600  * sequences then the dbuf in the @dmabuf is added to the list of frames that
17601  * make up that sequence. If no sequence is found that matches this frame then
17602  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
17603  * This function returns a pointer to the first dmabuf in the sequence list that
17604  * the frame was linked to.
17605  **/
17606 static struct hbq_dmabuf *
17607 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
17608 {
17609 	struct fc_frame_header *new_hdr;
17610 	struct fc_frame_header *temp_hdr;
17611 	struct lpfc_dmabuf *d_buf;
17612 	struct lpfc_dmabuf *h_buf;
17613 	struct hbq_dmabuf *seq_dmabuf = NULL;
17614 	struct hbq_dmabuf *temp_dmabuf = NULL;
17615 	uint8_t	found = 0;
17616 
17617 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
17618 	dmabuf->time_stamp = jiffies;
17619 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17620 
17621 	/* Use the hdr_buf to find the sequence that this frame belongs to */
17622 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
17623 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
17624 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
17625 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
17626 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
17627 			continue;
17628 		/* found a pending sequence that matches this frame */
17629 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17630 		break;
17631 	}
17632 	if (!seq_dmabuf) {
17633 		/*
17634 		 * This indicates first frame received for this sequence.
17635 		 * Queue the buffer on the vport's rcv_buffer_list.
17636 		 */
17637 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17638 		lpfc_update_rcv_time_stamp(vport);
17639 		return dmabuf;
17640 	}
17641 	temp_hdr = seq_dmabuf->hbuf.virt;
17642 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
17643 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17644 		list_del_init(&seq_dmabuf->hbuf.list);
17645 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17646 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17647 		lpfc_update_rcv_time_stamp(vport);
17648 		return dmabuf;
17649 	}
17650 	/* move this sequence to the tail to indicate a young sequence */
17651 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
17652 	seq_dmabuf->time_stamp = jiffies;
17653 	lpfc_update_rcv_time_stamp(vport);
17654 	if (list_empty(&seq_dmabuf->dbuf.list)) {
17655 		temp_hdr = dmabuf->hbuf.virt;
17656 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17657 		return seq_dmabuf;
17658 	}
17659 	/* find the correct place in the sequence to insert this frame */
17660 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
17661 	while (!found) {
17662 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17663 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
17664 		/*
17665 		 * If the frame's sequence count is greater than the frame on
17666 		 * the list then insert the frame right after this frame
17667 		 */
17668 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
17669 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17670 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
17671 			found = 1;
17672 			break;
17673 		}
17674 
17675 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
17676 			break;
17677 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
17678 	}
17679 
17680 	if (found)
17681 		return seq_dmabuf;
17682 	return NULL;
17683 }
17684 
17685 /**
17686  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
17687  * @vport: pointer to a vitural port
17688  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17689  *
17690  * This function tries to abort from the partially assembed sequence, described
17691  * by the information from basic abbort @dmabuf. It checks to see whether such
17692  * partially assembled sequence held by the driver. If so, it shall free up all
17693  * the frames from the partially assembled sequence.
17694  *
17695  * Return
17696  * true  -- if there is matching partially assembled sequence present and all
17697  *          the frames freed with the sequence;
17698  * false -- if there is no matching partially assembled sequence present so
17699  *          nothing got aborted in the lower layer driver
17700  **/
17701 static bool
17702 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
17703 			    struct hbq_dmabuf *dmabuf)
17704 {
17705 	struct fc_frame_header *new_hdr;
17706 	struct fc_frame_header *temp_hdr;
17707 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
17708 	struct hbq_dmabuf *seq_dmabuf = NULL;
17709 
17710 	/* Use the hdr_buf to find the sequence that matches this frame */
17711 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
17712 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
17713 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17714 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
17715 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
17716 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
17717 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
17718 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
17719 			continue;
17720 		/* found a pending sequence that matches this frame */
17721 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17722 		break;
17723 	}
17724 
17725 	/* Free up all the frames from the partially assembled sequence */
17726 	if (seq_dmabuf) {
17727 		list_for_each_entry_safe(d_buf, n_buf,
17728 					 &seq_dmabuf->dbuf.list, list) {
17729 			list_del_init(&d_buf->list);
17730 			lpfc_in_buf_free(vport->phba, d_buf);
17731 		}
17732 		return true;
17733 	}
17734 	return false;
17735 }
17736 
17737 /**
17738  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
17739  * @vport: pointer to a vitural port
17740  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17741  *
17742  * This function tries to abort from the assembed sequence from upper level
17743  * protocol, described by the information from basic abbort @dmabuf. It
17744  * checks to see whether such pending context exists at upper level protocol.
17745  * If so, it shall clean up the pending context.
17746  *
17747  * Return
17748  * true  -- if there is matching pending context of the sequence cleaned
17749  *          at ulp;
17750  * false -- if there is no matching pending context of the sequence present
17751  *          at ulp.
17752  **/
17753 static bool
17754 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
17755 {
17756 	struct lpfc_hba *phba = vport->phba;
17757 	int handled;
17758 
17759 	/* Accepting abort at ulp with SLI4 only */
17760 	if (phba->sli_rev < LPFC_SLI_REV4)
17761 		return false;
17762 
17763 	/* Register all caring upper level protocols to attend abort */
17764 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
17765 	if (handled)
17766 		return true;
17767 
17768 	return false;
17769 }
17770 
17771 /**
17772  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
17773  * @phba: Pointer to HBA context object.
17774  * @cmd_iocbq: pointer to the command iocbq structure.
17775  * @rsp_iocbq: pointer to the response iocbq structure.
17776  *
17777  * This function handles the sequence abort response iocb command complete
17778  * event. It properly releases the memory allocated to the sequence abort
17779  * accept iocb.
17780  **/
17781 static void
17782 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
17783 			     struct lpfc_iocbq *cmd_iocbq,
17784 			     struct lpfc_iocbq *rsp_iocbq)
17785 {
17786 	struct lpfc_nodelist *ndlp;
17787 
17788 	if (cmd_iocbq) {
17789 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
17790 		lpfc_nlp_put(ndlp);
17791 		lpfc_nlp_not_used(ndlp);
17792 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
17793 	}
17794 
17795 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
17796 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
17797 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17798 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
17799 			rsp_iocbq->iocb.ulpStatus,
17800 			rsp_iocbq->iocb.un.ulpWord[4]);
17801 }
17802 
17803 /**
17804  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
17805  * @phba: Pointer to HBA context object.
17806  * @xri: xri id in transaction.
17807  *
17808  * This function validates the xri maps to the known range of XRIs allocated an
17809  * used by the driver.
17810  **/
17811 uint16_t
17812 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
17813 		      uint16_t xri)
17814 {
17815 	uint16_t i;
17816 
17817 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
17818 		if (xri == phba->sli4_hba.xri_ids[i])
17819 			return i;
17820 	}
17821 	return NO_XRI;
17822 }
17823 
17824 /**
17825  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
17826  * @vport: pointer to a vitural port.
17827  * @fc_hdr: pointer to a FC frame header.
17828  * @aborted: was the partially assembled receive sequence successfully aborted
17829  *
17830  * This function sends a basic response to a previous unsol sequence abort
17831  * event after aborting the sequence handling.
17832  **/
17833 void
17834 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
17835 			struct fc_frame_header *fc_hdr, bool aborted)
17836 {
17837 	struct lpfc_hba *phba = vport->phba;
17838 	struct lpfc_iocbq *ctiocb = NULL;
17839 	struct lpfc_nodelist *ndlp;
17840 	uint16_t oxid, rxid, xri, lxri;
17841 	uint32_t sid, fctl;
17842 	IOCB_t *icmd;
17843 	int rc;
17844 
17845 	if (!lpfc_is_link_up(phba))
17846 		return;
17847 
17848 	sid = sli4_sid_from_fc_hdr(fc_hdr);
17849 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
17850 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
17851 
17852 	ndlp = lpfc_findnode_did(vport, sid);
17853 	if (!ndlp) {
17854 		ndlp = lpfc_nlp_init(vport, sid);
17855 		if (!ndlp) {
17856 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
17857 					 "1268 Failed to allocate ndlp for "
17858 					 "oxid:x%x SID:x%x\n", oxid, sid);
17859 			return;
17860 		}
17861 		/* Put ndlp onto pport node list */
17862 		lpfc_enqueue_node(vport, ndlp);
17863 	} else if (!NLP_CHK_NODE_ACT(ndlp)) {
17864 		/* re-setup ndlp without removing from node list */
17865 		ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
17866 		if (!ndlp) {
17867 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
17868 					 "3275 Failed to active ndlp found "
17869 					 "for oxid:x%x SID:x%x\n", oxid, sid);
17870 			return;
17871 		}
17872 	}
17873 
17874 	/* Allocate buffer for rsp iocb */
17875 	ctiocb = lpfc_sli_get_iocbq(phba);
17876 	if (!ctiocb)
17877 		return;
17878 
17879 	/* Extract the F_CTL field from FC_HDR */
17880 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
17881 
17882 	icmd = &ctiocb->iocb;
17883 	icmd->un.xseq64.bdl.bdeSize = 0;
17884 	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
17885 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
17886 	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
17887 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
17888 
17889 	/* Fill in the rest of iocb fields */
17890 	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
17891 	icmd->ulpBdeCount = 0;
17892 	icmd->ulpLe = 1;
17893 	icmd->ulpClass = CLASS3;
17894 	icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
17895 	ctiocb->context1 = lpfc_nlp_get(ndlp);
17896 
17897 	ctiocb->vport = phba->pport;
17898 	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
17899 	ctiocb->sli4_lxritag = NO_XRI;
17900 	ctiocb->sli4_xritag = NO_XRI;
17901 
17902 	if (fctl & FC_FC_EX_CTX)
17903 		/* Exchange responder sent the abort so we
17904 		 * own the oxid.
17905 		 */
17906 		xri = oxid;
17907 	else
17908 		xri = rxid;
17909 	lxri = lpfc_sli4_xri_inrange(phba, xri);
17910 	if (lxri != NO_XRI)
17911 		lpfc_set_rrq_active(phba, ndlp, lxri,
17912 			(xri == oxid) ? rxid : oxid, 0);
17913 	/* For BA_ABTS from exchange responder, if the logical xri with
17914 	 * the oxid maps to the FCP XRI range, the port no longer has
17915 	 * that exchange context, send a BLS_RJT. Override the IOCB for
17916 	 * a BA_RJT.
17917 	 */
17918 	if ((fctl & FC_FC_EX_CTX) &&
17919 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
17920 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
17921 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
17922 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
17923 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
17924 	}
17925 
17926 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
17927 	 * the driver no longer has that exchange, send a BLS_RJT. Override
17928 	 * the IOCB for a BA_RJT.
17929 	 */
17930 	if (aborted == false) {
17931 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
17932 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
17933 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
17934 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
17935 	}
17936 
17937 	if (fctl & FC_FC_EX_CTX) {
17938 		/* ABTS sent by responder to CT exchange, construction
17939 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
17940 		 * field and RX_ID from ABTS for RX_ID field.
17941 		 */
17942 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
17943 	} else {
17944 		/* ABTS sent by initiator to CT exchange, construction
17945 		 * of BA_ACC will need to allocate a new XRI as for the
17946 		 * XRI_TAG field.
17947 		 */
17948 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
17949 	}
17950 	bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
17951 	bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
17952 
17953 	/* Xmit CT abts response on exchange <xid> */
17954 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
17955 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
17956 			 icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
17957 
17958 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
17959 	if (rc == IOCB_ERROR) {
17960 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
17961 				 "2925 Failed to issue CT ABTS RSP x%x on "
17962 				 "xri x%x, Data x%x\n",
17963 				 icmd->un.xseq64.w5.hcsw.Rctl, oxid,
17964 				 phba->link_state);
17965 		lpfc_nlp_put(ndlp);
17966 		ctiocb->context1 = NULL;
17967 		lpfc_sli_release_iocbq(phba, ctiocb);
17968 	}
17969 }
17970 
17971 /**
17972  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
17973  * @vport: Pointer to the vport on which this sequence was received
17974  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17975  *
17976  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
17977  * receive sequence is only partially assembed by the driver, it shall abort
17978  * the partially assembled frames for the sequence. Otherwise, if the
17979  * unsolicited receive sequence has been completely assembled and passed to
17980  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
17981  * unsolicited sequence has been aborted. After that, it will issue a basic
17982  * accept to accept the abort.
17983  **/
17984 static void
17985 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
17986 			     struct hbq_dmabuf *dmabuf)
17987 {
17988 	struct lpfc_hba *phba = vport->phba;
17989 	struct fc_frame_header fc_hdr;
17990 	uint32_t fctl;
17991 	bool aborted;
17992 
17993 	/* Make a copy of fc_hdr before the dmabuf being released */
17994 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
17995 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
17996 
17997 	if (fctl & FC_FC_EX_CTX) {
17998 		/* ABTS by responder to exchange, no cleanup needed */
17999 		aborted = true;
18000 	} else {
18001 		/* ABTS by initiator to exchange, need to do cleanup */
18002 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
18003 		if (aborted == false)
18004 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
18005 	}
18006 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18007 
18008 	if (phba->nvmet_support) {
18009 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
18010 		return;
18011 	}
18012 
18013 	/* Respond with BA_ACC or BA_RJT accordingly */
18014 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
18015 }
18016 
18017 /**
18018  * lpfc_seq_complete - Indicates if a sequence is complete
18019  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18020  *
18021  * This function checks the sequence, starting with the frame described by
18022  * @dmabuf, to see if all the frames associated with this sequence are present.
18023  * the frames associated with this sequence are linked to the @dmabuf using the
18024  * dbuf list. This function looks for two major things. 1) That the first frame
18025  * has a sequence count of zero. 2) There is a frame with last frame of sequence
18026  * set. 3) That there are no holes in the sequence count. The function will
18027  * return 1 when the sequence is complete, otherwise it will return 0.
18028  **/
18029 static int
18030 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
18031 {
18032 	struct fc_frame_header *hdr;
18033 	struct lpfc_dmabuf *d_buf;
18034 	struct hbq_dmabuf *seq_dmabuf;
18035 	uint32_t fctl;
18036 	int seq_count = 0;
18037 
18038 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18039 	/* make sure first fame of sequence has a sequence count of zero */
18040 	if (hdr->fh_seq_cnt != seq_count)
18041 		return 0;
18042 	fctl = (hdr->fh_f_ctl[0] << 16 |
18043 		hdr->fh_f_ctl[1] << 8 |
18044 		hdr->fh_f_ctl[2]);
18045 	/* If last frame of sequence we can return success. */
18046 	if (fctl & FC_FC_END_SEQ)
18047 		return 1;
18048 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
18049 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18050 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18051 		/* If there is a hole in the sequence count then fail. */
18052 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
18053 			return 0;
18054 		fctl = (hdr->fh_f_ctl[0] << 16 |
18055 			hdr->fh_f_ctl[1] << 8 |
18056 			hdr->fh_f_ctl[2]);
18057 		/* If last frame of sequence we can return success. */
18058 		if (fctl & FC_FC_END_SEQ)
18059 			return 1;
18060 	}
18061 	return 0;
18062 }
18063 
18064 /**
18065  * lpfc_prep_seq - Prep sequence for ULP processing
18066  * @vport: Pointer to the vport on which this sequence was received
18067  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
18068  *
18069  * This function takes a sequence, described by a list of frames, and creates
18070  * a list of iocbq structures to describe the sequence. This iocbq list will be
18071  * used to issue to the generic unsolicited sequence handler. This routine
18072  * returns a pointer to the first iocbq in the list. If the function is unable
18073  * to allocate an iocbq then it throw out the received frames that were not
18074  * able to be described and return a pointer to the first iocbq. If unable to
18075  * allocate any iocbqs (including the first) this function will return NULL.
18076  **/
18077 static struct lpfc_iocbq *
18078 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
18079 {
18080 	struct hbq_dmabuf *hbq_buf;
18081 	struct lpfc_dmabuf *d_buf, *n_buf;
18082 	struct lpfc_iocbq *first_iocbq, *iocbq;
18083 	struct fc_frame_header *fc_hdr;
18084 	uint32_t sid;
18085 	uint32_t len, tot_len;
18086 	struct ulp_bde64 *pbde;
18087 
18088 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18089 	/* remove from receive buffer list */
18090 	list_del_init(&seq_dmabuf->hbuf.list);
18091 	lpfc_update_rcv_time_stamp(vport);
18092 	/* get the Remote Port's SID */
18093 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18094 	tot_len = 0;
18095 	/* Get an iocbq struct to fill in. */
18096 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
18097 	if (first_iocbq) {
18098 		/* Initialize the first IOCB. */
18099 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
18100 		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
18101 		first_iocbq->vport = vport;
18102 
18103 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
18104 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
18105 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
18106 			first_iocbq->iocb.un.rcvels.parmRo =
18107 				sli4_did_from_fc_hdr(fc_hdr);
18108 			first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
18109 		} else
18110 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
18111 		first_iocbq->iocb.ulpContext = NO_XRI;
18112 		first_iocbq->iocb.unsli3.rcvsli3.ox_id =
18113 			be16_to_cpu(fc_hdr->fh_ox_id);
18114 		/* iocbq is prepped for internal consumption.  Physical vpi. */
18115 		first_iocbq->iocb.unsli3.rcvsli3.vpi =
18116 			vport->phba->vpi_ids[vport->vpi];
18117 		/* put the first buffer into the first IOCBq */
18118 		tot_len = bf_get(lpfc_rcqe_length,
18119 				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
18120 
18121 		first_iocbq->context2 = &seq_dmabuf->dbuf;
18122 		first_iocbq->context3 = NULL;
18123 		first_iocbq->iocb.ulpBdeCount = 1;
18124 		if (tot_len > LPFC_DATA_BUF_SIZE)
18125 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
18126 							LPFC_DATA_BUF_SIZE;
18127 		else
18128 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
18129 
18130 		first_iocbq->iocb.un.rcvels.remoteID = sid;
18131 
18132 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
18133 	}
18134 	iocbq = first_iocbq;
18135 	/*
18136 	 * Each IOCBq can have two Buffers assigned, so go through the list
18137 	 * of buffers for this sequence and save two buffers in each IOCBq
18138 	 */
18139 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
18140 		if (!iocbq) {
18141 			lpfc_in_buf_free(vport->phba, d_buf);
18142 			continue;
18143 		}
18144 		if (!iocbq->context3) {
18145 			iocbq->context3 = d_buf;
18146 			iocbq->iocb.ulpBdeCount++;
18147 			/* We need to get the size out of the right CQE */
18148 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18149 			len = bf_get(lpfc_rcqe_length,
18150 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
18151 			pbde = (struct ulp_bde64 *)
18152 					&iocbq->iocb.unsli3.sli3Words[4];
18153 			if (len > LPFC_DATA_BUF_SIZE)
18154 				pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
18155 			else
18156 				pbde->tus.f.bdeSize = len;
18157 
18158 			iocbq->iocb.unsli3.rcvsli3.acc_len += len;
18159 			tot_len += len;
18160 		} else {
18161 			iocbq = lpfc_sli_get_iocbq(vport->phba);
18162 			if (!iocbq) {
18163 				if (first_iocbq) {
18164 					first_iocbq->iocb.ulpStatus =
18165 							IOSTAT_FCP_RSP_ERROR;
18166 					first_iocbq->iocb.un.ulpWord[4] =
18167 							IOERR_NO_RESOURCES;
18168 				}
18169 				lpfc_in_buf_free(vport->phba, d_buf);
18170 				continue;
18171 			}
18172 			/* We need to get the size out of the right CQE */
18173 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18174 			len = bf_get(lpfc_rcqe_length,
18175 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
18176 			iocbq->context2 = d_buf;
18177 			iocbq->context3 = NULL;
18178 			iocbq->iocb.ulpBdeCount = 1;
18179 			if (len > LPFC_DATA_BUF_SIZE)
18180 				iocbq->iocb.un.cont64[0].tus.f.bdeSize =
18181 							LPFC_DATA_BUF_SIZE;
18182 			else
18183 				iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
18184 
18185 			tot_len += len;
18186 			iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
18187 
18188 			iocbq->iocb.un.rcvels.remoteID = sid;
18189 			list_add_tail(&iocbq->list, &first_iocbq->list);
18190 		}
18191 	}
18192 	/* Free the sequence's header buffer */
18193 	if (!first_iocbq)
18194 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
18195 
18196 	return first_iocbq;
18197 }
18198 
18199 static void
18200 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
18201 			  struct hbq_dmabuf *seq_dmabuf)
18202 {
18203 	struct fc_frame_header *fc_hdr;
18204 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
18205 	struct lpfc_hba *phba = vport->phba;
18206 
18207 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18208 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
18209 	if (!iocbq) {
18210 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18211 				"2707 Ring %d handler: Failed to allocate "
18212 				"iocb Rctl x%x Type x%x received\n",
18213 				LPFC_ELS_RING,
18214 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18215 		return;
18216 	}
18217 	if (!lpfc_complete_unsol_iocb(phba,
18218 				      phba->sli4_hba.els_wq->pring,
18219 				      iocbq, fc_hdr->fh_r_ctl,
18220 				      fc_hdr->fh_type))
18221 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18222 				"2540 Ring %d handler: unexpected Rctl "
18223 				"x%x Type x%x received\n",
18224 				LPFC_ELS_RING,
18225 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18226 
18227 	/* Free iocb created in lpfc_prep_seq */
18228 	list_for_each_entry_safe(curr_iocb, next_iocb,
18229 		&iocbq->list, list) {
18230 		list_del_init(&curr_iocb->list);
18231 		lpfc_sli_release_iocbq(phba, curr_iocb);
18232 	}
18233 	lpfc_sli_release_iocbq(phba, iocbq);
18234 }
18235 
18236 static void
18237 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
18238 			    struct lpfc_iocbq *rspiocb)
18239 {
18240 	struct lpfc_dmabuf *pcmd = cmdiocb->context2;
18241 
18242 	if (pcmd && pcmd->virt)
18243 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18244 	kfree(pcmd);
18245 	lpfc_sli_release_iocbq(phba, cmdiocb);
18246 	lpfc_drain_txq(phba);
18247 }
18248 
18249 static void
18250 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
18251 			      struct hbq_dmabuf *dmabuf)
18252 {
18253 	struct fc_frame_header *fc_hdr;
18254 	struct lpfc_hba *phba = vport->phba;
18255 	struct lpfc_iocbq *iocbq = NULL;
18256 	union  lpfc_wqe *wqe;
18257 	struct lpfc_dmabuf *pcmd = NULL;
18258 	uint32_t frame_len;
18259 	int rc;
18260 	unsigned long iflags;
18261 
18262 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18263 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
18264 
18265 	/* Send the received frame back */
18266 	iocbq = lpfc_sli_get_iocbq(phba);
18267 	if (!iocbq) {
18268 		/* Queue cq event and wakeup worker thread to process it */
18269 		spin_lock_irqsave(&phba->hbalock, iflags);
18270 		list_add_tail(&dmabuf->cq_event.list,
18271 			      &phba->sli4_hba.sp_queue_event);
18272 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
18273 		spin_unlock_irqrestore(&phba->hbalock, iflags);
18274 		lpfc_worker_wake_up(phba);
18275 		return;
18276 	}
18277 
18278 	/* Allocate buffer for command payload */
18279 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
18280 	if (pcmd)
18281 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
18282 					    &pcmd->phys);
18283 	if (!pcmd || !pcmd->virt)
18284 		goto exit;
18285 
18286 	INIT_LIST_HEAD(&pcmd->list);
18287 
18288 	/* copyin the payload */
18289 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
18290 
18291 	/* fill in BDE's for command */
18292 	iocbq->iocb.un.xseq64.bdl.addrHigh = putPaddrHigh(pcmd->phys);
18293 	iocbq->iocb.un.xseq64.bdl.addrLow = putPaddrLow(pcmd->phys);
18294 	iocbq->iocb.un.xseq64.bdl.bdeFlags = BUFF_TYPE_BDE_64;
18295 	iocbq->iocb.un.xseq64.bdl.bdeSize = frame_len;
18296 
18297 	iocbq->context2 = pcmd;
18298 	iocbq->vport = vport;
18299 	iocbq->iocb_flag &= ~LPFC_FIP_ELS_ID_MASK;
18300 	iocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
18301 
18302 	/*
18303 	 * Setup rest of the iocb as though it were a WQE
18304 	 * Build the SEND_FRAME WQE
18305 	 */
18306 	wqe = (union lpfc_wqe *)&iocbq->iocb;
18307 
18308 	wqe->send_frame.frame_len = frame_len;
18309 	wqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((uint32_t *)fc_hdr));
18310 	wqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((uint32_t *)fc_hdr + 1));
18311 	wqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((uint32_t *)fc_hdr + 2));
18312 	wqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((uint32_t *)fc_hdr + 3));
18313 	wqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((uint32_t *)fc_hdr + 4));
18314 	wqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((uint32_t *)fc_hdr + 5));
18315 
18316 	iocbq->iocb.ulpCommand = CMD_SEND_FRAME;
18317 	iocbq->iocb.ulpLe = 1;
18318 	iocbq->iocb_cmpl = lpfc_sli4_mds_loopback_cmpl;
18319 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
18320 	if (rc == IOCB_ERROR)
18321 		goto exit;
18322 
18323 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18324 	return;
18325 
18326 exit:
18327 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18328 			"2023 Unable to process MDS loopback frame\n");
18329 	if (pcmd && pcmd->virt)
18330 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18331 	kfree(pcmd);
18332 	if (iocbq)
18333 		lpfc_sli_release_iocbq(phba, iocbq);
18334 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18335 }
18336 
18337 /**
18338  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
18339  * @phba: Pointer to HBA context object.
18340  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
18341  *
18342  * This function is called with no lock held. This function processes all
18343  * the received buffers and gives it to upper layers when a received buffer
18344  * indicates that it is the final frame in the sequence. The interrupt
18345  * service routine processes received buffers at interrupt contexts.
18346  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
18347  * appropriate receive function when the final frame in a sequence is received.
18348  **/
18349 void
18350 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
18351 				 struct hbq_dmabuf *dmabuf)
18352 {
18353 	struct hbq_dmabuf *seq_dmabuf;
18354 	struct fc_frame_header *fc_hdr;
18355 	struct lpfc_vport *vport;
18356 	uint32_t fcfi;
18357 	uint32_t did;
18358 
18359 	/* Process each received buffer */
18360 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18361 
18362 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
18363 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
18364 		vport = phba->pport;
18365 		/* Handle MDS Loopback frames */
18366 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18367 		return;
18368 	}
18369 
18370 	/* check to see if this a valid type of frame */
18371 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
18372 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18373 		return;
18374 	}
18375 
18376 	if ((bf_get(lpfc_cqe_code,
18377 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
18378 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
18379 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
18380 	else
18381 		fcfi = bf_get(lpfc_rcqe_fcf_id,
18382 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
18383 
18384 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
18385 		vport = phba->pport;
18386 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
18387 				"2023 MDS Loopback %d bytes\n",
18388 				bf_get(lpfc_rcqe_length,
18389 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
18390 		/* Handle MDS Loopback frames */
18391 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18392 		return;
18393 	}
18394 
18395 	/* d_id this frame is directed to */
18396 	did = sli4_did_from_fc_hdr(fc_hdr);
18397 
18398 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
18399 	if (!vport) {
18400 		/* throw out the frame */
18401 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18402 		return;
18403 	}
18404 
18405 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
18406 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
18407 		(did != Fabric_DID)) {
18408 		/*
18409 		 * Throw out the frame if we are not pt2pt.
18410 		 * The pt2pt protocol allows for discovery frames
18411 		 * to be received without a registered VPI.
18412 		 */
18413 		if (!(vport->fc_flag & FC_PT2PT) ||
18414 			(phba->link_state == LPFC_HBA_READY)) {
18415 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
18416 			return;
18417 		}
18418 	}
18419 
18420 	/* Handle the basic abort sequence (BA_ABTS) event */
18421 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
18422 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
18423 		return;
18424 	}
18425 
18426 	/* Link this frame */
18427 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
18428 	if (!seq_dmabuf) {
18429 		/* unable to add frame to vport - throw it out */
18430 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18431 		return;
18432 	}
18433 	/* If not last frame in sequence continue processing frames. */
18434 	if (!lpfc_seq_complete(seq_dmabuf))
18435 		return;
18436 
18437 	/* Send the complete sequence to the upper layer protocol */
18438 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
18439 }
18440 
18441 /**
18442  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
18443  * @phba: pointer to lpfc hba data structure.
18444  *
18445  * This routine is invoked to post rpi header templates to the
18446  * HBA consistent with the SLI-4 interface spec.  This routine
18447  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18448  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18449  *
18450  * This routine does not require any locks.  It's usage is expected
18451  * to be driver load or reset recovery when the driver is
18452  * sequential.
18453  *
18454  * Return codes
18455  * 	0 - successful
18456  *      -EIO - The mailbox failed to complete successfully.
18457  * 	When this error occurs, the driver is not guaranteed
18458  *	to have any rpi regions posted to the device and
18459  *	must either attempt to repost the regions or take a
18460  *	fatal error.
18461  **/
18462 int
18463 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
18464 {
18465 	struct lpfc_rpi_hdr *rpi_page;
18466 	uint32_t rc = 0;
18467 	uint16_t lrpi = 0;
18468 
18469 	/* SLI4 ports that support extents do not require RPI headers. */
18470 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18471 		goto exit;
18472 	if (phba->sli4_hba.extents_in_use)
18473 		return -EIO;
18474 
18475 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
18476 		/*
18477 		 * Assign the rpi headers a physical rpi only if the driver
18478 		 * has not initialized those resources.  A port reset only
18479 		 * needs the headers posted.
18480 		 */
18481 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
18482 		    LPFC_RPI_RSRC_RDY)
18483 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18484 
18485 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
18486 		if (rc != MBX_SUCCESS) {
18487 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18488 					"2008 Error %d posting all rpi "
18489 					"headers\n", rc);
18490 			rc = -EIO;
18491 			break;
18492 		}
18493 	}
18494 
18495  exit:
18496 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
18497 	       LPFC_RPI_RSRC_RDY);
18498 	return rc;
18499 }
18500 
18501 /**
18502  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
18503  * @phba: pointer to lpfc hba data structure.
18504  * @rpi_page:  pointer to the rpi memory region.
18505  *
18506  * This routine is invoked to post a single rpi header to the
18507  * HBA consistent with the SLI-4 interface spec.  This memory region
18508  * maps up to 64 rpi context regions.
18509  *
18510  * Return codes
18511  * 	0 - successful
18512  * 	-ENOMEM - No available memory
18513  *      -EIO - The mailbox failed to complete successfully.
18514  **/
18515 int
18516 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
18517 {
18518 	LPFC_MBOXQ_t *mboxq;
18519 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
18520 	uint32_t rc = 0;
18521 	uint32_t shdr_status, shdr_add_status;
18522 	union lpfc_sli4_cfg_shdr *shdr;
18523 
18524 	/* SLI4 ports that support extents do not require RPI headers. */
18525 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18526 		return rc;
18527 	if (phba->sli4_hba.extents_in_use)
18528 		return -EIO;
18529 
18530 	/* The port is notified of the header region via a mailbox command. */
18531 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18532 	if (!mboxq) {
18533 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18534 				"2001 Unable to allocate memory for issuing "
18535 				"SLI_CONFIG_SPECIAL mailbox command\n");
18536 		return -ENOMEM;
18537 	}
18538 
18539 	/* Post all rpi memory regions to the port. */
18540 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
18541 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
18542 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
18543 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
18544 			 sizeof(struct lpfc_sli4_cfg_mhdr),
18545 			 LPFC_SLI4_MBX_EMBED);
18546 
18547 
18548 	/* Post the physical rpi to the port for this rpi header. */
18549 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
18550 	       rpi_page->start_rpi);
18551 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
18552 	       hdr_tmpl, rpi_page->page_count);
18553 
18554 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
18555 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
18556 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
18557 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
18558 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18559 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18560 	if (rc != MBX_TIMEOUT)
18561 		mempool_free(mboxq, phba->mbox_mem_pool);
18562 	if (shdr_status || shdr_add_status || rc) {
18563 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18564 				"2514 POST_RPI_HDR mailbox failed with "
18565 				"status x%x add_status x%x, mbx status x%x\n",
18566 				shdr_status, shdr_add_status, rc);
18567 		rc = -ENXIO;
18568 	} else {
18569 		/*
18570 		 * The next_rpi stores the next logical module-64 rpi value used
18571 		 * to post physical rpis in subsequent rpi postings.
18572 		 */
18573 		spin_lock_irq(&phba->hbalock);
18574 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
18575 		spin_unlock_irq(&phba->hbalock);
18576 	}
18577 	return rc;
18578 }
18579 
18580 /**
18581  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
18582  * @phba: pointer to lpfc hba data structure.
18583  *
18584  * This routine is invoked to post rpi header templates to the
18585  * HBA consistent with the SLI-4 interface spec.  This routine
18586  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18587  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18588  *
18589  * Returns
18590  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
18591  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
18592  **/
18593 int
18594 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
18595 {
18596 	unsigned long rpi;
18597 	uint16_t max_rpi, rpi_limit;
18598 	uint16_t rpi_remaining, lrpi = 0;
18599 	struct lpfc_rpi_hdr *rpi_hdr;
18600 	unsigned long iflag;
18601 
18602 	/*
18603 	 * Fetch the next logical rpi.  Because this index is logical,
18604 	 * the  driver starts at 0 each time.
18605 	 */
18606 	spin_lock_irqsave(&phba->hbalock, iflag);
18607 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
18608 	rpi_limit = phba->sli4_hba.next_rpi;
18609 
18610 	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
18611 	if (rpi >= rpi_limit)
18612 		rpi = LPFC_RPI_ALLOC_ERROR;
18613 	else {
18614 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
18615 		phba->sli4_hba.max_cfg_param.rpi_used++;
18616 		phba->sli4_hba.rpi_count++;
18617 	}
18618 	lpfc_printf_log(phba, KERN_INFO,
18619 			LOG_NODE | LOG_DISCOVERY,
18620 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
18621 			(int) rpi, max_rpi, rpi_limit);
18622 
18623 	/*
18624 	 * Don't try to allocate more rpi header regions if the device limit
18625 	 * has been exhausted.
18626 	 */
18627 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
18628 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
18629 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18630 		return rpi;
18631 	}
18632 
18633 	/*
18634 	 * RPI header postings are not required for SLI4 ports capable of
18635 	 * extents.
18636 	 */
18637 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
18638 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18639 		return rpi;
18640 	}
18641 
18642 	/*
18643 	 * If the driver is running low on rpi resources, allocate another
18644 	 * page now.  Note that the next_rpi value is used because
18645 	 * it represents how many are actually in use whereas max_rpi notes
18646 	 * how many are supported max by the device.
18647 	 */
18648 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
18649 	spin_unlock_irqrestore(&phba->hbalock, iflag);
18650 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
18651 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
18652 		if (!rpi_hdr) {
18653 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18654 					"2002 Error Could not grow rpi "
18655 					"count\n");
18656 		} else {
18657 			lrpi = rpi_hdr->start_rpi;
18658 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18659 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
18660 		}
18661 	}
18662 
18663 	return rpi;
18664 }
18665 
18666 /**
18667  * lpfc_sli4_free_rpi - Release an rpi for reuse.
18668  * @phba: pointer to lpfc hba data structure.
18669  * @rpi: rpi to free
18670  *
18671  * This routine is invoked to release an rpi to the pool of
18672  * available rpis maintained by the driver.
18673  **/
18674 static void
18675 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
18676 {
18677 	/*
18678 	 * if the rpi value indicates a prior unreg has already
18679 	 * been done, skip the unreg.
18680 	 */
18681 	if (rpi == LPFC_RPI_ALLOC_ERROR)
18682 		return;
18683 
18684 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
18685 		phba->sli4_hba.rpi_count--;
18686 		phba->sli4_hba.max_cfg_param.rpi_used--;
18687 	} else {
18688 		lpfc_printf_log(phba, KERN_INFO,
18689 				LOG_NODE | LOG_DISCOVERY,
18690 				"2016 rpi %x not inuse\n",
18691 				rpi);
18692 	}
18693 }
18694 
18695 /**
18696  * lpfc_sli4_free_rpi - Release an rpi for reuse.
18697  * @phba: pointer to lpfc hba data structure.
18698  * @rpi: rpi to free
18699  *
18700  * This routine is invoked to release an rpi to the pool of
18701  * available rpis maintained by the driver.
18702  **/
18703 void
18704 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
18705 {
18706 	spin_lock_irq(&phba->hbalock);
18707 	__lpfc_sli4_free_rpi(phba, rpi);
18708 	spin_unlock_irq(&phba->hbalock);
18709 }
18710 
18711 /**
18712  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
18713  * @phba: pointer to lpfc hba data structure.
18714  *
18715  * This routine is invoked to remove the memory region that
18716  * provided rpi via a bitmask.
18717  **/
18718 void
18719 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
18720 {
18721 	kfree(phba->sli4_hba.rpi_bmask);
18722 	kfree(phba->sli4_hba.rpi_ids);
18723 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
18724 }
18725 
18726 /**
18727  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
18728  * @ndlp: pointer to lpfc nodelist data structure.
18729  * @cmpl: completion call-back.
18730  * @arg: data to load as MBox 'caller buffer information'
18731  *
18732  * This routine is invoked to remove the memory region that
18733  * provided rpi via a bitmask.
18734  **/
18735 int
18736 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
18737 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
18738 {
18739 	LPFC_MBOXQ_t *mboxq;
18740 	struct lpfc_hba *phba = ndlp->phba;
18741 	int rc;
18742 
18743 	/* The port is notified of the header region via a mailbox command. */
18744 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18745 	if (!mboxq)
18746 		return -ENOMEM;
18747 
18748 	/* Post all rpi memory regions to the port. */
18749 	lpfc_resume_rpi(mboxq, ndlp);
18750 	if (cmpl) {
18751 		mboxq->mbox_cmpl = cmpl;
18752 		mboxq->ctx_buf = arg;
18753 		mboxq->ctx_ndlp = ndlp;
18754 	} else
18755 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
18756 	mboxq->vport = ndlp->vport;
18757 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18758 	if (rc == MBX_NOT_FINISHED) {
18759 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18760 				"2010 Resume RPI Mailbox failed "
18761 				"status %d, mbxStatus x%x\n", rc,
18762 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
18763 		mempool_free(mboxq, phba->mbox_mem_pool);
18764 		return -EIO;
18765 	}
18766 	return 0;
18767 }
18768 
18769 /**
18770  * lpfc_sli4_init_vpi - Initialize a vpi with the port
18771  * @vport: Pointer to the vport for which the vpi is being initialized
18772  *
18773  * This routine is invoked to activate a vpi with the port.
18774  *
18775  * Returns:
18776  *    0 success
18777  *    -Evalue otherwise
18778  **/
18779 int
18780 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
18781 {
18782 	LPFC_MBOXQ_t *mboxq;
18783 	int rc = 0;
18784 	int retval = MBX_SUCCESS;
18785 	uint32_t mbox_tmo;
18786 	struct lpfc_hba *phba = vport->phba;
18787 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18788 	if (!mboxq)
18789 		return -ENOMEM;
18790 	lpfc_init_vpi(phba, mboxq, vport->vpi);
18791 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
18792 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
18793 	if (rc != MBX_SUCCESS) {
18794 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
18795 				"2022 INIT VPI Mailbox failed "
18796 				"status %d, mbxStatus x%x\n", rc,
18797 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
18798 		retval = -EIO;
18799 	}
18800 	if (rc != MBX_TIMEOUT)
18801 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
18802 
18803 	return retval;
18804 }
18805 
18806 /**
18807  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
18808  * @phba: pointer to lpfc hba data structure.
18809  * @mboxq: Pointer to mailbox object.
18810  *
18811  * This routine is invoked to manually add a single FCF record. The caller
18812  * must pass a completely initialized FCF_Record.  This routine takes
18813  * care of the nonembedded mailbox operations.
18814  **/
18815 static void
18816 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
18817 {
18818 	void *virt_addr;
18819 	union lpfc_sli4_cfg_shdr *shdr;
18820 	uint32_t shdr_status, shdr_add_status;
18821 
18822 	virt_addr = mboxq->sge_array->addr[0];
18823 	/* The IOCTL status is embedded in the mailbox subheader. */
18824 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
18825 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18826 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18827 
18828 	if ((shdr_status || shdr_add_status) &&
18829 		(shdr_status != STATUS_FCF_IN_USE))
18830 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18831 			"2558 ADD_FCF_RECORD mailbox failed with "
18832 			"status x%x add_status x%x\n",
18833 			shdr_status, shdr_add_status);
18834 
18835 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
18836 }
18837 
18838 /**
18839  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
18840  * @phba: pointer to lpfc hba data structure.
18841  * @fcf_record:  pointer to the initialized fcf record to add.
18842  *
18843  * This routine is invoked to manually add a single FCF record. The caller
18844  * must pass a completely initialized FCF_Record.  This routine takes
18845  * care of the nonembedded mailbox operations.
18846  **/
18847 int
18848 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
18849 {
18850 	int rc = 0;
18851 	LPFC_MBOXQ_t *mboxq;
18852 	uint8_t *bytep;
18853 	void *virt_addr;
18854 	struct lpfc_mbx_sge sge;
18855 	uint32_t alloc_len, req_len;
18856 	uint32_t fcfindex;
18857 
18858 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18859 	if (!mboxq) {
18860 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18861 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
18862 		return -ENOMEM;
18863 	}
18864 
18865 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
18866 		  sizeof(uint32_t);
18867 
18868 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18869 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
18870 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
18871 				     req_len, LPFC_SLI4_MBX_NEMBED);
18872 	if (alloc_len < req_len) {
18873 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18874 			"2523 Allocated DMA memory size (x%x) is "
18875 			"less than the requested DMA memory "
18876 			"size (x%x)\n", alloc_len, req_len);
18877 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18878 		return -ENOMEM;
18879 	}
18880 
18881 	/*
18882 	 * Get the first SGE entry from the non-embedded DMA memory.  This
18883 	 * routine only uses a single SGE.
18884 	 */
18885 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
18886 	virt_addr = mboxq->sge_array->addr[0];
18887 	/*
18888 	 * Configure the FCF record for FCFI 0.  This is the driver's
18889 	 * hardcoded default and gets used in nonFIP mode.
18890 	 */
18891 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
18892 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
18893 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
18894 
18895 	/*
18896 	 * Copy the fcf_index and the FCF Record Data. The data starts after
18897 	 * the FCoE header plus word10. The data copy needs to be endian
18898 	 * correct.
18899 	 */
18900 	bytep += sizeof(uint32_t);
18901 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
18902 	mboxq->vport = phba->pport;
18903 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
18904 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18905 	if (rc == MBX_NOT_FINISHED) {
18906 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18907 			"2515 ADD_FCF_RECORD mailbox failed with "
18908 			"status 0x%x\n", rc);
18909 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18910 		rc = -EIO;
18911 	} else
18912 		rc = 0;
18913 
18914 	return rc;
18915 }
18916 
18917 /**
18918  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
18919  * @phba: pointer to lpfc hba data structure.
18920  * @fcf_record:  pointer to the fcf record to write the default data.
18921  * @fcf_index: FCF table entry index.
18922  *
18923  * This routine is invoked to build the driver's default FCF record.  The
18924  * values used are hardcoded.  This routine handles memory initialization.
18925  *
18926  **/
18927 void
18928 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
18929 				struct fcf_record *fcf_record,
18930 				uint16_t fcf_index)
18931 {
18932 	memset(fcf_record, 0, sizeof(struct fcf_record));
18933 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
18934 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
18935 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
18936 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
18937 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
18938 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
18939 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
18940 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
18941 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
18942 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
18943 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
18944 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
18945 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
18946 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
18947 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
18948 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
18949 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
18950 	/* Set the VLAN bit map */
18951 	if (phba->valid_vlan) {
18952 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
18953 			= 1 << (phba->vlan_id % 8);
18954 	}
18955 }
18956 
18957 /**
18958  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
18959  * @phba: pointer to lpfc hba data structure.
18960  * @fcf_index: FCF table entry offset.
18961  *
18962  * This routine is invoked to scan the entire FCF table by reading FCF
18963  * record and processing it one at a time starting from the @fcf_index
18964  * for initial FCF discovery or fast FCF failover rediscovery.
18965  *
18966  * Return 0 if the mailbox command is submitted successfully, none 0
18967  * otherwise.
18968  **/
18969 int
18970 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
18971 {
18972 	int rc = 0, error;
18973 	LPFC_MBOXQ_t *mboxq;
18974 
18975 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
18976 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
18977 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18978 	if (!mboxq) {
18979 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18980 				"2000 Failed to allocate mbox for "
18981 				"READ_FCF cmd\n");
18982 		error = -ENOMEM;
18983 		goto fail_fcf_scan;
18984 	}
18985 	/* Construct the read FCF record mailbox command */
18986 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
18987 	if (rc) {
18988 		error = -EINVAL;
18989 		goto fail_fcf_scan;
18990 	}
18991 	/* Issue the mailbox command asynchronously */
18992 	mboxq->vport = phba->pport;
18993 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
18994 
18995 	spin_lock_irq(&phba->hbalock);
18996 	phba->hba_flag |= FCF_TS_INPROG;
18997 	spin_unlock_irq(&phba->hbalock);
18998 
18999 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19000 	if (rc == MBX_NOT_FINISHED)
19001 		error = -EIO;
19002 	else {
19003 		/* Reset eligible FCF count for new scan */
19004 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
19005 			phba->fcf.eligible_fcf_cnt = 0;
19006 		error = 0;
19007 	}
19008 fail_fcf_scan:
19009 	if (error) {
19010 		if (mboxq)
19011 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
19012 		/* FCF scan failed, clear FCF_TS_INPROG flag */
19013 		spin_lock_irq(&phba->hbalock);
19014 		phba->hba_flag &= ~FCF_TS_INPROG;
19015 		spin_unlock_irq(&phba->hbalock);
19016 	}
19017 	return error;
19018 }
19019 
19020 /**
19021  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
19022  * @phba: pointer to lpfc hba data structure.
19023  * @fcf_index: FCF table entry offset.
19024  *
19025  * This routine is invoked to read an FCF record indicated by @fcf_index
19026  * and to use it for FLOGI roundrobin FCF failover.
19027  *
19028  * Return 0 if the mailbox command is submitted successfully, none 0
19029  * otherwise.
19030  **/
19031 int
19032 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19033 {
19034 	int rc = 0, error;
19035 	LPFC_MBOXQ_t *mboxq;
19036 
19037 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19038 	if (!mboxq) {
19039 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
19040 				"2763 Failed to allocate mbox for "
19041 				"READ_FCF cmd\n");
19042 		error = -ENOMEM;
19043 		goto fail_fcf_read;
19044 	}
19045 	/* Construct the read FCF record mailbox command */
19046 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19047 	if (rc) {
19048 		error = -EINVAL;
19049 		goto fail_fcf_read;
19050 	}
19051 	/* Issue the mailbox command asynchronously */
19052 	mboxq->vport = phba->pport;
19053 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
19054 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19055 	if (rc == MBX_NOT_FINISHED)
19056 		error = -EIO;
19057 	else
19058 		error = 0;
19059 
19060 fail_fcf_read:
19061 	if (error && mboxq)
19062 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19063 	return error;
19064 }
19065 
19066 /**
19067  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
19068  * @phba: pointer to lpfc hba data structure.
19069  * @fcf_index: FCF table entry offset.
19070  *
19071  * This routine is invoked to read an FCF record indicated by @fcf_index to
19072  * determine whether it's eligible for FLOGI roundrobin failover list.
19073  *
19074  * Return 0 if the mailbox command is submitted successfully, none 0
19075  * otherwise.
19076  **/
19077 int
19078 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19079 {
19080 	int rc = 0, error;
19081 	LPFC_MBOXQ_t *mboxq;
19082 
19083 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19084 	if (!mboxq) {
19085 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
19086 				"2758 Failed to allocate mbox for "
19087 				"READ_FCF cmd\n");
19088 				error = -ENOMEM;
19089 				goto fail_fcf_read;
19090 	}
19091 	/* Construct the read FCF record mailbox command */
19092 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19093 	if (rc) {
19094 		error = -EINVAL;
19095 		goto fail_fcf_read;
19096 	}
19097 	/* Issue the mailbox command asynchronously */
19098 	mboxq->vport = phba->pport;
19099 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
19100 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19101 	if (rc == MBX_NOT_FINISHED)
19102 		error = -EIO;
19103 	else
19104 		error = 0;
19105 
19106 fail_fcf_read:
19107 	if (error && mboxq)
19108 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19109 	return error;
19110 }
19111 
19112 /**
19113  * lpfc_check_next_fcf_pri_level
19114  * @phba: pointer to the lpfc_hba struct for this port.
19115  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
19116  * routine when the rr_bmask is empty. The FCF indecies are put into the
19117  * rr_bmask based on their priority level. Starting from the highest priority
19118  * to the lowest. The most likely FCF candidate will be in the highest
19119  * priority group. When this routine is called it searches the fcf_pri list for
19120  * next lowest priority group and repopulates the rr_bmask with only those
19121  * fcf_indexes.
19122  * returns:
19123  * 1=success 0=failure
19124  **/
19125 static int
19126 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
19127 {
19128 	uint16_t next_fcf_pri;
19129 	uint16_t last_index;
19130 	struct lpfc_fcf_pri *fcf_pri;
19131 	int rc;
19132 	int ret = 0;
19133 
19134 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
19135 			LPFC_SLI4_FCF_TBL_INDX_MAX);
19136 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19137 			"3060 Last IDX %d\n", last_index);
19138 
19139 	/* Verify the priority list has 2 or more entries */
19140 	spin_lock_irq(&phba->hbalock);
19141 	if (list_empty(&phba->fcf.fcf_pri_list) ||
19142 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
19143 		spin_unlock_irq(&phba->hbalock);
19144 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19145 			"3061 Last IDX %d\n", last_index);
19146 		return 0; /* Empty rr list */
19147 	}
19148 	spin_unlock_irq(&phba->hbalock);
19149 
19150 	next_fcf_pri = 0;
19151 	/*
19152 	 * Clear the rr_bmask and set all of the bits that are at this
19153 	 * priority.
19154 	 */
19155 	memset(phba->fcf.fcf_rr_bmask, 0,
19156 			sizeof(*phba->fcf.fcf_rr_bmask));
19157 	spin_lock_irq(&phba->hbalock);
19158 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
19159 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
19160 			continue;
19161 		/*
19162 		 * the 1st priority that has not FLOGI failed
19163 		 * will be the highest.
19164 		 */
19165 		if (!next_fcf_pri)
19166 			next_fcf_pri = fcf_pri->fcf_rec.priority;
19167 		spin_unlock_irq(&phba->hbalock);
19168 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
19169 			rc = lpfc_sli4_fcf_rr_index_set(phba,
19170 						fcf_pri->fcf_rec.fcf_index);
19171 			if (rc)
19172 				return 0;
19173 		}
19174 		spin_lock_irq(&phba->hbalock);
19175 	}
19176 	/*
19177 	 * if next_fcf_pri was not set above and the list is not empty then
19178 	 * we have failed flogis on all of them. So reset flogi failed
19179 	 * and start at the beginning.
19180 	 */
19181 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
19182 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
19183 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
19184 			/*
19185 			 * the 1st priority that has not FLOGI failed
19186 			 * will be the highest.
19187 			 */
19188 			if (!next_fcf_pri)
19189 				next_fcf_pri = fcf_pri->fcf_rec.priority;
19190 			spin_unlock_irq(&phba->hbalock);
19191 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
19192 				rc = lpfc_sli4_fcf_rr_index_set(phba,
19193 						fcf_pri->fcf_rec.fcf_index);
19194 				if (rc)
19195 					return 0;
19196 			}
19197 			spin_lock_irq(&phba->hbalock);
19198 		}
19199 	} else
19200 		ret = 1;
19201 	spin_unlock_irq(&phba->hbalock);
19202 
19203 	return ret;
19204 }
19205 /**
19206  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
19207  * @phba: pointer to lpfc hba data structure.
19208  *
19209  * This routine is to get the next eligible FCF record index in a round
19210  * robin fashion. If the next eligible FCF record index equals to the
19211  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
19212  * shall be returned, otherwise, the next eligible FCF record's index
19213  * shall be returned.
19214  **/
19215 uint16_t
19216 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
19217 {
19218 	uint16_t next_fcf_index;
19219 
19220 initial_priority:
19221 	/* Search start from next bit of currently registered FCF index */
19222 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
19223 
19224 next_priority:
19225 	/* Determine the next fcf index to check */
19226 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
19227 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
19228 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
19229 				       next_fcf_index);
19230 
19231 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
19232 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19233 		/*
19234 		 * If we have wrapped then we need to clear the bits that
19235 		 * have been tested so that we can detect when we should
19236 		 * change the priority level.
19237 		 */
19238 		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
19239 					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
19240 	}
19241 
19242 
19243 	/* Check roundrobin failover list empty condition */
19244 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
19245 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
19246 		/*
19247 		 * If next fcf index is not found check if there are lower
19248 		 * Priority level fcf's in the fcf_priority list.
19249 		 * Set up the rr_bmask with all of the avaiable fcf bits
19250 		 * at that level and continue the selection process.
19251 		 */
19252 		if (lpfc_check_next_fcf_pri_level(phba))
19253 			goto initial_priority;
19254 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
19255 				"2844 No roundrobin failover FCF available\n");
19256 
19257 		return LPFC_FCOE_FCF_NEXT_NONE;
19258 	}
19259 
19260 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
19261 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
19262 		LPFC_FCF_FLOGI_FAILED) {
19263 		if (list_is_singular(&phba->fcf.fcf_pri_list))
19264 			return LPFC_FCOE_FCF_NEXT_NONE;
19265 
19266 		goto next_priority;
19267 	}
19268 
19269 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19270 			"2845 Get next roundrobin failover FCF (x%x)\n",
19271 			next_fcf_index);
19272 
19273 	return next_fcf_index;
19274 }
19275 
19276 /**
19277  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
19278  * @phba: pointer to lpfc hba data structure.
19279  * @fcf_index: index into the FCF table to 'set'
19280  *
19281  * This routine sets the FCF record index in to the eligible bmask for
19282  * roundrobin failover search. It checks to make sure that the index
19283  * does not go beyond the range of the driver allocated bmask dimension
19284  * before setting the bit.
19285  *
19286  * Returns 0 if the index bit successfully set, otherwise, it returns
19287  * -EINVAL.
19288  **/
19289 int
19290 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
19291 {
19292 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19293 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19294 				"2610 FCF (x%x) reached driver's book "
19295 				"keeping dimension:x%x\n",
19296 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19297 		return -EINVAL;
19298 	}
19299 	/* Set the eligible FCF record index bmask */
19300 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19301 
19302 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19303 			"2790 Set FCF (x%x) to roundrobin FCF failover "
19304 			"bmask\n", fcf_index);
19305 
19306 	return 0;
19307 }
19308 
19309 /**
19310  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
19311  * @phba: pointer to lpfc hba data structure.
19312  * @fcf_index: index into the FCF table to 'clear'
19313  *
19314  * This routine clears the FCF record index from the eligible bmask for
19315  * roundrobin failover search. It checks to make sure that the index
19316  * does not go beyond the range of the driver allocated bmask dimension
19317  * before clearing the bit.
19318  **/
19319 void
19320 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
19321 {
19322 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
19323 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19324 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19325 				"2762 FCF (x%x) reached driver's book "
19326 				"keeping dimension:x%x\n",
19327 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19328 		return;
19329 	}
19330 	/* Clear the eligible FCF record index bmask */
19331 	spin_lock_irq(&phba->hbalock);
19332 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
19333 				 list) {
19334 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
19335 			list_del_init(&fcf_pri->list);
19336 			break;
19337 		}
19338 	}
19339 	spin_unlock_irq(&phba->hbalock);
19340 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19341 
19342 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19343 			"2791 Clear FCF (x%x) from roundrobin failover "
19344 			"bmask\n", fcf_index);
19345 }
19346 
19347 /**
19348  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
19349  * @phba: pointer to lpfc hba data structure.
19350  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
19351  *
19352  * This routine is the completion routine for the rediscover FCF table mailbox
19353  * command. If the mailbox command returned failure, it will try to stop the
19354  * FCF rediscover wait timer.
19355  **/
19356 static void
19357 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
19358 {
19359 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19360 	uint32_t shdr_status, shdr_add_status;
19361 
19362 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19363 
19364 	shdr_status = bf_get(lpfc_mbox_hdr_status,
19365 			     &redisc_fcf->header.cfg_shdr.response);
19366 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
19367 			     &redisc_fcf->header.cfg_shdr.response);
19368 	if (shdr_status || shdr_add_status) {
19369 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19370 				"2746 Requesting for FCF rediscovery failed "
19371 				"status x%x add_status x%x\n",
19372 				shdr_status, shdr_add_status);
19373 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
19374 			spin_lock_irq(&phba->hbalock);
19375 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
19376 			spin_unlock_irq(&phba->hbalock);
19377 			/*
19378 			 * CVL event triggered FCF rediscover request failed,
19379 			 * last resort to re-try current registered FCF entry.
19380 			 */
19381 			lpfc_retry_pport_discovery(phba);
19382 		} else {
19383 			spin_lock_irq(&phba->hbalock);
19384 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
19385 			spin_unlock_irq(&phba->hbalock);
19386 			/*
19387 			 * DEAD FCF event triggered FCF rediscover request
19388 			 * failed, last resort to fail over as a link down
19389 			 * to FCF registration.
19390 			 */
19391 			lpfc_sli4_fcf_dead_failthrough(phba);
19392 		}
19393 	} else {
19394 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19395 				"2775 Start FCF rediscover quiescent timer\n");
19396 		/*
19397 		 * Start FCF rediscovery wait timer for pending FCF
19398 		 * before rescan FCF record table.
19399 		 */
19400 		lpfc_fcf_redisc_wait_start_timer(phba);
19401 	}
19402 
19403 	mempool_free(mbox, phba->mbox_mem_pool);
19404 }
19405 
19406 /**
19407  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
19408  * @phba: pointer to lpfc hba data structure.
19409  *
19410  * This routine is invoked to request for rediscovery of the entire FCF table
19411  * by the port.
19412  **/
19413 int
19414 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
19415 {
19416 	LPFC_MBOXQ_t *mbox;
19417 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19418 	int rc, length;
19419 
19420 	/* Cancel retry delay timers to all vports before FCF rediscover */
19421 	lpfc_cancel_all_vport_retry_delay_timer(phba);
19422 
19423 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19424 	if (!mbox) {
19425 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19426 				"2745 Failed to allocate mbox for "
19427 				"requesting FCF rediscover.\n");
19428 		return -ENOMEM;
19429 	}
19430 
19431 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
19432 		  sizeof(struct lpfc_sli4_cfg_mhdr));
19433 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
19434 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
19435 			 length, LPFC_SLI4_MBX_EMBED);
19436 
19437 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19438 	/* Set count to 0 for invalidating the entire FCF database */
19439 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
19440 
19441 	/* Issue the mailbox command asynchronously */
19442 	mbox->vport = phba->pport;
19443 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
19444 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
19445 
19446 	if (rc == MBX_NOT_FINISHED) {
19447 		mempool_free(mbox, phba->mbox_mem_pool);
19448 		return -EIO;
19449 	}
19450 	return 0;
19451 }
19452 
19453 /**
19454  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
19455  * @phba: pointer to lpfc hba data structure.
19456  *
19457  * This function is the failover routine as a last resort to the FCF DEAD
19458  * event when driver failed to perform fast FCF failover.
19459  **/
19460 void
19461 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
19462 {
19463 	uint32_t link_state;
19464 
19465 	/*
19466 	 * Last resort as FCF DEAD event failover will treat this as
19467 	 * a link down, but save the link state because we don't want
19468 	 * it to be changed to Link Down unless it is already down.
19469 	 */
19470 	link_state = phba->link_state;
19471 	lpfc_linkdown(phba);
19472 	phba->link_state = link_state;
19473 
19474 	/* Unregister FCF if no devices connected to it */
19475 	lpfc_unregister_unused_fcf(phba);
19476 }
19477 
19478 /**
19479  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
19480  * @phba: pointer to lpfc hba data structure.
19481  * @rgn23_data: pointer to configure region 23 data.
19482  *
19483  * This function gets SLI3 port configure region 23 data through memory dump
19484  * mailbox command. When it successfully retrieves data, the size of the data
19485  * will be returned, otherwise, 0 will be returned.
19486  **/
19487 static uint32_t
19488 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19489 {
19490 	LPFC_MBOXQ_t *pmb = NULL;
19491 	MAILBOX_t *mb;
19492 	uint32_t offset = 0;
19493 	int i, rc;
19494 
19495 	if (!rgn23_data)
19496 		return 0;
19497 
19498 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19499 	if (!pmb) {
19500 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19501 				"2600 failed to allocate mailbox memory\n");
19502 		return 0;
19503 	}
19504 	mb = &pmb->u.mb;
19505 
19506 	do {
19507 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
19508 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
19509 
19510 		if (rc != MBX_SUCCESS) {
19511 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19512 					"2601 failed to read config "
19513 					"region 23, rc 0x%x Status 0x%x\n",
19514 					rc, mb->mbxStatus);
19515 			mb->un.varDmp.word_cnt = 0;
19516 		}
19517 		/*
19518 		 * dump mem may return a zero when finished or we got a
19519 		 * mailbox error, either way we are done.
19520 		 */
19521 		if (mb->un.varDmp.word_cnt == 0)
19522 			break;
19523 
19524 		i =  mb->un.varDmp.word_cnt * sizeof(uint32_t);
19525 		if (offset + i >  DMP_RGN23_SIZE)
19526 			i =  DMP_RGN23_SIZE - offset;
19527 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
19528 				      rgn23_data  + offset, i);
19529 		offset += i;
19530 	} while (offset < DMP_RGN23_SIZE);
19531 
19532 	mempool_free(pmb, phba->mbox_mem_pool);
19533 	return offset;
19534 }
19535 
19536 /**
19537  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
19538  * @phba: pointer to lpfc hba data structure.
19539  * @rgn23_data: pointer to configure region 23 data.
19540  *
19541  * This function gets SLI4 port configure region 23 data through memory dump
19542  * mailbox command. When it successfully retrieves data, the size of the data
19543  * will be returned, otherwise, 0 will be returned.
19544  **/
19545 static uint32_t
19546 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19547 {
19548 	LPFC_MBOXQ_t *mboxq = NULL;
19549 	struct lpfc_dmabuf *mp = NULL;
19550 	struct lpfc_mqe *mqe;
19551 	uint32_t data_length = 0;
19552 	int rc;
19553 
19554 	if (!rgn23_data)
19555 		return 0;
19556 
19557 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19558 	if (!mboxq) {
19559 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19560 				"3105 failed to allocate mailbox memory\n");
19561 		return 0;
19562 	}
19563 
19564 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
19565 		goto out;
19566 	mqe = &mboxq->u.mqe;
19567 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
19568 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19569 	if (rc)
19570 		goto out;
19571 	data_length = mqe->un.mb_words[5];
19572 	if (data_length == 0)
19573 		goto out;
19574 	if (data_length > DMP_RGN23_SIZE) {
19575 		data_length = 0;
19576 		goto out;
19577 	}
19578 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
19579 out:
19580 	mempool_free(mboxq, phba->mbox_mem_pool);
19581 	if (mp) {
19582 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
19583 		kfree(mp);
19584 	}
19585 	return data_length;
19586 }
19587 
19588 /**
19589  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
19590  * @phba: pointer to lpfc hba data structure.
19591  *
19592  * This function read region 23 and parse TLV for port status to
19593  * decide if the user disaled the port. If the TLV indicates the
19594  * port is disabled, the hba_flag is set accordingly.
19595  **/
19596 void
19597 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
19598 {
19599 	uint8_t *rgn23_data = NULL;
19600 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
19601 	uint32_t offset = 0;
19602 
19603 	/* Get adapter Region 23 data */
19604 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
19605 	if (!rgn23_data)
19606 		goto out;
19607 
19608 	if (phba->sli_rev < LPFC_SLI_REV4)
19609 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
19610 	else {
19611 		if_type = bf_get(lpfc_sli_intf_if_type,
19612 				 &phba->sli4_hba.sli_intf);
19613 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
19614 			goto out;
19615 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
19616 	}
19617 
19618 	if (!data_size)
19619 		goto out;
19620 
19621 	/* Check the region signature first */
19622 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
19623 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19624 			"2619 Config region 23 has bad signature\n");
19625 			goto out;
19626 	}
19627 	offset += 4;
19628 
19629 	/* Check the data structure version */
19630 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
19631 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19632 			"2620 Config region 23 has bad version\n");
19633 		goto out;
19634 	}
19635 	offset += 4;
19636 
19637 	/* Parse TLV entries in the region */
19638 	while (offset < data_size) {
19639 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
19640 			break;
19641 		/*
19642 		 * If the TLV is not driver specific TLV or driver id is
19643 		 * not linux driver id, skip the record.
19644 		 */
19645 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
19646 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
19647 		    (rgn23_data[offset + 3] != 0)) {
19648 			offset += rgn23_data[offset + 1] * 4 + 4;
19649 			continue;
19650 		}
19651 
19652 		/* Driver found a driver specific TLV in the config region */
19653 		sub_tlv_len = rgn23_data[offset + 1] * 4;
19654 		offset += 4;
19655 		tlv_offset = 0;
19656 
19657 		/*
19658 		 * Search for configured port state sub-TLV.
19659 		 */
19660 		while ((offset < data_size) &&
19661 			(tlv_offset < sub_tlv_len)) {
19662 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
19663 				offset += 4;
19664 				tlv_offset += 4;
19665 				break;
19666 			}
19667 			if (rgn23_data[offset] != PORT_STE_TYPE) {
19668 				offset += rgn23_data[offset + 1] * 4 + 4;
19669 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
19670 				continue;
19671 			}
19672 
19673 			/* This HBA contains PORT_STE configured */
19674 			if (!rgn23_data[offset + 2])
19675 				phba->hba_flag |= LINK_DISABLED;
19676 
19677 			goto out;
19678 		}
19679 	}
19680 
19681 out:
19682 	kfree(rgn23_data);
19683 	return;
19684 }
19685 
19686 /**
19687  * lpfc_wr_object - write an object to the firmware
19688  * @phba: HBA structure that indicates port to create a queue on.
19689  * @dmabuf_list: list of dmabufs to write to the port.
19690  * @size: the total byte value of the objects to write to the port.
19691  * @offset: the current offset to be used to start the transfer.
19692  *
19693  * This routine will create a wr_object mailbox command to send to the port.
19694  * the mailbox command will be constructed using the dma buffers described in
19695  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
19696  * BDEs that the imbedded mailbox can support. The @offset variable will be
19697  * used to indicate the starting offset of the transfer and will also return
19698  * the offset after the write object mailbox has completed. @size is used to
19699  * determine the end of the object and whether the eof bit should be set.
19700  *
19701  * Return 0 is successful and offset will contain the the new offset to use
19702  * for the next write.
19703  * Return negative value for error cases.
19704  **/
19705 int
19706 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
19707 	       uint32_t size, uint32_t *offset)
19708 {
19709 	struct lpfc_mbx_wr_object *wr_object;
19710 	LPFC_MBOXQ_t *mbox;
19711 	int rc = 0, i = 0;
19712 	uint32_t shdr_status, shdr_add_status, shdr_change_status, shdr_csf;
19713 	uint32_t mbox_tmo;
19714 	struct lpfc_dmabuf *dmabuf;
19715 	uint32_t written = 0;
19716 	bool check_change_status = false;
19717 
19718 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19719 	if (!mbox)
19720 		return -ENOMEM;
19721 
19722 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
19723 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
19724 			sizeof(struct lpfc_mbx_wr_object) -
19725 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
19726 
19727 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
19728 	wr_object->u.request.write_offset = *offset;
19729 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
19730 	wr_object->u.request.object_name[0] =
19731 		cpu_to_le32(wr_object->u.request.object_name[0]);
19732 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
19733 	list_for_each_entry(dmabuf, dmabuf_list, list) {
19734 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
19735 			break;
19736 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
19737 		wr_object->u.request.bde[i].addrHigh =
19738 			putPaddrHigh(dmabuf->phys);
19739 		if (written + SLI4_PAGE_SIZE >= size) {
19740 			wr_object->u.request.bde[i].tus.f.bdeSize =
19741 				(size - written);
19742 			written += (size - written);
19743 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
19744 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
19745 			check_change_status = true;
19746 		} else {
19747 			wr_object->u.request.bde[i].tus.f.bdeSize =
19748 				SLI4_PAGE_SIZE;
19749 			written += SLI4_PAGE_SIZE;
19750 		}
19751 		i++;
19752 	}
19753 	wr_object->u.request.bde_count = i;
19754 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
19755 	if (!phba->sli4_hba.intr_enable)
19756 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
19757 	else {
19758 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
19759 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
19760 	}
19761 	/* The IOCTL status is embedded in the mailbox subheader. */
19762 	shdr_status = bf_get(lpfc_mbox_hdr_status,
19763 			     &wr_object->header.cfg_shdr.response);
19764 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
19765 				 &wr_object->header.cfg_shdr.response);
19766 	if (check_change_status) {
19767 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
19768 					    &wr_object->u.response);
19769 
19770 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
19771 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
19772 			shdr_csf = bf_get(lpfc_wr_object_csf,
19773 					  &wr_object->u.response);
19774 			if (shdr_csf)
19775 				shdr_change_status =
19776 						   LPFC_CHANGE_STATUS_PCI_RESET;
19777 		}
19778 
19779 		switch (shdr_change_status) {
19780 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
19781 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19782 					"3198 Firmware write complete: System "
19783 					"reboot required to instantiate\n");
19784 			break;
19785 		case (LPFC_CHANGE_STATUS_FW_RESET):
19786 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19787 					"3199 Firmware write complete: Firmware"
19788 					" reset required to instantiate\n");
19789 			break;
19790 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
19791 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19792 					"3200 Firmware write complete: Port "
19793 					"Migration or PCI Reset required to "
19794 					"instantiate\n");
19795 			break;
19796 		case (LPFC_CHANGE_STATUS_PCI_RESET):
19797 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19798 					"3201 Firmware write complete: PCI "
19799 					"Reset required to instantiate\n");
19800 			break;
19801 		default:
19802 			break;
19803 		}
19804 	}
19805 	if (rc != MBX_TIMEOUT)
19806 		mempool_free(mbox, phba->mbox_mem_pool);
19807 	if (shdr_status || shdr_add_status || rc) {
19808 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19809 				"3025 Write Object mailbox failed with "
19810 				"status x%x add_status x%x, mbx status x%x\n",
19811 				shdr_status, shdr_add_status, rc);
19812 		rc = -ENXIO;
19813 		*offset = shdr_add_status;
19814 	} else
19815 		*offset += wr_object->u.response.actual_write_length;
19816 	return rc;
19817 }
19818 
19819 /**
19820  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
19821  * @vport: pointer to vport data structure.
19822  *
19823  * This function iterate through the mailboxq and clean up all REG_LOGIN
19824  * and REG_VPI mailbox commands associated with the vport. This function
19825  * is called when driver want to restart discovery of the vport due to
19826  * a Clear Virtual Link event.
19827  **/
19828 void
19829 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
19830 {
19831 	struct lpfc_hba *phba = vport->phba;
19832 	LPFC_MBOXQ_t *mb, *nextmb;
19833 	struct lpfc_dmabuf *mp;
19834 	struct lpfc_nodelist *ndlp;
19835 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
19836 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
19837 	LIST_HEAD(mbox_cmd_list);
19838 	uint8_t restart_loop;
19839 
19840 	/* Clean up internally queued mailbox commands with the vport */
19841 	spin_lock_irq(&phba->hbalock);
19842 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
19843 		if (mb->vport != vport)
19844 			continue;
19845 
19846 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
19847 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
19848 			continue;
19849 
19850 		list_del(&mb->list);
19851 		list_add_tail(&mb->list, &mbox_cmd_list);
19852 	}
19853 	/* Clean up active mailbox command with the vport */
19854 	mb = phba->sli.mbox_active;
19855 	if (mb && (mb->vport == vport)) {
19856 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
19857 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
19858 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19859 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19860 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19861 			/* Put reference count for delayed processing */
19862 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
19863 			/* Unregister the RPI when mailbox complete */
19864 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
19865 		}
19866 	}
19867 	/* Cleanup any mailbox completions which are not yet processed */
19868 	do {
19869 		restart_loop = 0;
19870 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
19871 			/*
19872 			 * If this mailox is already processed or it is
19873 			 * for another vport ignore it.
19874 			 */
19875 			if ((mb->vport != vport) ||
19876 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
19877 				continue;
19878 
19879 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
19880 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
19881 				continue;
19882 
19883 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19884 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19885 				ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19886 				/* Unregister the RPI when mailbox complete */
19887 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
19888 				restart_loop = 1;
19889 				spin_unlock_irq(&phba->hbalock);
19890 				spin_lock(shost->host_lock);
19891 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19892 				spin_unlock(shost->host_lock);
19893 				spin_lock_irq(&phba->hbalock);
19894 				break;
19895 			}
19896 		}
19897 	} while (restart_loop);
19898 
19899 	spin_unlock_irq(&phba->hbalock);
19900 
19901 	/* Release the cleaned-up mailbox commands */
19902 	while (!list_empty(&mbox_cmd_list)) {
19903 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
19904 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19905 			mp = (struct lpfc_dmabuf *)(mb->ctx_buf);
19906 			if (mp) {
19907 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
19908 				kfree(mp);
19909 			}
19910 			mb->ctx_buf = NULL;
19911 			ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19912 			mb->ctx_ndlp = NULL;
19913 			if (ndlp) {
19914 				spin_lock(shost->host_lock);
19915 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19916 				spin_unlock(shost->host_lock);
19917 				lpfc_nlp_put(ndlp);
19918 			}
19919 		}
19920 		mempool_free(mb, phba->mbox_mem_pool);
19921 	}
19922 
19923 	/* Release the ndlp with the cleaned-up active mailbox command */
19924 	if (act_mbx_ndlp) {
19925 		spin_lock(shost->host_lock);
19926 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19927 		spin_unlock(shost->host_lock);
19928 		lpfc_nlp_put(act_mbx_ndlp);
19929 	}
19930 }
19931 
19932 /**
19933  * lpfc_drain_txq - Drain the txq
19934  * @phba: Pointer to HBA context object.
19935  *
19936  * This function attempt to submit IOCBs on the txq
19937  * to the adapter.  For SLI4 adapters, the txq contains
19938  * ELS IOCBs that have been deferred because the there
19939  * are no SGLs.  This congestion can occur with large
19940  * vport counts during node discovery.
19941  **/
19942 
19943 uint32_t
19944 lpfc_drain_txq(struct lpfc_hba *phba)
19945 {
19946 	LIST_HEAD(completions);
19947 	struct lpfc_sli_ring *pring;
19948 	struct lpfc_iocbq *piocbq = NULL;
19949 	unsigned long iflags = 0;
19950 	char *fail_msg = NULL;
19951 	struct lpfc_sglq *sglq;
19952 	union lpfc_wqe128 wqe;
19953 	uint32_t txq_cnt = 0;
19954 	struct lpfc_queue *wq;
19955 
19956 	if (phba->link_flag & LS_MDS_LOOPBACK) {
19957 		/* MDS WQE are posted only to first WQ*/
19958 		wq = phba->sli4_hba.hdwq[0].io_wq;
19959 		if (unlikely(!wq))
19960 			return 0;
19961 		pring = wq->pring;
19962 	} else {
19963 		wq = phba->sli4_hba.els_wq;
19964 		if (unlikely(!wq))
19965 			return 0;
19966 		pring = lpfc_phba_elsring(phba);
19967 	}
19968 
19969 	if (unlikely(!pring) || list_empty(&pring->txq))
19970 		return 0;
19971 
19972 	spin_lock_irqsave(&pring->ring_lock, iflags);
19973 	list_for_each_entry(piocbq, &pring->txq, list) {
19974 		txq_cnt++;
19975 	}
19976 
19977 	if (txq_cnt > pring->txq_max)
19978 		pring->txq_max = txq_cnt;
19979 
19980 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
19981 
19982 	while (!list_empty(&pring->txq)) {
19983 		spin_lock_irqsave(&pring->ring_lock, iflags);
19984 
19985 		piocbq = lpfc_sli_ringtx_get(phba, pring);
19986 		if (!piocbq) {
19987 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19988 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19989 				"2823 txq empty and txq_cnt is %d\n ",
19990 				txq_cnt);
19991 			break;
19992 		}
19993 		sglq = __lpfc_sli_get_els_sglq(phba, piocbq);
19994 		if (!sglq) {
19995 			__lpfc_sli_ringtx_put(phba, pring, piocbq);
19996 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19997 			break;
19998 		}
19999 		txq_cnt--;
20000 
20001 		/* The xri and iocb resources secured,
20002 		 * attempt to issue request
20003 		 */
20004 		piocbq->sli4_lxritag = sglq->sli4_lxritag;
20005 		piocbq->sli4_xritag = sglq->sli4_xritag;
20006 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
20007 			fail_msg = "to convert bpl to sgl";
20008 		else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
20009 			fail_msg = "to convert iocb to wqe";
20010 		else if (lpfc_sli4_wq_put(wq, &wqe))
20011 			fail_msg = " - Wq is full";
20012 		else
20013 			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
20014 
20015 		if (fail_msg) {
20016 			/* Failed means we can't issue and need to cancel */
20017 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20018 					"2822 IOCB failed %s iotag 0x%x "
20019 					"xri 0x%x\n",
20020 					fail_msg,
20021 					piocbq->iotag, piocbq->sli4_xritag);
20022 			list_add_tail(&piocbq->list, &completions);
20023 		}
20024 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20025 	}
20026 
20027 	/* Cancel all the IOCBs that cannot be issued */
20028 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
20029 				IOERR_SLI_ABORTED);
20030 
20031 	return txq_cnt;
20032 }
20033 
20034 /**
20035  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
20036  * @phba: Pointer to HBA context object.
20037  * @pwqeq: Pointer to command WQE.
20038  * @sglq: Pointer to the scatter gather queue object.
20039  *
20040  * This routine converts the bpl or bde that is in the WQE
20041  * to a sgl list for the sli4 hardware. The physical address
20042  * of the bpl/bde is converted back to a virtual address.
20043  * If the WQE contains a BPL then the list of BDE's is
20044  * converted to sli4_sge's. If the WQE contains a single
20045  * BDE then it is converted to a single sli_sge.
20046  * The WQE is still in cpu endianness so the contents of
20047  * the bpl can be used without byte swapping.
20048  *
20049  * Returns valid XRI = Success, NO_XRI = Failure.
20050  */
20051 static uint16_t
20052 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
20053 		 struct lpfc_sglq *sglq)
20054 {
20055 	uint16_t xritag = NO_XRI;
20056 	struct ulp_bde64 *bpl = NULL;
20057 	struct ulp_bde64 bde;
20058 	struct sli4_sge *sgl  = NULL;
20059 	struct lpfc_dmabuf *dmabuf;
20060 	union lpfc_wqe128 *wqe;
20061 	int numBdes = 0;
20062 	int i = 0;
20063 	uint32_t offset = 0; /* accumulated offset in the sg request list */
20064 	int inbound = 0; /* number of sg reply entries inbound from firmware */
20065 	uint32_t cmd;
20066 
20067 	if (!pwqeq || !sglq)
20068 		return xritag;
20069 
20070 	sgl  = (struct sli4_sge *)sglq->sgl;
20071 	wqe = &pwqeq->wqe;
20072 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
20073 
20074 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
20075 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
20076 		return sglq->sli4_xritag;
20077 	numBdes = pwqeq->rsvd2;
20078 	if (numBdes) {
20079 		/* The addrHigh and addrLow fields within the WQE
20080 		 * have not been byteswapped yet so there is no
20081 		 * need to swap them back.
20082 		 */
20083 		if (pwqeq->context3)
20084 			dmabuf = (struct lpfc_dmabuf *)pwqeq->context3;
20085 		else
20086 			return xritag;
20087 
20088 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
20089 		if (!bpl)
20090 			return xritag;
20091 
20092 		for (i = 0; i < numBdes; i++) {
20093 			/* Should already be byte swapped. */
20094 			sgl->addr_hi = bpl->addrHigh;
20095 			sgl->addr_lo = bpl->addrLow;
20096 
20097 			sgl->word2 = le32_to_cpu(sgl->word2);
20098 			if ((i+1) == numBdes)
20099 				bf_set(lpfc_sli4_sge_last, sgl, 1);
20100 			else
20101 				bf_set(lpfc_sli4_sge_last, sgl, 0);
20102 			/* swap the size field back to the cpu so we
20103 			 * can assign it to the sgl.
20104 			 */
20105 			bde.tus.w = le32_to_cpu(bpl->tus.w);
20106 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
20107 			/* The offsets in the sgl need to be accumulated
20108 			 * separately for the request and reply lists.
20109 			 * The request is always first, the reply follows.
20110 			 */
20111 			switch (cmd) {
20112 			case CMD_GEN_REQUEST64_WQE:
20113 				/* add up the reply sg entries */
20114 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
20115 					inbound++;
20116 				/* first inbound? reset the offset */
20117 				if (inbound == 1)
20118 					offset = 0;
20119 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
20120 				bf_set(lpfc_sli4_sge_type, sgl,
20121 					LPFC_SGE_TYPE_DATA);
20122 				offset += bde.tus.f.bdeSize;
20123 				break;
20124 			case CMD_FCP_TRSP64_WQE:
20125 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
20126 				bf_set(lpfc_sli4_sge_type, sgl,
20127 					LPFC_SGE_TYPE_DATA);
20128 				break;
20129 			case CMD_FCP_TSEND64_WQE:
20130 			case CMD_FCP_TRECEIVE64_WQE:
20131 				bf_set(lpfc_sli4_sge_type, sgl,
20132 					bpl->tus.f.bdeFlags);
20133 				if (i < 3)
20134 					offset = 0;
20135 				else
20136 					offset += bde.tus.f.bdeSize;
20137 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
20138 				break;
20139 			}
20140 			sgl->word2 = cpu_to_le32(sgl->word2);
20141 			bpl++;
20142 			sgl++;
20143 		}
20144 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
20145 		/* The addrHigh and addrLow fields of the BDE have not
20146 		 * been byteswapped yet so they need to be swapped
20147 		 * before putting them in the sgl.
20148 		 */
20149 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
20150 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
20151 		sgl->word2 = le32_to_cpu(sgl->word2);
20152 		bf_set(lpfc_sli4_sge_last, sgl, 1);
20153 		sgl->word2 = cpu_to_le32(sgl->word2);
20154 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
20155 	}
20156 	return sglq->sli4_xritag;
20157 }
20158 
20159 /**
20160  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
20161  * @phba: Pointer to HBA context object.
20162  * @qp: Pointer to HDW queue.
20163  * @pwqe: Pointer to command WQE.
20164  **/
20165 int
20166 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
20167 		    struct lpfc_iocbq *pwqe)
20168 {
20169 	union lpfc_wqe128 *wqe = &pwqe->wqe;
20170 	struct lpfc_async_xchg_ctx *ctxp;
20171 	struct lpfc_queue *wq;
20172 	struct lpfc_sglq *sglq;
20173 	struct lpfc_sli_ring *pring;
20174 	unsigned long iflags;
20175 	uint32_t ret = 0;
20176 
20177 	/* NVME_LS and NVME_LS ABTS requests. */
20178 	if (pwqe->iocb_flag & LPFC_IO_NVME_LS) {
20179 		pring =  phba->sli4_hba.nvmels_wq->pring;
20180 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20181 					  qp, wq_access);
20182 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
20183 		if (!sglq) {
20184 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20185 			return WQE_BUSY;
20186 		}
20187 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
20188 		pwqe->sli4_xritag = sglq->sli4_xritag;
20189 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
20190 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20191 			return WQE_ERROR;
20192 		}
20193 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
20194 		       pwqe->sli4_xritag);
20195 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
20196 		if (ret) {
20197 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20198 			return ret;
20199 		}
20200 
20201 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20202 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20203 
20204 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20205 		return 0;
20206 	}
20207 
20208 	/* NVME_FCREQ and NVME_ABTS requests */
20209 	if (pwqe->iocb_flag & LPFC_IO_NVME) {
20210 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
20211 		wq = qp->io_wq;
20212 		pring = wq->pring;
20213 
20214 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
20215 
20216 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20217 					  qp, wq_access);
20218 		ret = lpfc_sli4_wq_put(wq, wqe);
20219 		if (ret) {
20220 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20221 			return ret;
20222 		}
20223 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20224 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20225 
20226 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20227 		return 0;
20228 	}
20229 
20230 	/* NVMET requests */
20231 	if (pwqe->iocb_flag & LPFC_IO_NVMET) {
20232 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
20233 		wq = qp->io_wq;
20234 		pring = wq->pring;
20235 
20236 		ctxp = pwqe->context2;
20237 		sglq = ctxp->ctxbuf->sglq;
20238 		if (pwqe->sli4_xritag ==  NO_XRI) {
20239 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
20240 			pwqe->sli4_xritag = sglq->sli4_xritag;
20241 		}
20242 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
20243 		       pwqe->sli4_xritag);
20244 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
20245 
20246 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20247 					  qp, wq_access);
20248 		ret = lpfc_sli4_wq_put(wq, wqe);
20249 		if (ret) {
20250 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20251 			return ret;
20252 		}
20253 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20254 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20255 
20256 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20257 		return 0;
20258 	}
20259 	return WQE_ERROR;
20260 }
20261 
20262 #ifdef LPFC_MXP_STAT
20263 /**
20264  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
20265  * @phba: pointer to lpfc hba data structure.
20266  * @hwqid: belong to which HWQ.
20267  *
20268  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
20269  * 15 seconds after a test case is running.
20270  *
20271  * The user should call lpfc_debugfs_multixripools_write before running a test
20272  * case to clear stat_snapshot_taken. Then the user starts a test case. During
20273  * test case is running, stat_snapshot_taken is incremented by 1 every time when
20274  * this routine is called from heartbeat timer. When stat_snapshot_taken is
20275  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
20276  **/
20277 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
20278 {
20279 	struct lpfc_sli4_hdw_queue *qp;
20280 	struct lpfc_multixri_pool *multixri_pool;
20281 	struct lpfc_pvt_pool *pvt_pool;
20282 	struct lpfc_pbl_pool *pbl_pool;
20283 	u32 txcmplq_cnt;
20284 
20285 	qp = &phba->sli4_hba.hdwq[hwqid];
20286 	multixri_pool = qp->p_multixri_pool;
20287 	if (!multixri_pool)
20288 		return;
20289 
20290 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
20291 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
20292 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
20293 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20294 
20295 		multixri_pool->stat_pbl_count = pbl_pool->count;
20296 		multixri_pool->stat_pvt_count = pvt_pool->count;
20297 		multixri_pool->stat_busy_count = txcmplq_cnt;
20298 	}
20299 
20300 	multixri_pool->stat_snapshot_taken++;
20301 }
20302 #endif
20303 
20304 /**
20305  * lpfc_adjust_pvt_pool_count - Adjust private pool count
20306  * @phba: pointer to lpfc hba data structure.
20307  * @hwqid: belong to which HWQ.
20308  *
20309  * This routine moves some XRIs from private to public pool when private pool
20310  * is not busy.
20311  **/
20312 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
20313 {
20314 	struct lpfc_multixri_pool *multixri_pool;
20315 	u32 io_req_count;
20316 	u32 prev_io_req_count;
20317 
20318 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
20319 	if (!multixri_pool)
20320 		return;
20321 	io_req_count = multixri_pool->io_req_count;
20322 	prev_io_req_count = multixri_pool->prev_io_req_count;
20323 
20324 	if (prev_io_req_count != io_req_count) {
20325 		/* Private pool is busy */
20326 		multixri_pool->prev_io_req_count = io_req_count;
20327 	} else {
20328 		/* Private pool is not busy.
20329 		 * Move XRIs from private to public pool.
20330 		 */
20331 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
20332 	}
20333 }
20334 
20335 /**
20336  * lpfc_adjust_high_watermark - Adjust high watermark
20337  * @phba: pointer to lpfc hba data structure.
20338  * @hwqid: belong to which HWQ.
20339  *
20340  * This routine sets high watermark as number of outstanding XRIs,
20341  * but make sure the new value is between xri_limit/2 and xri_limit.
20342  **/
20343 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
20344 {
20345 	u32 new_watermark;
20346 	u32 watermark_max;
20347 	u32 watermark_min;
20348 	u32 xri_limit;
20349 	u32 txcmplq_cnt;
20350 	u32 abts_io_bufs;
20351 	struct lpfc_multixri_pool *multixri_pool;
20352 	struct lpfc_sli4_hdw_queue *qp;
20353 
20354 	qp = &phba->sli4_hba.hdwq[hwqid];
20355 	multixri_pool = qp->p_multixri_pool;
20356 	if (!multixri_pool)
20357 		return;
20358 	xri_limit = multixri_pool->xri_limit;
20359 
20360 	watermark_max = xri_limit;
20361 	watermark_min = xri_limit / 2;
20362 
20363 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20364 	abts_io_bufs = qp->abts_scsi_io_bufs;
20365 	abts_io_bufs += qp->abts_nvme_io_bufs;
20366 
20367 	new_watermark = txcmplq_cnt + abts_io_bufs;
20368 	new_watermark = min(watermark_max, new_watermark);
20369 	new_watermark = max(watermark_min, new_watermark);
20370 	multixri_pool->pvt_pool.high_watermark = new_watermark;
20371 
20372 #ifdef LPFC_MXP_STAT
20373 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
20374 					  new_watermark);
20375 #endif
20376 }
20377 
20378 /**
20379  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
20380  * @phba: pointer to lpfc hba data structure.
20381  * @hwqid: belong to which HWQ.
20382  *
20383  * This routine is called from hearbeat timer when pvt_pool is idle.
20384  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
20385  * The first step moves (all - low_watermark) amount of XRIs.
20386  * The second step moves the rest of XRIs.
20387  **/
20388 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
20389 {
20390 	struct lpfc_pbl_pool *pbl_pool;
20391 	struct lpfc_pvt_pool *pvt_pool;
20392 	struct lpfc_sli4_hdw_queue *qp;
20393 	struct lpfc_io_buf *lpfc_ncmd;
20394 	struct lpfc_io_buf *lpfc_ncmd_next;
20395 	unsigned long iflag;
20396 	struct list_head tmp_list;
20397 	u32 tmp_count;
20398 
20399 	qp = &phba->sli4_hba.hdwq[hwqid];
20400 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
20401 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
20402 	tmp_count = 0;
20403 
20404 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
20405 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
20406 
20407 	if (pvt_pool->count > pvt_pool->low_watermark) {
20408 		/* Step 1: move (all - low_watermark) from pvt_pool
20409 		 * to pbl_pool
20410 		 */
20411 
20412 		/* Move low watermark of bufs from pvt_pool to tmp_list */
20413 		INIT_LIST_HEAD(&tmp_list);
20414 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20415 					 &pvt_pool->list, list) {
20416 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
20417 			tmp_count++;
20418 			if (tmp_count >= pvt_pool->low_watermark)
20419 				break;
20420 		}
20421 
20422 		/* Move all bufs from pvt_pool to pbl_pool */
20423 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
20424 
20425 		/* Move all bufs from tmp_list to pvt_pool */
20426 		list_splice(&tmp_list, &pvt_pool->list);
20427 
20428 		pbl_pool->count += (pvt_pool->count - tmp_count);
20429 		pvt_pool->count = tmp_count;
20430 	} else {
20431 		/* Step 2: move the rest from pvt_pool to pbl_pool */
20432 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
20433 		pbl_pool->count += pvt_pool->count;
20434 		pvt_pool->count = 0;
20435 	}
20436 
20437 	spin_unlock(&pvt_pool->lock);
20438 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20439 }
20440 
20441 /**
20442  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
20443  * @phba: pointer to lpfc hba data structure
20444  * @qp: pointer to HDW queue
20445  * @pbl_pool: specified public free XRI pool
20446  * @pvt_pool: specified private free XRI pool
20447  * @count: number of XRIs to move
20448  *
20449  * This routine tries to move some free common bufs from the specified pbl_pool
20450  * to the specified pvt_pool. It might move less than count XRIs if there's not
20451  * enough in public pool.
20452  *
20453  * Return:
20454  *   true - if XRIs are successfully moved from the specified pbl_pool to the
20455  *          specified pvt_pool
20456  *   false - if the specified pbl_pool is empty or locked by someone else
20457  **/
20458 static bool
20459 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
20460 			  struct lpfc_pbl_pool *pbl_pool,
20461 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
20462 {
20463 	struct lpfc_io_buf *lpfc_ncmd;
20464 	struct lpfc_io_buf *lpfc_ncmd_next;
20465 	unsigned long iflag;
20466 	int ret;
20467 
20468 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
20469 	if (ret) {
20470 		if (pbl_pool->count) {
20471 			/* Move a batch of XRIs from public to private pool */
20472 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
20473 			list_for_each_entry_safe(lpfc_ncmd,
20474 						 lpfc_ncmd_next,
20475 						 &pbl_pool->list,
20476 						 list) {
20477 				list_move_tail(&lpfc_ncmd->list,
20478 					       &pvt_pool->list);
20479 				pvt_pool->count++;
20480 				pbl_pool->count--;
20481 				count--;
20482 				if (count == 0)
20483 					break;
20484 			}
20485 
20486 			spin_unlock(&pvt_pool->lock);
20487 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20488 			return true;
20489 		}
20490 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20491 	}
20492 
20493 	return false;
20494 }
20495 
20496 /**
20497  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
20498  * @phba: pointer to lpfc hba data structure.
20499  * @hwqid: belong to which HWQ.
20500  * @count: number of XRIs to move
20501  *
20502  * This routine tries to find some free common bufs in one of public pools with
20503  * Round Robin method. The search always starts from local hwqid, then the next
20504  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
20505  * a batch of free common bufs are moved to private pool on hwqid.
20506  * It might move less than count XRIs if there's not enough in public pool.
20507  **/
20508 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
20509 {
20510 	struct lpfc_multixri_pool *multixri_pool;
20511 	struct lpfc_multixri_pool *next_multixri_pool;
20512 	struct lpfc_pvt_pool *pvt_pool;
20513 	struct lpfc_pbl_pool *pbl_pool;
20514 	struct lpfc_sli4_hdw_queue *qp;
20515 	u32 next_hwqid;
20516 	u32 hwq_count;
20517 	int ret;
20518 
20519 	qp = &phba->sli4_hba.hdwq[hwqid];
20520 	multixri_pool = qp->p_multixri_pool;
20521 	pvt_pool = &multixri_pool->pvt_pool;
20522 	pbl_pool = &multixri_pool->pbl_pool;
20523 
20524 	/* Check if local pbl_pool is available */
20525 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
20526 	if (ret) {
20527 #ifdef LPFC_MXP_STAT
20528 		multixri_pool->local_pbl_hit_count++;
20529 #endif
20530 		return;
20531 	}
20532 
20533 	hwq_count = phba->cfg_hdw_queue;
20534 
20535 	/* Get the next hwqid which was found last time */
20536 	next_hwqid = multixri_pool->rrb_next_hwqid;
20537 
20538 	do {
20539 		/* Go to next hwq */
20540 		next_hwqid = (next_hwqid + 1) % hwq_count;
20541 
20542 		next_multixri_pool =
20543 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
20544 		pbl_pool = &next_multixri_pool->pbl_pool;
20545 
20546 		/* Check if the public free xri pool is available */
20547 		ret = _lpfc_move_xri_pbl_to_pvt(
20548 			phba, qp, pbl_pool, pvt_pool, count);
20549 
20550 		/* Exit while-loop if success or all hwqid are checked */
20551 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
20552 
20553 	/* Starting point for the next time */
20554 	multixri_pool->rrb_next_hwqid = next_hwqid;
20555 
20556 	if (!ret) {
20557 		/* stats: all public pools are empty*/
20558 		multixri_pool->pbl_empty_count++;
20559 	}
20560 
20561 #ifdef LPFC_MXP_STAT
20562 	if (ret) {
20563 		if (next_hwqid == hwqid)
20564 			multixri_pool->local_pbl_hit_count++;
20565 		else
20566 			multixri_pool->other_pbl_hit_count++;
20567 	}
20568 #endif
20569 }
20570 
20571 /**
20572  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
20573  * @phba: pointer to lpfc hba data structure.
20574  * @hwqid: belong to which HWQ.
20575  *
20576  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
20577  * low watermark.
20578  **/
20579 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
20580 {
20581 	struct lpfc_multixri_pool *multixri_pool;
20582 	struct lpfc_pvt_pool *pvt_pool;
20583 
20584 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
20585 	pvt_pool = &multixri_pool->pvt_pool;
20586 
20587 	if (pvt_pool->count < pvt_pool->low_watermark)
20588 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
20589 }
20590 
20591 /**
20592  * lpfc_release_io_buf - Return one IO buf back to free pool
20593  * @phba: pointer to lpfc hba data structure.
20594  * @lpfc_ncmd: IO buf to be returned.
20595  * @qp: belong to which HWQ.
20596  *
20597  * This routine returns one IO buf back to free pool. If this is an urgent IO,
20598  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
20599  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
20600  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
20601  * lpfc_io_buf_list_put.
20602  **/
20603 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
20604 			 struct lpfc_sli4_hdw_queue *qp)
20605 {
20606 	unsigned long iflag;
20607 	struct lpfc_pbl_pool *pbl_pool;
20608 	struct lpfc_pvt_pool *pvt_pool;
20609 	struct lpfc_epd_pool *epd_pool;
20610 	u32 txcmplq_cnt;
20611 	u32 xri_owned;
20612 	u32 xri_limit;
20613 	u32 abts_io_bufs;
20614 
20615 	/* MUST zero fields if buffer is reused by another protocol */
20616 	lpfc_ncmd->nvmeCmd = NULL;
20617 	lpfc_ncmd->cur_iocbq.wqe_cmpl = NULL;
20618 	lpfc_ncmd->cur_iocbq.iocb_cmpl = NULL;
20619 
20620 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
20621 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
20622 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
20623 
20624 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
20625 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
20626 
20627 	if (phba->cfg_xri_rebalancing) {
20628 		if (lpfc_ncmd->expedite) {
20629 			/* Return to expedite pool */
20630 			epd_pool = &phba->epd_pool;
20631 			spin_lock_irqsave(&epd_pool->lock, iflag);
20632 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
20633 			epd_pool->count++;
20634 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
20635 			return;
20636 		}
20637 
20638 		/* Avoid invalid access if an IO sneaks in and is being rejected
20639 		 * just _after_ xri pools are destroyed in lpfc_offline.
20640 		 * Nothing much can be done at this point.
20641 		 */
20642 		if (!qp->p_multixri_pool)
20643 			return;
20644 
20645 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
20646 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
20647 
20648 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20649 		abts_io_bufs = qp->abts_scsi_io_bufs;
20650 		abts_io_bufs += qp->abts_nvme_io_bufs;
20651 
20652 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
20653 		xri_limit = qp->p_multixri_pool->xri_limit;
20654 
20655 #ifdef LPFC_MXP_STAT
20656 		if (xri_owned <= xri_limit)
20657 			qp->p_multixri_pool->below_limit_count++;
20658 		else
20659 			qp->p_multixri_pool->above_limit_count++;
20660 #endif
20661 
20662 		/* XRI goes to either public or private free xri pool
20663 		 *     based on watermark and xri_limit
20664 		 */
20665 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
20666 		    (xri_owned < xri_limit &&
20667 		     pvt_pool->count < pvt_pool->high_watermark)) {
20668 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
20669 						  qp, free_pvt_pool);
20670 			list_add_tail(&lpfc_ncmd->list,
20671 				      &pvt_pool->list);
20672 			pvt_pool->count++;
20673 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
20674 		} else {
20675 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
20676 						  qp, free_pub_pool);
20677 			list_add_tail(&lpfc_ncmd->list,
20678 				      &pbl_pool->list);
20679 			pbl_pool->count++;
20680 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20681 		}
20682 	} else {
20683 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
20684 					  qp, free_xri);
20685 		list_add_tail(&lpfc_ncmd->list,
20686 			      &qp->lpfc_io_buf_list_put);
20687 		qp->put_io_bufs++;
20688 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
20689 				       iflag);
20690 	}
20691 }
20692 
20693 /**
20694  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
20695  * @phba: pointer to lpfc hba data structure.
20696  * @qp: pointer to HDW queue
20697  * @pvt_pool: pointer to private pool data structure.
20698  * @ndlp: pointer to lpfc nodelist data structure.
20699  *
20700  * This routine tries to get one free IO buf from private pool.
20701  *
20702  * Return:
20703  *   pointer to one free IO buf - if private pool is not empty
20704  *   NULL - if private pool is empty
20705  **/
20706 static struct lpfc_io_buf *
20707 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
20708 				  struct lpfc_sli4_hdw_queue *qp,
20709 				  struct lpfc_pvt_pool *pvt_pool,
20710 				  struct lpfc_nodelist *ndlp)
20711 {
20712 	struct lpfc_io_buf *lpfc_ncmd;
20713 	struct lpfc_io_buf *lpfc_ncmd_next;
20714 	unsigned long iflag;
20715 
20716 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
20717 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20718 				 &pvt_pool->list, list) {
20719 		if (lpfc_test_rrq_active(
20720 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
20721 			continue;
20722 		list_del(&lpfc_ncmd->list);
20723 		pvt_pool->count--;
20724 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
20725 		return lpfc_ncmd;
20726 	}
20727 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
20728 
20729 	return NULL;
20730 }
20731 
20732 /**
20733  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
20734  * @phba: pointer to lpfc hba data structure.
20735  *
20736  * This routine tries to get one free IO buf from expedite pool.
20737  *
20738  * Return:
20739  *   pointer to one free IO buf - if expedite pool is not empty
20740  *   NULL - if expedite pool is empty
20741  **/
20742 static struct lpfc_io_buf *
20743 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
20744 {
20745 	struct lpfc_io_buf *lpfc_ncmd;
20746 	struct lpfc_io_buf *lpfc_ncmd_next;
20747 	unsigned long iflag;
20748 	struct lpfc_epd_pool *epd_pool;
20749 
20750 	epd_pool = &phba->epd_pool;
20751 	lpfc_ncmd = NULL;
20752 
20753 	spin_lock_irqsave(&epd_pool->lock, iflag);
20754 	if (epd_pool->count > 0) {
20755 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20756 					 &epd_pool->list, list) {
20757 			list_del(&lpfc_ncmd->list);
20758 			epd_pool->count--;
20759 			break;
20760 		}
20761 	}
20762 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
20763 
20764 	return lpfc_ncmd;
20765 }
20766 
20767 /**
20768  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
20769  * @phba: pointer to lpfc hba data structure.
20770  * @ndlp: pointer to lpfc nodelist data structure.
20771  * @hwqid: belong to which HWQ
20772  * @expedite: 1 means this request is urgent.
20773  *
20774  * This routine will do the following actions and then return a pointer to
20775  * one free IO buf.
20776  *
20777  * 1. If private free xri count is empty, move some XRIs from public to
20778  *    private pool.
20779  * 2. Get one XRI from private free xri pool.
20780  * 3. If we fail to get one from pvt_pool and this is an expedite request,
20781  *    get one free xri from expedite pool.
20782  *
20783  * Note: ndlp is only used on SCSI side for RRQ testing.
20784  *       The caller should pass NULL for ndlp on NVME side.
20785  *
20786  * Return:
20787  *   pointer to one free IO buf - if private pool is not empty
20788  *   NULL - if private pool is empty
20789  **/
20790 static struct lpfc_io_buf *
20791 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
20792 				    struct lpfc_nodelist *ndlp,
20793 				    int hwqid, int expedite)
20794 {
20795 	struct lpfc_sli4_hdw_queue *qp;
20796 	struct lpfc_multixri_pool *multixri_pool;
20797 	struct lpfc_pvt_pool *pvt_pool;
20798 	struct lpfc_io_buf *lpfc_ncmd;
20799 
20800 	qp = &phba->sli4_hba.hdwq[hwqid];
20801 	lpfc_ncmd = NULL;
20802 	multixri_pool = qp->p_multixri_pool;
20803 	pvt_pool = &multixri_pool->pvt_pool;
20804 	multixri_pool->io_req_count++;
20805 
20806 	/* If pvt_pool is empty, move some XRIs from public to private pool */
20807 	if (pvt_pool->count == 0)
20808 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
20809 
20810 	/* Get one XRI from private free xri pool */
20811 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
20812 
20813 	if (lpfc_ncmd) {
20814 		lpfc_ncmd->hdwq = qp;
20815 		lpfc_ncmd->hdwq_no = hwqid;
20816 	} else if (expedite) {
20817 		/* If we fail to get one from pvt_pool and this is an expedite
20818 		 * request, get one free xri from expedite pool.
20819 		 */
20820 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
20821 	}
20822 
20823 	return lpfc_ncmd;
20824 }
20825 
20826 static inline struct lpfc_io_buf *
20827 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
20828 {
20829 	struct lpfc_sli4_hdw_queue *qp;
20830 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
20831 
20832 	qp = &phba->sli4_hba.hdwq[idx];
20833 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
20834 				 &qp->lpfc_io_buf_list_get, list) {
20835 		if (lpfc_test_rrq_active(phba, ndlp,
20836 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
20837 			continue;
20838 
20839 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
20840 			continue;
20841 
20842 		list_del_init(&lpfc_cmd->list);
20843 		qp->get_io_bufs--;
20844 		lpfc_cmd->hdwq = qp;
20845 		lpfc_cmd->hdwq_no = idx;
20846 		return lpfc_cmd;
20847 	}
20848 	return NULL;
20849 }
20850 
20851 /**
20852  * lpfc_get_io_buf - Get one IO buffer from free pool
20853  * @phba: The HBA for which this call is being executed.
20854  * @ndlp: pointer to lpfc nodelist data structure.
20855  * @hwqid: belong to which HWQ
20856  * @expedite: 1 means this request is urgent.
20857  *
20858  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
20859  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
20860  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
20861  *
20862  * Note: ndlp is only used on SCSI side for RRQ testing.
20863  *       The caller should pass NULL for ndlp on NVME side.
20864  *
20865  * Return codes:
20866  *   NULL - Error
20867  *   Pointer to lpfc_io_buf - Success
20868  **/
20869 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
20870 				    struct lpfc_nodelist *ndlp,
20871 				    u32 hwqid, int expedite)
20872 {
20873 	struct lpfc_sli4_hdw_queue *qp;
20874 	unsigned long iflag;
20875 	struct lpfc_io_buf *lpfc_cmd;
20876 
20877 	qp = &phba->sli4_hba.hdwq[hwqid];
20878 	lpfc_cmd = NULL;
20879 
20880 	if (phba->cfg_xri_rebalancing)
20881 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
20882 			phba, ndlp, hwqid, expedite);
20883 	else {
20884 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
20885 					  qp, alloc_xri_get);
20886 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
20887 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
20888 		if (!lpfc_cmd) {
20889 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
20890 					  qp, alloc_xri_put);
20891 			list_splice(&qp->lpfc_io_buf_list_put,
20892 				    &qp->lpfc_io_buf_list_get);
20893 			qp->get_io_bufs += qp->put_io_bufs;
20894 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
20895 			qp->put_io_bufs = 0;
20896 			spin_unlock(&qp->io_buf_list_put_lock);
20897 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
20898 			    expedite)
20899 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
20900 		}
20901 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
20902 	}
20903 
20904 	return lpfc_cmd;
20905 }
20906 
20907 /**
20908  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
20909  * @phba: The HBA for which this call is being executed.
20910  * @lpfc_buf: IO buf structure to append the SGL chunk
20911  *
20912  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
20913  * and will allocate an SGL chunk if the pool is empty.
20914  *
20915  * Return codes:
20916  *   NULL - Error
20917  *   Pointer to sli4_hybrid_sgl - Success
20918  **/
20919 struct sli4_hybrid_sgl *
20920 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
20921 {
20922 	struct sli4_hybrid_sgl *list_entry = NULL;
20923 	struct sli4_hybrid_sgl *tmp = NULL;
20924 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
20925 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20926 	struct list_head *buf_list = &hdwq->sgl_list;
20927 	unsigned long iflags;
20928 
20929 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20930 
20931 	if (likely(!list_empty(buf_list))) {
20932 		/* break off 1 chunk from the sgl_list */
20933 		list_for_each_entry_safe(list_entry, tmp,
20934 					 buf_list, list_node) {
20935 			list_move_tail(&list_entry->list_node,
20936 				       &lpfc_buf->dma_sgl_xtra_list);
20937 			break;
20938 		}
20939 	} else {
20940 		/* allocate more */
20941 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20942 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
20943 				   cpu_to_node(hdwq->io_wq->chann));
20944 		if (!tmp) {
20945 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20946 					"8353 error kmalloc memory for HDWQ "
20947 					"%d %s\n",
20948 					lpfc_buf->hdwq_no, __func__);
20949 			return NULL;
20950 		}
20951 
20952 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
20953 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
20954 		if (!tmp->dma_sgl) {
20955 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20956 					"8354 error pool_alloc memory for HDWQ "
20957 					"%d %s\n",
20958 					lpfc_buf->hdwq_no, __func__);
20959 			kfree(tmp);
20960 			return NULL;
20961 		}
20962 
20963 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20964 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
20965 	}
20966 
20967 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
20968 					struct sli4_hybrid_sgl,
20969 					list_node);
20970 
20971 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20972 
20973 	return allocated_sgl;
20974 }
20975 
20976 /**
20977  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
20978  * @phba: The HBA for which this call is being executed.
20979  * @lpfc_buf: IO buf structure with the SGL chunk
20980  *
20981  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
20982  *
20983  * Return codes:
20984  *   0 - Success
20985  *   -EINVAL - Error
20986  **/
20987 int
20988 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
20989 {
20990 	int rc = 0;
20991 	struct sli4_hybrid_sgl *list_entry = NULL;
20992 	struct sli4_hybrid_sgl *tmp = NULL;
20993 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20994 	struct list_head *buf_list = &hdwq->sgl_list;
20995 	unsigned long iflags;
20996 
20997 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20998 
20999 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
21000 		list_for_each_entry_safe(list_entry, tmp,
21001 					 &lpfc_buf->dma_sgl_xtra_list,
21002 					 list_node) {
21003 			list_move_tail(&list_entry->list_node,
21004 				       buf_list);
21005 		}
21006 	} else {
21007 		rc = -EINVAL;
21008 	}
21009 
21010 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21011 	return rc;
21012 }
21013 
21014 /**
21015  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
21016  * @phba: phba object
21017  * @hdwq: hdwq to cleanup sgl buff resources on
21018  *
21019  * This routine frees all SGL chunks of hdwq SGL chunk pool.
21020  *
21021  * Return codes:
21022  *   None
21023  **/
21024 void
21025 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
21026 		       struct lpfc_sli4_hdw_queue *hdwq)
21027 {
21028 	struct list_head *buf_list = &hdwq->sgl_list;
21029 	struct sli4_hybrid_sgl *list_entry = NULL;
21030 	struct sli4_hybrid_sgl *tmp = NULL;
21031 	unsigned long iflags;
21032 
21033 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21034 
21035 	/* Free sgl pool */
21036 	list_for_each_entry_safe(list_entry, tmp,
21037 				 buf_list, list_node) {
21038 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
21039 			      list_entry->dma_sgl,
21040 			      list_entry->dma_phys_sgl);
21041 		list_del(&list_entry->list_node);
21042 		kfree(list_entry);
21043 	}
21044 
21045 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21046 }
21047 
21048 /**
21049  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
21050  * @phba: The HBA for which this call is being executed.
21051  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
21052  *
21053  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
21054  * and will allocate an CMD/RSP buffer if the pool is empty.
21055  *
21056  * Return codes:
21057  *   NULL - Error
21058  *   Pointer to fcp_cmd_rsp_buf - Success
21059  **/
21060 struct fcp_cmd_rsp_buf *
21061 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
21062 			      struct lpfc_io_buf *lpfc_buf)
21063 {
21064 	struct fcp_cmd_rsp_buf *list_entry = NULL;
21065 	struct fcp_cmd_rsp_buf *tmp = NULL;
21066 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
21067 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21068 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
21069 	unsigned long iflags;
21070 
21071 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21072 
21073 	if (likely(!list_empty(buf_list))) {
21074 		/* break off 1 chunk from the list */
21075 		list_for_each_entry_safe(list_entry, tmp,
21076 					 buf_list,
21077 					 list_node) {
21078 			list_move_tail(&list_entry->list_node,
21079 				       &lpfc_buf->dma_cmd_rsp_list);
21080 			break;
21081 		}
21082 	} else {
21083 		/* allocate more */
21084 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21085 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
21086 				   cpu_to_node(hdwq->io_wq->chann));
21087 		if (!tmp) {
21088 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21089 					"8355 error kmalloc memory for HDWQ "
21090 					"%d %s\n",
21091 					lpfc_buf->hdwq_no, __func__);
21092 			return NULL;
21093 		}
21094 
21095 		tmp->fcp_cmnd = dma_pool_alloc(phba->lpfc_cmd_rsp_buf_pool,
21096 						GFP_ATOMIC,
21097 						&tmp->fcp_cmd_rsp_dma_handle);
21098 
21099 		if (!tmp->fcp_cmnd) {
21100 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21101 					"8356 error pool_alloc memory for HDWQ "
21102 					"%d %s\n",
21103 					lpfc_buf->hdwq_no, __func__);
21104 			kfree(tmp);
21105 			return NULL;
21106 		}
21107 
21108 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
21109 				sizeof(struct fcp_cmnd));
21110 
21111 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21112 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
21113 	}
21114 
21115 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
21116 					struct fcp_cmd_rsp_buf,
21117 					list_node);
21118 
21119 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21120 
21121 	return allocated_buf;
21122 }
21123 
21124 /**
21125  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
21126  * @phba: The HBA for which this call is being executed.
21127  * @lpfc_buf: IO buf structure with the CMD/RSP buf
21128  *
21129  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
21130  *
21131  * Return codes:
21132  *   0 - Success
21133  *   -EINVAL - Error
21134  **/
21135 int
21136 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
21137 			      struct lpfc_io_buf *lpfc_buf)
21138 {
21139 	int rc = 0;
21140 	struct fcp_cmd_rsp_buf *list_entry = NULL;
21141 	struct fcp_cmd_rsp_buf *tmp = NULL;
21142 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21143 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
21144 	unsigned long iflags;
21145 
21146 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21147 
21148 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
21149 		list_for_each_entry_safe(list_entry, tmp,
21150 					 &lpfc_buf->dma_cmd_rsp_list,
21151 					 list_node) {
21152 			list_move_tail(&list_entry->list_node,
21153 				       buf_list);
21154 		}
21155 	} else {
21156 		rc = -EINVAL;
21157 	}
21158 
21159 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21160 	return rc;
21161 }
21162 
21163 /**
21164  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
21165  * @phba: phba object
21166  * @hdwq: hdwq to cleanup cmd rsp buff resources on
21167  *
21168  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
21169  *
21170  * Return codes:
21171  *   None
21172  **/
21173 void
21174 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
21175 			       struct lpfc_sli4_hdw_queue *hdwq)
21176 {
21177 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
21178 	struct fcp_cmd_rsp_buf *list_entry = NULL;
21179 	struct fcp_cmd_rsp_buf *tmp = NULL;
21180 	unsigned long iflags;
21181 
21182 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21183 
21184 	/* Free cmd_rsp buf pool */
21185 	list_for_each_entry_safe(list_entry, tmp,
21186 				 buf_list,
21187 				 list_node) {
21188 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
21189 			      list_entry->fcp_cmnd,
21190 			      list_entry->fcp_cmd_rsp_dma_handle);
21191 		list_del(&list_entry->list_node);
21192 		kfree(list_entry);
21193 	}
21194 
21195 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21196 }
21197