xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision 352780b6)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2020 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.  *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/pci.h>
26 #include <linux/interrupt.h>
27 #include <linux/delay.h>
28 #include <linux/slab.h>
29 #include <linux/lockdep.h>
30 
31 #include <scsi/scsi.h>
32 #include <scsi/scsi_cmnd.h>
33 #include <scsi/scsi_device.h>
34 #include <scsi/scsi_host.h>
35 #include <scsi/scsi_transport_fc.h>
36 #include <scsi/fc/fc_fs.h>
37 #include <linux/aer.h>
38 #ifdef CONFIG_X86
39 #include <asm/set_memory.h>
40 #endif
41 
42 #include <linux/nvme-fc-driver.h>
43 
44 #include "lpfc_hw4.h"
45 #include "lpfc_hw.h"
46 #include "lpfc_sli.h"
47 #include "lpfc_sli4.h"
48 #include "lpfc_nl.h"
49 #include "lpfc_disc.h"
50 #include "lpfc.h"
51 #include "lpfc_scsi.h"
52 #include "lpfc_nvme.h"
53 #include "lpfc_nvmet.h"
54 #include "lpfc_crtn.h"
55 #include "lpfc_logmsg.h"
56 #include "lpfc_compat.h"
57 #include "lpfc_debugfs.h"
58 #include "lpfc_vport.h"
59 #include "lpfc_version.h"
60 
61 /* There are only four IOCB completion types. */
62 typedef enum _lpfc_iocb_type {
63 	LPFC_UNKNOWN_IOCB,
64 	LPFC_UNSOL_IOCB,
65 	LPFC_SOL_IOCB,
66 	LPFC_ABORT_IOCB
67 } lpfc_iocb_type;
68 
69 
70 /* Provide function prototypes local to this module. */
71 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
72 				  uint32_t);
73 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
74 			      uint8_t *, uint32_t *);
75 static struct lpfc_iocbq *lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *,
76 							 struct lpfc_iocbq *);
77 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
78 				      struct hbq_dmabuf *);
79 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
80 					  struct hbq_dmabuf *dmabuf);
81 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
82 				   struct lpfc_queue *cq, struct lpfc_cqe *cqe);
83 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
84 				       int);
85 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
86 				     struct lpfc_queue *eq,
87 				     struct lpfc_eqe *eqe);
88 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
89 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
90 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
91 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
92 				    struct lpfc_queue *cq,
93 				    struct lpfc_cqe *cqe);
94 
95 static IOCB_t *
96 lpfc_get_iocb_from_iocbq(struct lpfc_iocbq *iocbq)
97 {
98 	return &iocbq->iocb;
99 }
100 
101 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
102 /**
103  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
104  * @srcp: Source memory pointer.
105  * @destp: Destination memory pointer.
106  * @cnt: Number of words required to be copied.
107  *       Must be a multiple of sizeof(uint64_t)
108  *
109  * This function is used for copying data between driver memory
110  * and the SLI WQ. This function also changes the endianness
111  * of each word if native endianness is different from SLI
112  * endianness. This function can be called with or without
113  * lock.
114  **/
115 static void
116 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
117 {
118 	uint64_t *src = srcp;
119 	uint64_t *dest = destp;
120 	int i;
121 
122 	for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
123 		*dest++ = *src++;
124 }
125 #else
126 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
127 #endif
128 
129 /**
130  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
131  * @q: The Work Queue to operate on.
132  * @wqe: The work Queue Entry to put on the Work queue.
133  *
134  * This routine will copy the contents of @wqe to the next available entry on
135  * the @q. This function will then ring the Work Queue Doorbell to signal the
136  * HBA to start processing the Work Queue Entry. This function returns 0 if
137  * successful. If no entries are available on @q then this function will return
138  * -ENOMEM.
139  * The caller is expected to hold the hbalock when calling this routine.
140  **/
141 static int
142 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
143 {
144 	union lpfc_wqe *temp_wqe;
145 	struct lpfc_register doorbell;
146 	uint32_t host_index;
147 	uint32_t idx;
148 	uint32_t i = 0;
149 	uint8_t *tmp;
150 	u32 if_type;
151 
152 	/* sanity check on queue memory */
153 	if (unlikely(!q))
154 		return -ENOMEM;
155 	temp_wqe = lpfc_sli4_qe(q, q->host_index);
156 
157 	/* If the host has not yet processed the next entry then we are done */
158 	idx = ((q->host_index + 1) % q->entry_count);
159 	if (idx == q->hba_index) {
160 		q->WQ_overflow++;
161 		return -EBUSY;
162 	}
163 	q->WQ_posted++;
164 	/* set consumption flag every once in a while */
165 	if (!((q->host_index + 1) % q->notify_interval))
166 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
167 	else
168 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
169 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
170 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
171 	lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
172 	if (q->dpp_enable && q->phba->cfg_enable_dpp) {
173 		/* write to DPP aperture taking advatage of Combined Writes */
174 		tmp = (uint8_t *)temp_wqe;
175 #ifdef __raw_writeq
176 		for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
177 			__raw_writeq(*((uint64_t *)(tmp + i)),
178 					q->dpp_regaddr + i);
179 #else
180 		for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
181 			__raw_writel(*((uint32_t *)(tmp + i)),
182 					q->dpp_regaddr + i);
183 #endif
184 	}
185 	/* ensure WQE bcopy and DPP flushed before doorbell write */
186 	wmb();
187 
188 	/* Update the host index before invoking device */
189 	host_index = q->host_index;
190 
191 	q->host_index = idx;
192 
193 	/* Ring Doorbell */
194 	doorbell.word0 = 0;
195 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
196 		if (q->dpp_enable && q->phba->cfg_enable_dpp) {
197 			bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
198 			bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
199 			bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
200 			    q->dpp_id);
201 			bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
202 			    q->queue_id);
203 		} else {
204 			bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
205 			bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
206 
207 			/* Leave bits <23:16> clear for if_type 6 dpp */
208 			if_type = bf_get(lpfc_sli_intf_if_type,
209 					 &q->phba->sli4_hba.sli_intf);
210 			if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
211 				bf_set(lpfc_wq_db_list_fm_index, &doorbell,
212 				       host_index);
213 		}
214 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
215 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
216 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
217 	} else {
218 		return -EINVAL;
219 	}
220 	writel(doorbell.word0, q->db_regaddr);
221 
222 	return 0;
223 }
224 
225 /**
226  * lpfc_sli4_wq_release - Updates internal hba index for WQ
227  * @q: The Work Queue to operate on.
228  * @index: The index to advance the hba index to.
229  *
230  * This routine will update the HBA index of a queue to reflect consumption of
231  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
232  * an entry the host calls this function to update the queue's internal
233  * pointers.
234  **/
235 static void
236 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
237 {
238 	/* sanity check on queue memory */
239 	if (unlikely(!q))
240 		return;
241 
242 	q->hba_index = index;
243 }
244 
245 /**
246  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
247  * @q: The Mailbox Queue to operate on.
248  * @wqe: The Mailbox Queue Entry to put on the Work queue.
249  *
250  * This routine will copy the contents of @mqe to the next available entry on
251  * the @q. This function will then ring the Work Queue Doorbell to signal the
252  * HBA to start processing the Work Queue Entry. This function returns 0 if
253  * successful. If no entries are available on @q then this function will return
254  * -ENOMEM.
255  * The caller is expected to hold the hbalock when calling this routine.
256  **/
257 static uint32_t
258 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
259 {
260 	struct lpfc_mqe *temp_mqe;
261 	struct lpfc_register doorbell;
262 
263 	/* sanity check on queue memory */
264 	if (unlikely(!q))
265 		return -ENOMEM;
266 	temp_mqe = lpfc_sli4_qe(q, q->host_index);
267 
268 	/* If the host has not yet processed the next entry then we are done */
269 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
270 		return -ENOMEM;
271 	lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
272 	/* Save off the mailbox pointer for completion */
273 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
274 
275 	/* Update the host index before invoking device */
276 	q->host_index = ((q->host_index + 1) % q->entry_count);
277 
278 	/* Ring Doorbell */
279 	doorbell.word0 = 0;
280 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
281 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
282 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
283 	return 0;
284 }
285 
286 /**
287  * lpfc_sli4_mq_release - Updates internal hba index for MQ
288  * @q: The Mailbox Queue to operate on.
289  *
290  * This routine will update the HBA index of a queue to reflect consumption of
291  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
292  * an entry the host calls this function to update the queue's internal
293  * pointers. This routine returns the number of entries that were consumed by
294  * the HBA.
295  **/
296 static uint32_t
297 lpfc_sli4_mq_release(struct lpfc_queue *q)
298 {
299 	/* sanity check on queue memory */
300 	if (unlikely(!q))
301 		return 0;
302 
303 	/* Clear the mailbox pointer for completion */
304 	q->phba->mbox = NULL;
305 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
306 	return 1;
307 }
308 
309 /**
310  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
311  * @q: The Event Queue to get the first valid EQE from
312  *
313  * This routine will get the first valid Event Queue Entry from @q, update
314  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
315  * the Queue (no more work to do), or the Queue is full of EQEs that have been
316  * processed, but not popped back to the HBA then this routine will return NULL.
317  **/
318 static struct lpfc_eqe *
319 lpfc_sli4_eq_get(struct lpfc_queue *q)
320 {
321 	struct lpfc_eqe *eqe;
322 
323 	/* sanity check on queue memory */
324 	if (unlikely(!q))
325 		return NULL;
326 	eqe = lpfc_sli4_qe(q, q->host_index);
327 
328 	/* If the next EQE is not valid then we are done */
329 	if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
330 		return NULL;
331 
332 	/*
333 	 * insert barrier for instruction interlock : data from the hardware
334 	 * must have the valid bit checked before it can be copied and acted
335 	 * upon. Speculative instructions were allowing a bcopy at the start
336 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
337 	 * after our return, to copy data before the valid bit check above
338 	 * was done. As such, some of the copied data was stale. The barrier
339 	 * ensures the check is before any data is copied.
340 	 */
341 	mb();
342 	return eqe;
343 }
344 
345 /**
346  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
347  * @q: The Event Queue to disable interrupts
348  *
349  **/
350 void
351 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
352 {
353 	struct lpfc_register doorbell;
354 
355 	doorbell.word0 = 0;
356 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
357 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
358 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
359 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
360 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
361 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
362 }
363 
364 /**
365  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
366  * @q: The Event Queue to disable interrupts
367  *
368  **/
369 void
370 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
371 {
372 	struct lpfc_register doorbell;
373 
374 	doorbell.word0 = 0;
375 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
376 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
377 }
378 
379 /**
380  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
381  * @phba: adapter with EQ
382  * @q: The Event Queue that the host has completed processing for.
383  * @count: Number of elements that have been consumed
384  * @arm: Indicates whether the host wants to arms this CQ.
385  *
386  * This routine will notify the HBA, by ringing the doorbell, that count
387  * number of EQEs have been processed. The @arm parameter indicates whether
388  * the queue should be rearmed when ringing the doorbell.
389  **/
390 void
391 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
392 		     uint32_t count, bool arm)
393 {
394 	struct lpfc_register doorbell;
395 
396 	/* sanity check on queue memory */
397 	if (unlikely(!q || (count == 0 && !arm)))
398 		return;
399 
400 	/* ring doorbell for number popped */
401 	doorbell.word0 = 0;
402 	if (arm) {
403 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
404 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
405 	}
406 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
407 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
408 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
409 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
410 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
411 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
412 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
413 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
414 		readl(q->phba->sli4_hba.EQDBregaddr);
415 }
416 
417 /**
418  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
419  * @phba: adapter with EQ
420  * @q: The Event Queue that the host has completed processing for.
421  * @count: Number of elements that have been consumed
422  * @arm: Indicates whether the host wants to arms this CQ.
423  *
424  * This routine will notify the HBA, by ringing the doorbell, that count
425  * number of EQEs have been processed. The @arm parameter indicates whether
426  * the queue should be rearmed when ringing the doorbell.
427  **/
428 void
429 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
430 			  uint32_t count, bool arm)
431 {
432 	struct lpfc_register doorbell;
433 
434 	/* sanity check on queue memory */
435 	if (unlikely(!q || (count == 0 && !arm)))
436 		return;
437 
438 	/* ring doorbell for number popped */
439 	doorbell.word0 = 0;
440 	if (arm)
441 		bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
442 	bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
443 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
444 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
445 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
446 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
447 		readl(q->phba->sli4_hba.EQDBregaddr);
448 }
449 
450 static void
451 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
452 			struct lpfc_eqe *eqe)
453 {
454 	if (!phba->sli4_hba.pc_sli4_params.eqav)
455 		bf_set_le32(lpfc_eqe_valid, eqe, 0);
456 
457 	eq->host_index = ((eq->host_index + 1) % eq->entry_count);
458 
459 	/* if the index wrapped around, toggle the valid bit */
460 	if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
461 		eq->qe_valid = (eq->qe_valid) ? 0 : 1;
462 }
463 
464 static void
465 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
466 {
467 	struct lpfc_eqe *eqe = NULL;
468 	u32 eq_count = 0, cq_count = 0;
469 	struct lpfc_cqe *cqe = NULL;
470 	struct lpfc_queue *cq = NULL, *childq = NULL;
471 	int cqid = 0;
472 
473 	/* walk all the EQ entries and drop on the floor */
474 	eqe = lpfc_sli4_eq_get(eq);
475 	while (eqe) {
476 		/* Get the reference to the corresponding CQ */
477 		cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
478 		cq = NULL;
479 
480 		list_for_each_entry(childq, &eq->child_list, list) {
481 			if (childq->queue_id == cqid) {
482 				cq = childq;
483 				break;
484 			}
485 		}
486 		/* If CQ is valid, iterate through it and drop all the CQEs */
487 		if (cq) {
488 			cqe = lpfc_sli4_cq_get(cq);
489 			while (cqe) {
490 				__lpfc_sli4_consume_cqe(phba, cq, cqe);
491 				cq_count++;
492 				cqe = lpfc_sli4_cq_get(cq);
493 			}
494 			/* Clear and re-arm the CQ */
495 			phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
496 			    LPFC_QUEUE_REARM);
497 			cq_count = 0;
498 		}
499 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
500 		eq_count++;
501 		eqe = lpfc_sli4_eq_get(eq);
502 	}
503 
504 	/* Clear and re-arm the EQ */
505 	phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
506 }
507 
508 static int
509 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
510 		     uint8_t rearm)
511 {
512 	struct lpfc_eqe *eqe;
513 	int count = 0, consumed = 0;
514 
515 	if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
516 		goto rearm_and_exit;
517 
518 	eqe = lpfc_sli4_eq_get(eq);
519 	while (eqe) {
520 		lpfc_sli4_hba_handle_eqe(phba, eq, eqe);
521 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
522 
523 		consumed++;
524 		if (!(++count % eq->max_proc_limit))
525 			break;
526 
527 		if (!(count % eq->notify_interval)) {
528 			phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
529 							LPFC_QUEUE_NOARM);
530 			consumed = 0;
531 		}
532 
533 		eqe = lpfc_sli4_eq_get(eq);
534 	}
535 	eq->EQ_processed += count;
536 
537 	/* Track the max number of EQEs processed in 1 intr */
538 	if (count > eq->EQ_max_eqe)
539 		eq->EQ_max_eqe = count;
540 
541 	eq->queue_claimed = 0;
542 
543 rearm_and_exit:
544 	/* Always clear the EQ. */
545 	phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
546 
547 	return count;
548 }
549 
550 /**
551  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
552  * @q: The Completion Queue to get the first valid CQE from
553  *
554  * This routine will get the first valid Completion Queue Entry from @q, update
555  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
556  * the Queue (no more work to do), or the Queue is full of CQEs that have been
557  * processed, but not popped back to the HBA then this routine will return NULL.
558  **/
559 static struct lpfc_cqe *
560 lpfc_sli4_cq_get(struct lpfc_queue *q)
561 {
562 	struct lpfc_cqe *cqe;
563 
564 	/* sanity check on queue memory */
565 	if (unlikely(!q))
566 		return NULL;
567 	cqe = lpfc_sli4_qe(q, q->host_index);
568 
569 	/* If the next CQE is not valid then we are done */
570 	if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
571 		return NULL;
572 
573 	/*
574 	 * insert barrier for instruction interlock : data from the hardware
575 	 * must have the valid bit checked before it can be copied and acted
576 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
577 	 * instructions allowing action on content before valid bit checked,
578 	 * add barrier here as well. May not be needed as "content" is a
579 	 * single 32-bit entity here (vs multi word structure for cq's).
580 	 */
581 	mb();
582 	return cqe;
583 }
584 
585 static void
586 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
587 			struct lpfc_cqe *cqe)
588 {
589 	if (!phba->sli4_hba.pc_sli4_params.cqav)
590 		bf_set_le32(lpfc_cqe_valid, cqe, 0);
591 
592 	cq->host_index = ((cq->host_index + 1) % cq->entry_count);
593 
594 	/* if the index wrapped around, toggle the valid bit */
595 	if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
596 		cq->qe_valid = (cq->qe_valid) ? 0 : 1;
597 }
598 
599 /**
600  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
601  * @phba: the adapter with the CQ
602  * @q: The Completion Queue that the host has completed processing for.
603  * @count: the number of elements that were consumed
604  * @arm: Indicates whether the host wants to arms this CQ.
605  *
606  * This routine will notify the HBA, by ringing the doorbell, that the
607  * CQEs have been processed. The @arm parameter specifies whether the
608  * queue should be rearmed when ringing the doorbell.
609  **/
610 void
611 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
612 		     uint32_t count, bool arm)
613 {
614 	struct lpfc_register doorbell;
615 
616 	/* sanity check on queue memory */
617 	if (unlikely(!q || (count == 0 && !arm)))
618 		return;
619 
620 	/* ring doorbell for number popped */
621 	doorbell.word0 = 0;
622 	if (arm)
623 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
624 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
625 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
626 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
627 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
628 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
629 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
630 }
631 
632 /**
633  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
634  * @phba: the adapter with the CQ
635  * @q: The Completion Queue that the host has completed processing for.
636  * @count: the number of elements that were consumed
637  * @arm: Indicates whether the host wants to arms this CQ.
638  *
639  * This routine will notify the HBA, by ringing the doorbell, that the
640  * CQEs have been processed. The @arm parameter specifies whether the
641  * queue should be rearmed when ringing the doorbell.
642  **/
643 void
644 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
645 			 uint32_t count, bool arm)
646 {
647 	struct lpfc_register doorbell;
648 
649 	/* sanity check on queue memory */
650 	if (unlikely(!q || (count == 0 && !arm)))
651 		return;
652 
653 	/* ring doorbell for number popped */
654 	doorbell.word0 = 0;
655 	if (arm)
656 		bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
657 	bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
658 	bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
659 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
660 }
661 
662 /**
663  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
664  * @q: The Header Receive Queue to operate on.
665  * @wqe: The Receive Queue Entry to put on the Receive queue.
666  *
667  * This routine will copy the contents of @wqe to the next available entry on
668  * the @q. This function will then ring the Receive Queue Doorbell to signal the
669  * HBA to start processing the Receive Queue Entry. This function returns the
670  * index that the rqe was copied to if successful. If no entries are available
671  * on @q then this function will return -ENOMEM.
672  * The caller is expected to hold the hbalock when calling this routine.
673  **/
674 int
675 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
676 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
677 {
678 	struct lpfc_rqe *temp_hrqe;
679 	struct lpfc_rqe *temp_drqe;
680 	struct lpfc_register doorbell;
681 	int hq_put_index;
682 	int dq_put_index;
683 
684 	/* sanity check on queue memory */
685 	if (unlikely(!hq) || unlikely(!dq))
686 		return -ENOMEM;
687 	hq_put_index = hq->host_index;
688 	dq_put_index = dq->host_index;
689 	temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
690 	temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
691 
692 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
693 		return -EINVAL;
694 	if (hq_put_index != dq_put_index)
695 		return -EINVAL;
696 	/* If the host has not yet processed the next entry then we are done */
697 	if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
698 		return -EBUSY;
699 	lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
700 	lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
701 
702 	/* Update the host index to point to the next slot */
703 	hq->host_index = ((hq_put_index + 1) % hq->entry_count);
704 	dq->host_index = ((dq_put_index + 1) % dq->entry_count);
705 	hq->RQ_buf_posted++;
706 
707 	/* Ring The Header Receive Queue Doorbell */
708 	if (!(hq->host_index % hq->notify_interval)) {
709 		doorbell.word0 = 0;
710 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
711 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
712 			       hq->notify_interval);
713 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
714 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
715 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
716 			       hq->notify_interval);
717 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
718 			       hq->host_index);
719 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
720 		} else {
721 			return -EINVAL;
722 		}
723 		writel(doorbell.word0, hq->db_regaddr);
724 	}
725 	return hq_put_index;
726 }
727 
728 /**
729  * lpfc_sli4_rq_release - Updates internal hba index for RQ
730  * @q: The Header Receive Queue to operate on.
731  *
732  * This routine will update the HBA index of a queue to reflect consumption of
733  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
734  * consumed an entry the host calls this function to update the queue's
735  * internal pointers. This routine returns the number of entries that were
736  * consumed by the HBA.
737  **/
738 static uint32_t
739 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
740 {
741 	/* sanity check on queue memory */
742 	if (unlikely(!hq) || unlikely(!dq))
743 		return 0;
744 
745 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
746 		return 0;
747 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
748 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
749 	return 1;
750 }
751 
752 /**
753  * lpfc_cmd_iocb - Get next command iocb entry in the ring
754  * @phba: Pointer to HBA context object.
755  * @pring: Pointer to driver SLI ring object.
756  *
757  * This function returns pointer to next command iocb entry
758  * in the command ring. The caller must hold hbalock to prevent
759  * other threads consume the next command iocb.
760  * SLI-2/SLI-3 provide different sized iocbs.
761  **/
762 static inline IOCB_t *
763 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
764 {
765 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
766 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
767 }
768 
769 /**
770  * lpfc_resp_iocb - Get next response iocb entry in the ring
771  * @phba: Pointer to HBA context object.
772  * @pring: Pointer to driver SLI ring object.
773  *
774  * This function returns pointer to next response iocb entry
775  * in the response ring. The caller must hold hbalock to make sure
776  * that no other thread consume the next response iocb.
777  * SLI-2/SLI-3 provide different sized iocbs.
778  **/
779 static inline IOCB_t *
780 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
781 {
782 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
783 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
784 }
785 
786 /**
787  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
788  * @phba: Pointer to HBA context object.
789  *
790  * This function is called with hbalock held. This function
791  * allocates a new driver iocb object from the iocb pool. If the
792  * allocation is successful, it returns pointer to the newly
793  * allocated iocb object else it returns NULL.
794  **/
795 struct lpfc_iocbq *
796 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
797 {
798 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
799 	struct lpfc_iocbq * iocbq = NULL;
800 
801 	lockdep_assert_held(&phba->hbalock);
802 
803 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
804 	if (iocbq)
805 		phba->iocb_cnt++;
806 	if (phba->iocb_cnt > phba->iocb_max)
807 		phba->iocb_max = phba->iocb_cnt;
808 	return iocbq;
809 }
810 
811 /**
812  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
813  * @phba: Pointer to HBA context object.
814  * @xritag: XRI value.
815  *
816  * This function clears the sglq pointer from the array of acive
817  * sglq's. The xritag that is passed in is used to index into the
818  * array. Before the xritag can be used it needs to be adjusted
819  * by subtracting the xribase.
820  *
821  * Returns sglq ponter = success, NULL = Failure.
822  **/
823 struct lpfc_sglq *
824 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
825 {
826 	struct lpfc_sglq *sglq;
827 
828 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
829 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
830 	return sglq;
831 }
832 
833 /**
834  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
835  * @phba: Pointer to HBA context object.
836  * @xritag: XRI value.
837  *
838  * This function returns the sglq pointer from the array of acive
839  * sglq's. The xritag that is passed in is used to index into the
840  * array. Before the xritag can be used it needs to be adjusted
841  * by subtracting the xribase.
842  *
843  * Returns sglq ponter = success, NULL = Failure.
844  **/
845 struct lpfc_sglq *
846 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
847 {
848 	struct lpfc_sglq *sglq;
849 
850 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
851 	return sglq;
852 }
853 
854 /**
855  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
856  * @phba: Pointer to HBA context object.
857  * @xritag: xri used in this exchange.
858  * @rrq: The RRQ to be cleared.
859  *
860  **/
861 void
862 lpfc_clr_rrq_active(struct lpfc_hba *phba,
863 		    uint16_t xritag,
864 		    struct lpfc_node_rrq *rrq)
865 {
866 	struct lpfc_nodelist *ndlp = NULL;
867 
868 	if ((rrq->vport) && NLP_CHK_NODE_ACT(rrq->ndlp))
869 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
870 
871 	/* The target DID could have been swapped (cable swap)
872 	 * we should use the ndlp from the findnode if it is
873 	 * available.
874 	 */
875 	if ((!ndlp) && rrq->ndlp)
876 		ndlp = rrq->ndlp;
877 
878 	if (!ndlp)
879 		goto out;
880 
881 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
882 		rrq->send_rrq = 0;
883 		rrq->xritag = 0;
884 		rrq->rrq_stop_time = 0;
885 	}
886 out:
887 	mempool_free(rrq, phba->rrq_pool);
888 }
889 
890 /**
891  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
892  * @phba: Pointer to HBA context object.
893  *
894  * This function is called with hbalock held. This function
895  * Checks if stop_time (ratov from setting rrq active) has
896  * been reached, if it has and the send_rrq flag is set then
897  * it will call lpfc_send_rrq. If the send_rrq flag is not set
898  * then it will just call the routine to clear the rrq and
899  * free the rrq resource.
900  * The timer is set to the next rrq that is going to expire before
901  * leaving the routine.
902  *
903  **/
904 void
905 lpfc_handle_rrq_active(struct lpfc_hba *phba)
906 {
907 	struct lpfc_node_rrq *rrq;
908 	struct lpfc_node_rrq *nextrrq;
909 	unsigned long next_time;
910 	unsigned long iflags;
911 	LIST_HEAD(send_rrq);
912 
913 	spin_lock_irqsave(&phba->hbalock, iflags);
914 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
915 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
916 	list_for_each_entry_safe(rrq, nextrrq,
917 				 &phba->active_rrq_list, list) {
918 		if (time_after(jiffies, rrq->rrq_stop_time))
919 			list_move(&rrq->list, &send_rrq);
920 		else if (time_before(rrq->rrq_stop_time, next_time))
921 			next_time = rrq->rrq_stop_time;
922 	}
923 	spin_unlock_irqrestore(&phba->hbalock, iflags);
924 	if ((!list_empty(&phba->active_rrq_list)) &&
925 	    (!(phba->pport->load_flag & FC_UNLOADING)))
926 		mod_timer(&phba->rrq_tmr, next_time);
927 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
928 		list_del(&rrq->list);
929 		if (!rrq->send_rrq) {
930 			/* this call will free the rrq */
931 			lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
932 		} else if (lpfc_send_rrq(phba, rrq)) {
933 			/* if we send the rrq then the completion handler
934 			*  will clear the bit in the xribitmap.
935 			*/
936 			lpfc_clr_rrq_active(phba, rrq->xritag,
937 					    rrq);
938 		}
939 	}
940 }
941 
942 /**
943  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
944  * @vport: Pointer to vport context object.
945  * @xri: The xri used in the exchange.
946  * @did: The targets DID for this exchange.
947  *
948  * returns NULL = rrq not found in the phba->active_rrq_list.
949  *         rrq = rrq for this xri and target.
950  **/
951 struct lpfc_node_rrq *
952 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
953 {
954 	struct lpfc_hba *phba = vport->phba;
955 	struct lpfc_node_rrq *rrq;
956 	struct lpfc_node_rrq *nextrrq;
957 	unsigned long iflags;
958 
959 	if (phba->sli_rev != LPFC_SLI_REV4)
960 		return NULL;
961 	spin_lock_irqsave(&phba->hbalock, iflags);
962 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
963 		if (rrq->vport == vport && rrq->xritag == xri &&
964 				rrq->nlp_DID == did){
965 			list_del(&rrq->list);
966 			spin_unlock_irqrestore(&phba->hbalock, iflags);
967 			return rrq;
968 		}
969 	}
970 	spin_unlock_irqrestore(&phba->hbalock, iflags);
971 	return NULL;
972 }
973 
974 /**
975  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
976  * @vport: Pointer to vport context object.
977  * @ndlp: Pointer to the lpfc_node_list structure.
978  * If ndlp is NULL Remove all active RRQs for this vport from the
979  * phba->active_rrq_list and clear the rrq.
980  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
981  **/
982 void
983 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
984 
985 {
986 	struct lpfc_hba *phba = vport->phba;
987 	struct lpfc_node_rrq *rrq;
988 	struct lpfc_node_rrq *nextrrq;
989 	unsigned long iflags;
990 	LIST_HEAD(rrq_list);
991 
992 	if (phba->sli_rev != LPFC_SLI_REV4)
993 		return;
994 	if (!ndlp) {
995 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
996 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
997 	}
998 	spin_lock_irqsave(&phba->hbalock, iflags);
999 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list)
1000 		if ((rrq->vport == vport) && (!ndlp  || rrq->ndlp == ndlp))
1001 			list_move(&rrq->list, &rrq_list);
1002 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1003 
1004 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1005 		list_del(&rrq->list);
1006 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1007 	}
1008 }
1009 
1010 /**
1011  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1012  * @phba: Pointer to HBA context object.
1013  * @ndlp: Targets nodelist pointer for this exchange.
1014  * @xritag the xri in the bitmap to test.
1015  *
1016  * This function returns:
1017  * 0 = rrq not active for this xri
1018  * 1 = rrq is valid for this xri.
1019  **/
1020 int
1021 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1022 			uint16_t  xritag)
1023 {
1024 	if (!ndlp)
1025 		return 0;
1026 	if (!ndlp->active_rrqs_xri_bitmap)
1027 		return 0;
1028 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1029 		return 1;
1030 	else
1031 		return 0;
1032 }
1033 
1034 /**
1035  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1036  * @phba: Pointer to HBA context object.
1037  * @ndlp: nodelist pointer for this target.
1038  * @xritag: xri used in this exchange.
1039  * @rxid: Remote Exchange ID.
1040  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1041  *
1042  * This function takes the hbalock.
1043  * The active bit is always set in the active rrq xri_bitmap even
1044  * if there is no slot avaiable for the other rrq information.
1045  *
1046  * returns 0 rrq actived for this xri
1047  *         < 0 No memory or invalid ndlp.
1048  **/
1049 int
1050 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1051 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1052 {
1053 	unsigned long iflags;
1054 	struct lpfc_node_rrq *rrq;
1055 	int empty;
1056 
1057 	if (!ndlp)
1058 		return -EINVAL;
1059 
1060 	if (!phba->cfg_enable_rrq)
1061 		return -EINVAL;
1062 
1063 	spin_lock_irqsave(&phba->hbalock, iflags);
1064 	if (phba->pport->load_flag & FC_UNLOADING) {
1065 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1066 		goto out;
1067 	}
1068 
1069 	/*
1070 	 * set the active bit even if there is no mem available.
1071 	 */
1072 	if (NLP_CHK_FREE_REQ(ndlp))
1073 		goto out;
1074 
1075 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
1076 		goto out;
1077 
1078 	if (!ndlp->active_rrqs_xri_bitmap)
1079 		goto out;
1080 
1081 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1082 		goto out;
1083 
1084 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1085 	rrq = mempool_alloc(phba->rrq_pool, GFP_KERNEL);
1086 	if (!rrq) {
1087 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1088 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1089 				" DID:0x%x Send:%d\n",
1090 				xritag, rxid, ndlp->nlp_DID, send_rrq);
1091 		return -EINVAL;
1092 	}
1093 	if (phba->cfg_enable_rrq == 1)
1094 		rrq->send_rrq = send_rrq;
1095 	else
1096 		rrq->send_rrq = 0;
1097 	rrq->xritag = xritag;
1098 	rrq->rrq_stop_time = jiffies +
1099 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1100 	rrq->ndlp = ndlp;
1101 	rrq->nlp_DID = ndlp->nlp_DID;
1102 	rrq->vport = ndlp->vport;
1103 	rrq->rxid = rxid;
1104 	spin_lock_irqsave(&phba->hbalock, iflags);
1105 	empty = list_empty(&phba->active_rrq_list);
1106 	list_add_tail(&rrq->list, &phba->active_rrq_list);
1107 	phba->hba_flag |= HBA_RRQ_ACTIVE;
1108 	if (empty)
1109 		lpfc_worker_wake_up(phba);
1110 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1111 	return 0;
1112 out:
1113 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1114 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1115 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
1116 			" DID:0x%x Send:%d\n",
1117 			xritag, rxid, ndlp->nlp_DID, send_rrq);
1118 	return -EINVAL;
1119 }
1120 
1121 /**
1122  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1123  * @phba: Pointer to HBA context object.
1124  * @piocb: Pointer to the iocbq.
1125  *
1126  * The driver calls this function with either the nvme ls ring lock
1127  * or the fc els ring lock held depending on the iocb usage.  This function
1128  * gets a new driver sglq object from the sglq list. If the list is not empty
1129  * then it is successful, it returns pointer to the newly allocated sglq
1130  * object else it returns NULL.
1131  **/
1132 static struct lpfc_sglq *
1133 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1134 {
1135 	struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1136 	struct lpfc_sglq *sglq = NULL;
1137 	struct lpfc_sglq *start_sglq = NULL;
1138 	struct lpfc_io_buf *lpfc_cmd;
1139 	struct lpfc_nodelist *ndlp;
1140 	struct lpfc_sli_ring *pring = NULL;
1141 	int found = 0;
1142 
1143 	if (piocbq->iocb_flag & LPFC_IO_NVME_LS)
1144 		pring =  phba->sli4_hba.nvmels_wq->pring;
1145 	else
1146 		pring = lpfc_phba_elsring(phba);
1147 
1148 	lockdep_assert_held(&pring->ring_lock);
1149 
1150 	if (piocbq->iocb_flag &  LPFC_IO_FCP) {
1151 		lpfc_cmd = (struct lpfc_io_buf *) piocbq->context1;
1152 		ndlp = lpfc_cmd->rdata->pnode;
1153 	} else  if ((piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) &&
1154 			!(piocbq->iocb_flag & LPFC_IO_LIBDFC)) {
1155 		ndlp = piocbq->context_un.ndlp;
1156 	} else  if (piocbq->iocb_flag & LPFC_IO_LIBDFC) {
1157 		if (piocbq->iocb_flag & LPFC_IO_LOOPBACK)
1158 			ndlp = NULL;
1159 		else
1160 			ndlp = piocbq->context_un.ndlp;
1161 	} else {
1162 		ndlp = piocbq->context1;
1163 	}
1164 
1165 	spin_lock(&phba->sli4_hba.sgl_list_lock);
1166 	list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1167 	start_sglq = sglq;
1168 	while (!found) {
1169 		if (!sglq)
1170 			break;
1171 		if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1172 		    test_bit(sglq->sli4_lxritag,
1173 		    ndlp->active_rrqs_xri_bitmap)) {
1174 			/* This xri has an rrq outstanding for this DID.
1175 			 * put it back in the list and get another xri.
1176 			 */
1177 			list_add_tail(&sglq->list, lpfc_els_sgl_list);
1178 			sglq = NULL;
1179 			list_remove_head(lpfc_els_sgl_list, sglq,
1180 						struct lpfc_sglq, list);
1181 			if (sglq == start_sglq) {
1182 				list_add_tail(&sglq->list, lpfc_els_sgl_list);
1183 				sglq = NULL;
1184 				break;
1185 			} else
1186 				continue;
1187 		}
1188 		sglq->ndlp = ndlp;
1189 		found = 1;
1190 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1191 		sglq->state = SGL_ALLOCATED;
1192 	}
1193 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
1194 	return sglq;
1195 }
1196 
1197 /**
1198  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1199  * @phba: Pointer to HBA context object.
1200  * @piocb: Pointer to the iocbq.
1201  *
1202  * This function is called with the sgl_list lock held. This function
1203  * gets a new driver sglq object from the sglq list. If the
1204  * list is not empty then it is successful, it returns pointer to the newly
1205  * allocated sglq object else it returns NULL.
1206  **/
1207 struct lpfc_sglq *
1208 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1209 {
1210 	struct list_head *lpfc_nvmet_sgl_list;
1211 	struct lpfc_sglq *sglq = NULL;
1212 
1213 	lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1214 
1215 	lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1216 
1217 	list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1218 	if (!sglq)
1219 		return NULL;
1220 	phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1221 	sglq->state = SGL_ALLOCATED;
1222 	return sglq;
1223 }
1224 
1225 /**
1226  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1227  * @phba: Pointer to HBA context object.
1228  *
1229  * This function is called with no lock held. This function
1230  * allocates a new driver iocb object from the iocb pool. If the
1231  * allocation is successful, it returns pointer to the newly
1232  * allocated iocb object else it returns NULL.
1233  **/
1234 struct lpfc_iocbq *
1235 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1236 {
1237 	struct lpfc_iocbq * iocbq = NULL;
1238 	unsigned long iflags;
1239 
1240 	spin_lock_irqsave(&phba->hbalock, iflags);
1241 	iocbq = __lpfc_sli_get_iocbq(phba);
1242 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1243 	return iocbq;
1244 }
1245 
1246 /**
1247  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1248  * @phba: Pointer to HBA context object.
1249  * @iocbq: Pointer to driver iocb object.
1250  *
1251  * This function is called with hbalock held to release driver
1252  * iocb object to the iocb pool. The iotag in the iocb object
1253  * does not change for each use of the iocb object. This function
1254  * clears all other fields of the iocb object when it is freed.
1255  * The sqlq structure that holds the xritag and phys and virtual
1256  * mappings for the scatter gather list is retrieved from the
1257  * active array of sglq. The get of the sglq pointer also clears
1258  * the entry in the array. If the status of the IO indiactes that
1259  * this IO was aborted then the sglq entry it put on the
1260  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1261  * IO has good status or fails for any other reason then the sglq
1262  * entry is added to the free list (lpfc_els_sgl_list).
1263  **/
1264 static void
1265 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1266 {
1267 	struct lpfc_sglq *sglq;
1268 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1269 	unsigned long iflag = 0;
1270 	struct lpfc_sli_ring *pring;
1271 
1272 	lockdep_assert_held(&phba->hbalock);
1273 
1274 	if (iocbq->sli4_xritag == NO_XRI)
1275 		sglq = NULL;
1276 	else
1277 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1278 
1279 
1280 	if (sglq)  {
1281 		if (iocbq->iocb_flag & LPFC_IO_NVMET) {
1282 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1283 					  iflag);
1284 			sglq->state = SGL_FREED;
1285 			sglq->ndlp = NULL;
1286 			list_add_tail(&sglq->list,
1287 				      &phba->sli4_hba.lpfc_nvmet_sgl_list);
1288 			spin_unlock_irqrestore(
1289 				&phba->sli4_hba.sgl_list_lock, iflag);
1290 			goto out;
1291 		}
1292 
1293 		pring = phba->sli4_hba.els_wq->pring;
1294 		if ((iocbq->iocb_flag & LPFC_EXCHANGE_BUSY) &&
1295 			(sglq->state != SGL_XRI_ABORTED)) {
1296 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1297 					  iflag);
1298 			list_add(&sglq->list,
1299 				 &phba->sli4_hba.lpfc_abts_els_sgl_list);
1300 			spin_unlock_irqrestore(
1301 				&phba->sli4_hba.sgl_list_lock, iflag);
1302 		} else {
1303 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1304 					  iflag);
1305 			sglq->state = SGL_FREED;
1306 			sglq->ndlp = NULL;
1307 			list_add_tail(&sglq->list,
1308 				      &phba->sli4_hba.lpfc_els_sgl_list);
1309 			spin_unlock_irqrestore(
1310 				&phba->sli4_hba.sgl_list_lock, iflag);
1311 
1312 			/* Check if TXQ queue needs to be serviced */
1313 			if (!list_empty(&pring->txq))
1314 				lpfc_worker_wake_up(phba);
1315 		}
1316 	}
1317 
1318 out:
1319 	/*
1320 	 * Clean all volatile data fields, preserve iotag and node struct.
1321 	 */
1322 	memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1323 	iocbq->sli4_lxritag = NO_XRI;
1324 	iocbq->sli4_xritag = NO_XRI;
1325 	iocbq->iocb_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET |
1326 			      LPFC_IO_NVME_LS);
1327 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1328 }
1329 
1330 
1331 /**
1332  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1333  * @phba: Pointer to HBA context object.
1334  * @iocbq: Pointer to driver iocb object.
1335  *
1336  * This function is called with hbalock held to release driver
1337  * iocb object to the iocb pool. The iotag in the iocb object
1338  * does not change for each use of the iocb object. This function
1339  * clears all other fields of the iocb object when it is freed.
1340  **/
1341 static void
1342 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1343 {
1344 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1345 
1346 	lockdep_assert_held(&phba->hbalock);
1347 
1348 	/*
1349 	 * Clean all volatile data fields, preserve iotag and node struct.
1350 	 */
1351 	memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1352 	iocbq->sli4_xritag = NO_XRI;
1353 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1354 }
1355 
1356 /**
1357  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1358  * @phba: Pointer to HBA context object.
1359  * @iocbq: Pointer to driver iocb object.
1360  *
1361  * This function is called with hbalock held to release driver
1362  * iocb object to the iocb pool. The iotag in the iocb object
1363  * does not change for each use of the iocb object. This function
1364  * clears all other fields of the iocb object when it is freed.
1365  **/
1366 static void
1367 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1368 {
1369 	lockdep_assert_held(&phba->hbalock);
1370 
1371 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1372 	phba->iocb_cnt--;
1373 }
1374 
1375 /**
1376  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1377  * @phba: Pointer to HBA context object.
1378  * @iocbq: Pointer to driver iocb object.
1379  *
1380  * This function is called with no lock held to release the iocb to
1381  * iocb pool.
1382  **/
1383 void
1384 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1385 {
1386 	unsigned long iflags;
1387 
1388 	/*
1389 	 * Clean all volatile data fields, preserve iotag and node struct.
1390 	 */
1391 	spin_lock_irqsave(&phba->hbalock, iflags);
1392 	__lpfc_sli_release_iocbq(phba, iocbq);
1393 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1394 }
1395 
1396 /**
1397  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1398  * @phba: Pointer to HBA context object.
1399  * @iocblist: List of IOCBs.
1400  * @ulpstatus: ULP status in IOCB command field.
1401  * @ulpWord4: ULP word-4 in IOCB command field.
1402  *
1403  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1404  * on the list by invoking the complete callback function associated with the
1405  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1406  * fields.
1407  **/
1408 void
1409 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1410 		      uint32_t ulpstatus, uint32_t ulpWord4)
1411 {
1412 	struct lpfc_iocbq *piocb;
1413 
1414 	while (!list_empty(iocblist)) {
1415 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1416 		if (!piocb->iocb_cmpl) {
1417 			if (piocb->iocb_flag & LPFC_IO_NVME)
1418 				lpfc_nvme_cancel_iocb(phba, piocb);
1419 			else
1420 				lpfc_sli_release_iocbq(phba, piocb);
1421 		} else {
1422 			piocb->iocb.ulpStatus = ulpstatus;
1423 			piocb->iocb.un.ulpWord[4] = ulpWord4;
1424 			(piocb->iocb_cmpl) (phba, piocb, piocb);
1425 		}
1426 	}
1427 	return;
1428 }
1429 
1430 /**
1431  * lpfc_sli_iocb_cmd_type - Get the iocb type
1432  * @iocb_cmnd: iocb command code.
1433  *
1434  * This function is called by ring event handler function to get the iocb type.
1435  * This function translates the iocb command to an iocb command type used to
1436  * decide the final disposition of each completed IOCB.
1437  * The function returns
1438  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1439  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1440  * LPFC_ABORT_IOCB   if it is an abort iocb
1441  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1442  *
1443  * The caller is not required to hold any lock.
1444  **/
1445 static lpfc_iocb_type
1446 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1447 {
1448 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1449 
1450 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1451 		return 0;
1452 
1453 	switch (iocb_cmnd) {
1454 	case CMD_XMIT_SEQUENCE_CR:
1455 	case CMD_XMIT_SEQUENCE_CX:
1456 	case CMD_XMIT_BCAST_CN:
1457 	case CMD_XMIT_BCAST_CX:
1458 	case CMD_ELS_REQUEST_CR:
1459 	case CMD_ELS_REQUEST_CX:
1460 	case CMD_CREATE_XRI_CR:
1461 	case CMD_CREATE_XRI_CX:
1462 	case CMD_GET_RPI_CN:
1463 	case CMD_XMIT_ELS_RSP_CX:
1464 	case CMD_GET_RPI_CR:
1465 	case CMD_FCP_IWRITE_CR:
1466 	case CMD_FCP_IWRITE_CX:
1467 	case CMD_FCP_IREAD_CR:
1468 	case CMD_FCP_IREAD_CX:
1469 	case CMD_FCP_ICMND_CR:
1470 	case CMD_FCP_ICMND_CX:
1471 	case CMD_FCP_TSEND_CX:
1472 	case CMD_FCP_TRSP_CX:
1473 	case CMD_FCP_TRECEIVE_CX:
1474 	case CMD_FCP_AUTO_TRSP_CX:
1475 	case CMD_ADAPTER_MSG:
1476 	case CMD_ADAPTER_DUMP:
1477 	case CMD_XMIT_SEQUENCE64_CR:
1478 	case CMD_XMIT_SEQUENCE64_CX:
1479 	case CMD_XMIT_BCAST64_CN:
1480 	case CMD_XMIT_BCAST64_CX:
1481 	case CMD_ELS_REQUEST64_CR:
1482 	case CMD_ELS_REQUEST64_CX:
1483 	case CMD_FCP_IWRITE64_CR:
1484 	case CMD_FCP_IWRITE64_CX:
1485 	case CMD_FCP_IREAD64_CR:
1486 	case CMD_FCP_IREAD64_CX:
1487 	case CMD_FCP_ICMND64_CR:
1488 	case CMD_FCP_ICMND64_CX:
1489 	case CMD_FCP_TSEND64_CX:
1490 	case CMD_FCP_TRSP64_CX:
1491 	case CMD_FCP_TRECEIVE64_CX:
1492 	case CMD_GEN_REQUEST64_CR:
1493 	case CMD_GEN_REQUEST64_CX:
1494 	case CMD_XMIT_ELS_RSP64_CX:
1495 	case DSSCMD_IWRITE64_CR:
1496 	case DSSCMD_IWRITE64_CX:
1497 	case DSSCMD_IREAD64_CR:
1498 	case DSSCMD_IREAD64_CX:
1499 		type = LPFC_SOL_IOCB;
1500 		break;
1501 	case CMD_ABORT_XRI_CN:
1502 	case CMD_ABORT_XRI_CX:
1503 	case CMD_CLOSE_XRI_CN:
1504 	case CMD_CLOSE_XRI_CX:
1505 	case CMD_XRI_ABORTED_CX:
1506 	case CMD_ABORT_MXRI64_CN:
1507 	case CMD_XMIT_BLS_RSP64_CX:
1508 		type = LPFC_ABORT_IOCB;
1509 		break;
1510 	case CMD_RCV_SEQUENCE_CX:
1511 	case CMD_RCV_ELS_REQ_CX:
1512 	case CMD_RCV_SEQUENCE64_CX:
1513 	case CMD_RCV_ELS_REQ64_CX:
1514 	case CMD_ASYNC_STATUS:
1515 	case CMD_IOCB_RCV_SEQ64_CX:
1516 	case CMD_IOCB_RCV_ELS64_CX:
1517 	case CMD_IOCB_RCV_CONT64_CX:
1518 	case CMD_IOCB_RET_XRI64_CX:
1519 		type = LPFC_UNSOL_IOCB;
1520 		break;
1521 	case CMD_IOCB_XMIT_MSEQ64_CR:
1522 	case CMD_IOCB_XMIT_MSEQ64_CX:
1523 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1524 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1525 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1526 	case CMD_IOCB_ABORT_EXTENDED_CN:
1527 	case CMD_IOCB_RET_HBQE64_CN:
1528 	case CMD_IOCB_FCP_IBIDIR64_CR:
1529 	case CMD_IOCB_FCP_IBIDIR64_CX:
1530 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1531 	case CMD_IOCB_LOGENTRY_CN:
1532 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1533 		printk("%s - Unhandled SLI-3 Command x%x\n",
1534 				__func__, iocb_cmnd);
1535 		type = LPFC_UNKNOWN_IOCB;
1536 		break;
1537 	default:
1538 		type = LPFC_UNKNOWN_IOCB;
1539 		break;
1540 	}
1541 
1542 	return type;
1543 }
1544 
1545 /**
1546  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1547  * @phba: Pointer to HBA context object.
1548  *
1549  * This function is called from SLI initialization code
1550  * to configure every ring of the HBA's SLI interface. The
1551  * caller is not required to hold any lock. This function issues
1552  * a config_ring mailbox command for each ring.
1553  * This function returns zero if successful else returns a negative
1554  * error code.
1555  **/
1556 static int
1557 lpfc_sli_ring_map(struct lpfc_hba *phba)
1558 {
1559 	struct lpfc_sli *psli = &phba->sli;
1560 	LPFC_MBOXQ_t *pmb;
1561 	MAILBOX_t *pmbox;
1562 	int i, rc, ret = 0;
1563 
1564 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1565 	if (!pmb)
1566 		return -ENOMEM;
1567 	pmbox = &pmb->u.mb;
1568 	phba->link_state = LPFC_INIT_MBX_CMDS;
1569 	for (i = 0; i < psli->num_rings; i++) {
1570 		lpfc_config_ring(phba, i, pmb);
1571 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1572 		if (rc != MBX_SUCCESS) {
1573 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1574 					"0446 Adapter failed to init (%d), "
1575 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1576 					"ring %d\n",
1577 					rc, pmbox->mbxCommand,
1578 					pmbox->mbxStatus, i);
1579 			phba->link_state = LPFC_HBA_ERROR;
1580 			ret = -ENXIO;
1581 			break;
1582 		}
1583 	}
1584 	mempool_free(pmb, phba->mbox_mem_pool);
1585 	return ret;
1586 }
1587 
1588 /**
1589  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1590  * @phba: Pointer to HBA context object.
1591  * @pring: Pointer to driver SLI ring object.
1592  * @piocb: Pointer to the driver iocb object.
1593  *
1594  * The driver calls this function with the hbalock held for SLI3 ports or
1595  * the ring lock held for SLI4 ports. The function adds the
1596  * new iocb to txcmplq of the given ring. This function always returns
1597  * 0. If this function is called for ELS ring, this function checks if
1598  * there is a vport associated with the ELS command. This function also
1599  * starts els_tmofunc timer if this is an ELS command.
1600  **/
1601 static int
1602 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1603 			struct lpfc_iocbq *piocb)
1604 {
1605 	if (phba->sli_rev == LPFC_SLI_REV4)
1606 		lockdep_assert_held(&pring->ring_lock);
1607 	else
1608 		lockdep_assert_held(&phba->hbalock);
1609 
1610 	BUG_ON(!piocb);
1611 
1612 	list_add_tail(&piocb->list, &pring->txcmplq);
1613 	piocb->iocb_flag |= LPFC_IO_ON_TXCMPLQ;
1614 	pring->txcmplq_cnt++;
1615 
1616 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1617 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
1618 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
1619 		BUG_ON(!piocb->vport);
1620 		if (!(piocb->vport->load_flag & FC_UNLOADING))
1621 			mod_timer(&piocb->vport->els_tmofunc,
1622 				  jiffies +
1623 				  msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1624 	}
1625 
1626 	return 0;
1627 }
1628 
1629 /**
1630  * lpfc_sli_ringtx_get - Get first element of the txq
1631  * @phba: Pointer to HBA context object.
1632  * @pring: Pointer to driver SLI ring object.
1633  *
1634  * This function is called with hbalock held to get next
1635  * iocb in txq of the given ring. If there is any iocb in
1636  * the txq, the function returns first iocb in the list after
1637  * removing the iocb from the list, else it returns NULL.
1638  **/
1639 struct lpfc_iocbq *
1640 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1641 {
1642 	struct lpfc_iocbq *cmd_iocb;
1643 
1644 	lockdep_assert_held(&phba->hbalock);
1645 
1646 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1647 	return cmd_iocb;
1648 }
1649 
1650 /**
1651  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
1652  * @phba: Pointer to HBA context object.
1653  * @pring: Pointer to driver SLI ring object.
1654  *
1655  * This function is called with hbalock held and the caller must post the
1656  * iocb without releasing the lock. If the caller releases the lock,
1657  * iocb slot returned by the function is not guaranteed to be available.
1658  * The function returns pointer to the next available iocb slot if there
1659  * is available slot in the ring, else it returns NULL.
1660  * If the get index of the ring is ahead of the put index, the function
1661  * will post an error attention event to the worker thread to take the
1662  * HBA to offline state.
1663  **/
1664 static IOCB_t *
1665 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1666 {
1667 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
1668 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
1669 
1670 	lockdep_assert_held(&phba->hbalock);
1671 
1672 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
1673 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
1674 		pring->sli.sli3.next_cmdidx = 0;
1675 
1676 	if (unlikely(pring->sli.sli3.local_getidx ==
1677 		pring->sli.sli3.next_cmdidx)) {
1678 
1679 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
1680 
1681 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
1682 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1683 					"0315 Ring %d issue: portCmdGet %d "
1684 					"is bigger than cmd ring %d\n",
1685 					pring->ringno,
1686 					pring->sli.sli3.local_getidx,
1687 					max_cmd_idx);
1688 
1689 			phba->link_state = LPFC_HBA_ERROR;
1690 			/*
1691 			 * All error attention handlers are posted to
1692 			 * worker thread
1693 			 */
1694 			phba->work_ha |= HA_ERATT;
1695 			phba->work_hs = HS_FFER3;
1696 
1697 			lpfc_worker_wake_up(phba);
1698 
1699 			return NULL;
1700 		}
1701 
1702 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
1703 			return NULL;
1704 	}
1705 
1706 	return lpfc_cmd_iocb(phba, pring);
1707 }
1708 
1709 /**
1710  * lpfc_sli_next_iotag - Get an iotag for the iocb
1711  * @phba: Pointer to HBA context object.
1712  * @iocbq: Pointer to driver iocb object.
1713  *
1714  * This function gets an iotag for the iocb. If there is no unused iotag and
1715  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
1716  * array and assigns a new iotag.
1717  * The function returns the allocated iotag if successful, else returns zero.
1718  * Zero is not a valid iotag.
1719  * The caller is not required to hold any lock.
1720  **/
1721 uint16_t
1722 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1723 {
1724 	struct lpfc_iocbq **new_arr;
1725 	struct lpfc_iocbq **old_arr;
1726 	size_t new_len;
1727 	struct lpfc_sli *psli = &phba->sli;
1728 	uint16_t iotag;
1729 
1730 	spin_lock_irq(&phba->hbalock);
1731 	iotag = psli->last_iotag;
1732 	if(++iotag < psli->iocbq_lookup_len) {
1733 		psli->last_iotag = iotag;
1734 		psli->iocbq_lookup[iotag] = iocbq;
1735 		spin_unlock_irq(&phba->hbalock);
1736 		iocbq->iotag = iotag;
1737 		return iotag;
1738 	} else if (psli->iocbq_lookup_len < (0xffff
1739 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
1740 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
1741 		spin_unlock_irq(&phba->hbalock);
1742 		new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
1743 				  GFP_KERNEL);
1744 		if (new_arr) {
1745 			spin_lock_irq(&phba->hbalock);
1746 			old_arr = psli->iocbq_lookup;
1747 			if (new_len <= psli->iocbq_lookup_len) {
1748 				/* highly unprobable case */
1749 				kfree(new_arr);
1750 				iotag = psli->last_iotag;
1751 				if(++iotag < psli->iocbq_lookup_len) {
1752 					psli->last_iotag = iotag;
1753 					psli->iocbq_lookup[iotag] = iocbq;
1754 					spin_unlock_irq(&phba->hbalock);
1755 					iocbq->iotag = iotag;
1756 					return iotag;
1757 				}
1758 				spin_unlock_irq(&phba->hbalock);
1759 				return 0;
1760 			}
1761 			if (psli->iocbq_lookup)
1762 				memcpy(new_arr, old_arr,
1763 				       ((psli->last_iotag  + 1) *
1764 					sizeof (struct lpfc_iocbq *)));
1765 			psli->iocbq_lookup = new_arr;
1766 			psli->iocbq_lookup_len = new_len;
1767 			psli->last_iotag = iotag;
1768 			psli->iocbq_lookup[iotag] = iocbq;
1769 			spin_unlock_irq(&phba->hbalock);
1770 			iocbq->iotag = iotag;
1771 			kfree(old_arr);
1772 			return iotag;
1773 		}
1774 	} else
1775 		spin_unlock_irq(&phba->hbalock);
1776 
1777 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
1778 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
1779 			psli->last_iotag);
1780 
1781 	return 0;
1782 }
1783 
1784 /**
1785  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
1786  * @phba: Pointer to HBA context object.
1787  * @pring: Pointer to driver SLI ring object.
1788  * @iocb: Pointer to iocb slot in the ring.
1789  * @nextiocb: Pointer to driver iocb object which need to be
1790  *            posted to firmware.
1791  *
1792  * This function is called with hbalock held to post a new iocb to
1793  * the firmware. This function copies the new iocb to ring iocb slot and
1794  * updates the ring pointers. It adds the new iocb to txcmplq if there is
1795  * a completion call back for this iocb else the function will free the
1796  * iocb object.
1797  **/
1798 static void
1799 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1800 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
1801 {
1802 	lockdep_assert_held(&phba->hbalock);
1803 	/*
1804 	 * Set up an iotag
1805 	 */
1806 	nextiocb->iocb.ulpIoTag = (nextiocb->iocb_cmpl) ? nextiocb->iotag : 0;
1807 
1808 
1809 	if (pring->ringno == LPFC_ELS_RING) {
1810 		lpfc_debugfs_slow_ring_trc(phba,
1811 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
1812 			*(((uint32_t *) &nextiocb->iocb) + 4),
1813 			*(((uint32_t *) &nextiocb->iocb) + 6),
1814 			*(((uint32_t *) &nextiocb->iocb) + 7));
1815 	}
1816 
1817 	/*
1818 	 * Issue iocb command to adapter
1819 	 */
1820 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
1821 	wmb();
1822 	pring->stats.iocb_cmd++;
1823 
1824 	/*
1825 	 * If there is no completion routine to call, we can release the
1826 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
1827 	 * that have no rsp ring completion, iocb_cmpl MUST be NULL.
1828 	 */
1829 	if (nextiocb->iocb_cmpl)
1830 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
1831 	else
1832 		__lpfc_sli_release_iocbq(phba, nextiocb);
1833 
1834 	/*
1835 	 * Let the HBA know what IOCB slot will be the next one the
1836 	 * driver will put a command into.
1837 	 */
1838 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
1839 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
1840 }
1841 
1842 /**
1843  * lpfc_sli_update_full_ring - Update the chip attention register
1844  * @phba: Pointer to HBA context object.
1845  * @pring: Pointer to driver SLI ring object.
1846  *
1847  * The caller is not required to hold any lock for calling this function.
1848  * This function updates the chip attention bits for the ring to inform firmware
1849  * that there are pending work to be done for this ring and requests an
1850  * interrupt when there is space available in the ring. This function is
1851  * called when the driver is unable to post more iocbs to the ring due
1852  * to unavailability of space in the ring.
1853  **/
1854 static void
1855 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1856 {
1857 	int ringno = pring->ringno;
1858 
1859 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
1860 
1861 	wmb();
1862 
1863 	/*
1864 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
1865 	 * The HBA will tell us when an IOCB entry is available.
1866 	 */
1867 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
1868 	readl(phba->CAregaddr); /* flush */
1869 
1870 	pring->stats.iocb_cmd_full++;
1871 }
1872 
1873 /**
1874  * lpfc_sli_update_ring - Update chip attention register
1875  * @phba: Pointer to HBA context object.
1876  * @pring: Pointer to driver SLI ring object.
1877  *
1878  * This function updates the chip attention register bit for the
1879  * given ring to inform HBA that there is more work to be done
1880  * in this ring. The caller is not required to hold any lock.
1881  **/
1882 static void
1883 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1884 {
1885 	int ringno = pring->ringno;
1886 
1887 	/*
1888 	 * Tell the HBA that there is work to do in this ring.
1889 	 */
1890 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
1891 		wmb();
1892 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
1893 		readl(phba->CAregaddr); /* flush */
1894 	}
1895 }
1896 
1897 /**
1898  * lpfc_sli_resume_iocb - Process iocbs in the txq
1899  * @phba: Pointer to HBA context object.
1900  * @pring: Pointer to driver SLI ring object.
1901  *
1902  * This function is called with hbalock held to post pending iocbs
1903  * in the txq to the firmware. This function is called when driver
1904  * detects space available in the ring.
1905  **/
1906 static void
1907 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1908 {
1909 	IOCB_t *iocb;
1910 	struct lpfc_iocbq *nextiocb;
1911 
1912 	lockdep_assert_held(&phba->hbalock);
1913 
1914 	/*
1915 	 * Check to see if:
1916 	 *  (a) there is anything on the txq to send
1917 	 *  (b) link is up
1918 	 *  (c) link attention events can be processed (fcp ring only)
1919 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
1920 	 */
1921 
1922 	if (lpfc_is_link_up(phba) &&
1923 	    (!list_empty(&pring->txq)) &&
1924 	    (pring->ringno != LPFC_FCP_RING ||
1925 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
1926 
1927 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
1928 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
1929 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
1930 
1931 		if (iocb)
1932 			lpfc_sli_update_ring(phba, pring);
1933 		else
1934 			lpfc_sli_update_full_ring(phba, pring);
1935 	}
1936 
1937 	return;
1938 }
1939 
1940 /**
1941  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
1942  * @phba: Pointer to HBA context object.
1943  * @hbqno: HBQ number.
1944  *
1945  * This function is called with hbalock held to get the next
1946  * available slot for the given HBQ. If there is free slot
1947  * available for the HBQ it will return pointer to the next available
1948  * HBQ entry else it will return NULL.
1949  **/
1950 static struct lpfc_hbq_entry *
1951 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
1952 {
1953 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
1954 
1955 	lockdep_assert_held(&phba->hbalock);
1956 
1957 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
1958 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
1959 		hbqp->next_hbqPutIdx = 0;
1960 
1961 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
1962 		uint32_t raw_index = phba->hbq_get[hbqno];
1963 		uint32_t getidx = le32_to_cpu(raw_index);
1964 
1965 		hbqp->local_hbqGetIdx = getidx;
1966 
1967 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
1968 			lpfc_printf_log(phba, KERN_ERR,
1969 					LOG_SLI | LOG_VPORT,
1970 					"1802 HBQ %d: local_hbqGetIdx "
1971 					"%u is > than hbqp->entry_count %u\n",
1972 					hbqno, hbqp->local_hbqGetIdx,
1973 					hbqp->entry_count);
1974 
1975 			phba->link_state = LPFC_HBA_ERROR;
1976 			return NULL;
1977 		}
1978 
1979 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
1980 			return NULL;
1981 	}
1982 
1983 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
1984 			hbqp->hbqPutIdx;
1985 }
1986 
1987 /**
1988  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
1989  * @phba: Pointer to HBA context object.
1990  *
1991  * This function is called with no lock held to free all the
1992  * hbq buffers while uninitializing the SLI interface. It also
1993  * frees the HBQ buffers returned by the firmware but not yet
1994  * processed by the upper layers.
1995  **/
1996 void
1997 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
1998 {
1999 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
2000 	struct hbq_dmabuf *hbq_buf;
2001 	unsigned long flags;
2002 	int i, hbq_count;
2003 
2004 	hbq_count = lpfc_sli_hbq_count();
2005 	/* Return all memory used by all HBQs */
2006 	spin_lock_irqsave(&phba->hbalock, flags);
2007 	for (i = 0; i < hbq_count; ++i) {
2008 		list_for_each_entry_safe(dmabuf, next_dmabuf,
2009 				&phba->hbqs[i].hbq_buffer_list, list) {
2010 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2011 			list_del(&hbq_buf->dbuf.list);
2012 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2013 		}
2014 		phba->hbqs[i].buffer_count = 0;
2015 	}
2016 
2017 	/* Mark the HBQs not in use */
2018 	phba->hbq_in_use = 0;
2019 	spin_unlock_irqrestore(&phba->hbalock, flags);
2020 }
2021 
2022 /**
2023  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2024  * @phba: Pointer to HBA context object.
2025  * @hbqno: HBQ number.
2026  * @hbq_buf: Pointer to HBQ buffer.
2027  *
2028  * This function is called with the hbalock held to post a
2029  * hbq buffer to the firmware. If the function finds an empty
2030  * slot in the HBQ, it will post the buffer. The function will return
2031  * pointer to the hbq entry if it successfully post the buffer
2032  * else it will return NULL.
2033  **/
2034 static int
2035 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2036 			 struct hbq_dmabuf *hbq_buf)
2037 {
2038 	lockdep_assert_held(&phba->hbalock);
2039 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2040 }
2041 
2042 /**
2043  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2044  * @phba: Pointer to HBA context object.
2045  * @hbqno: HBQ number.
2046  * @hbq_buf: Pointer to HBQ buffer.
2047  *
2048  * This function is called with the hbalock held to post a hbq buffer to the
2049  * firmware. If the function finds an empty slot in the HBQ, it will post the
2050  * buffer and place it on the hbq_buffer_list. The function will return zero if
2051  * it successfully post the buffer else it will return an error.
2052  **/
2053 static int
2054 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2055 			    struct hbq_dmabuf *hbq_buf)
2056 {
2057 	struct lpfc_hbq_entry *hbqe;
2058 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
2059 
2060 	lockdep_assert_held(&phba->hbalock);
2061 	/* Get next HBQ entry slot to use */
2062 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2063 	if (hbqe) {
2064 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
2065 
2066 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2067 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2068 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2069 		hbqe->bde.tus.f.bdeFlags = 0;
2070 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2071 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2072 				/* Sync SLIM */
2073 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2074 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2075 				/* flush */
2076 		readl(phba->hbq_put + hbqno);
2077 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2078 		return 0;
2079 	} else
2080 		return -ENOMEM;
2081 }
2082 
2083 /**
2084  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2085  * @phba: Pointer to HBA context object.
2086  * @hbqno: HBQ number.
2087  * @hbq_buf: Pointer to HBQ buffer.
2088  *
2089  * This function is called with the hbalock held to post an RQE to the SLI4
2090  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2091  * the hbq_buffer_list and return zero, otherwise it will return an error.
2092  **/
2093 static int
2094 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2095 			    struct hbq_dmabuf *hbq_buf)
2096 {
2097 	int rc;
2098 	struct lpfc_rqe hrqe;
2099 	struct lpfc_rqe drqe;
2100 	struct lpfc_queue *hrq;
2101 	struct lpfc_queue *drq;
2102 
2103 	if (hbqno != LPFC_ELS_HBQ)
2104 		return 1;
2105 	hrq = phba->sli4_hba.hdr_rq;
2106 	drq = phba->sli4_hba.dat_rq;
2107 
2108 	lockdep_assert_held(&phba->hbalock);
2109 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2110 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2111 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2112 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2113 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2114 	if (rc < 0)
2115 		return rc;
2116 	hbq_buf->tag = (rc | (hbqno << 16));
2117 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2118 	return 0;
2119 }
2120 
2121 /* HBQ for ELS and CT traffic. */
2122 static struct lpfc_hbq_init lpfc_els_hbq = {
2123 	.rn = 1,
2124 	.entry_count = 256,
2125 	.mask_count = 0,
2126 	.profile = 0,
2127 	.ring_mask = (1 << LPFC_ELS_RING),
2128 	.buffer_count = 0,
2129 	.init_count = 40,
2130 	.add_count = 40,
2131 };
2132 
2133 /* Array of HBQs */
2134 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2135 	&lpfc_els_hbq,
2136 };
2137 
2138 /**
2139  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2140  * @phba: Pointer to HBA context object.
2141  * @hbqno: HBQ number.
2142  * @count: Number of HBQ buffers to be posted.
2143  *
2144  * This function is called with no lock held to post more hbq buffers to the
2145  * given HBQ. The function returns the number of HBQ buffers successfully
2146  * posted.
2147  **/
2148 static int
2149 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2150 {
2151 	uint32_t i, posted = 0;
2152 	unsigned long flags;
2153 	struct hbq_dmabuf *hbq_buffer;
2154 	LIST_HEAD(hbq_buf_list);
2155 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2156 		return 0;
2157 
2158 	if ((phba->hbqs[hbqno].buffer_count + count) >
2159 	    lpfc_hbq_defs[hbqno]->entry_count)
2160 		count = lpfc_hbq_defs[hbqno]->entry_count -
2161 					phba->hbqs[hbqno].buffer_count;
2162 	if (!count)
2163 		return 0;
2164 	/* Allocate HBQ entries */
2165 	for (i = 0; i < count; i++) {
2166 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2167 		if (!hbq_buffer)
2168 			break;
2169 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2170 	}
2171 	/* Check whether HBQ is still in use */
2172 	spin_lock_irqsave(&phba->hbalock, flags);
2173 	if (!phba->hbq_in_use)
2174 		goto err;
2175 	while (!list_empty(&hbq_buf_list)) {
2176 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2177 				 dbuf.list);
2178 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2179 				      (hbqno << 16));
2180 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2181 			phba->hbqs[hbqno].buffer_count++;
2182 			posted++;
2183 		} else
2184 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2185 	}
2186 	spin_unlock_irqrestore(&phba->hbalock, flags);
2187 	return posted;
2188 err:
2189 	spin_unlock_irqrestore(&phba->hbalock, flags);
2190 	while (!list_empty(&hbq_buf_list)) {
2191 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2192 				 dbuf.list);
2193 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2194 	}
2195 	return 0;
2196 }
2197 
2198 /**
2199  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2200  * @phba: Pointer to HBA context object.
2201  * @qno: HBQ number.
2202  *
2203  * This function posts more buffers to the HBQ. This function
2204  * is called with no lock held. The function returns the number of HBQ entries
2205  * successfully allocated.
2206  **/
2207 int
2208 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2209 {
2210 	if (phba->sli_rev == LPFC_SLI_REV4)
2211 		return 0;
2212 	else
2213 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2214 					 lpfc_hbq_defs[qno]->add_count);
2215 }
2216 
2217 /**
2218  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2219  * @phba: Pointer to HBA context object.
2220  * @qno:  HBQ queue number.
2221  *
2222  * This function is called from SLI initialization code path with
2223  * no lock held to post initial HBQ buffers to firmware. The
2224  * function returns the number of HBQ entries successfully allocated.
2225  **/
2226 static int
2227 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2228 {
2229 	if (phba->sli_rev == LPFC_SLI_REV4)
2230 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2231 					lpfc_hbq_defs[qno]->entry_count);
2232 	else
2233 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2234 					 lpfc_hbq_defs[qno]->init_count);
2235 }
2236 
2237 /**
2238  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2239  * @phba: Pointer to HBA context object.
2240  * @hbqno: HBQ number.
2241  *
2242  * This function removes the first hbq buffer on an hbq list and returns a
2243  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2244  **/
2245 static struct hbq_dmabuf *
2246 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2247 {
2248 	struct lpfc_dmabuf *d_buf;
2249 
2250 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2251 	if (!d_buf)
2252 		return NULL;
2253 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2254 }
2255 
2256 /**
2257  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2258  * @phba: Pointer to HBA context object.
2259  * @hbqno: HBQ number.
2260  *
2261  * This function removes the first RQ buffer on an RQ buffer list and returns a
2262  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2263  **/
2264 static struct rqb_dmabuf *
2265 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2266 {
2267 	struct lpfc_dmabuf *h_buf;
2268 	struct lpfc_rqb *rqbp;
2269 
2270 	rqbp = hrq->rqbp;
2271 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2272 			 struct lpfc_dmabuf, list);
2273 	if (!h_buf)
2274 		return NULL;
2275 	rqbp->buffer_count--;
2276 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2277 }
2278 
2279 /**
2280  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2281  * @phba: Pointer to HBA context object.
2282  * @tag: Tag of the hbq buffer.
2283  *
2284  * This function searches for the hbq buffer associated with the given tag in
2285  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2286  * otherwise it returns NULL.
2287  **/
2288 static struct hbq_dmabuf *
2289 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2290 {
2291 	struct lpfc_dmabuf *d_buf;
2292 	struct hbq_dmabuf *hbq_buf;
2293 	uint32_t hbqno;
2294 
2295 	hbqno = tag >> 16;
2296 	if (hbqno >= LPFC_MAX_HBQS)
2297 		return NULL;
2298 
2299 	spin_lock_irq(&phba->hbalock);
2300 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2301 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2302 		if (hbq_buf->tag == tag) {
2303 			spin_unlock_irq(&phba->hbalock);
2304 			return hbq_buf;
2305 		}
2306 	}
2307 	spin_unlock_irq(&phba->hbalock);
2308 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_VPORT,
2309 			"1803 Bad hbq tag. Data: x%x x%x\n",
2310 			tag, phba->hbqs[tag >> 16].buffer_count);
2311 	return NULL;
2312 }
2313 
2314 /**
2315  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2316  * @phba: Pointer to HBA context object.
2317  * @hbq_buffer: Pointer to HBQ buffer.
2318  *
2319  * This function is called with hbalock. This function gives back
2320  * the hbq buffer to firmware. If the HBQ does not have space to
2321  * post the buffer, it will free the buffer.
2322  **/
2323 void
2324 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2325 {
2326 	uint32_t hbqno;
2327 
2328 	if (hbq_buffer) {
2329 		hbqno = hbq_buffer->tag >> 16;
2330 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2331 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2332 	}
2333 }
2334 
2335 /**
2336  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2337  * @mbxCommand: mailbox command code.
2338  *
2339  * This function is called by the mailbox event handler function to verify
2340  * that the completed mailbox command is a legitimate mailbox command. If the
2341  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2342  * and the mailbox event handler will take the HBA offline.
2343  **/
2344 static int
2345 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2346 {
2347 	uint8_t ret;
2348 
2349 	switch (mbxCommand) {
2350 	case MBX_LOAD_SM:
2351 	case MBX_READ_NV:
2352 	case MBX_WRITE_NV:
2353 	case MBX_WRITE_VPARMS:
2354 	case MBX_RUN_BIU_DIAG:
2355 	case MBX_INIT_LINK:
2356 	case MBX_DOWN_LINK:
2357 	case MBX_CONFIG_LINK:
2358 	case MBX_CONFIG_RING:
2359 	case MBX_RESET_RING:
2360 	case MBX_READ_CONFIG:
2361 	case MBX_READ_RCONFIG:
2362 	case MBX_READ_SPARM:
2363 	case MBX_READ_STATUS:
2364 	case MBX_READ_RPI:
2365 	case MBX_READ_XRI:
2366 	case MBX_READ_REV:
2367 	case MBX_READ_LNK_STAT:
2368 	case MBX_REG_LOGIN:
2369 	case MBX_UNREG_LOGIN:
2370 	case MBX_CLEAR_LA:
2371 	case MBX_DUMP_MEMORY:
2372 	case MBX_DUMP_CONTEXT:
2373 	case MBX_RUN_DIAGS:
2374 	case MBX_RESTART:
2375 	case MBX_UPDATE_CFG:
2376 	case MBX_DOWN_LOAD:
2377 	case MBX_DEL_LD_ENTRY:
2378 	case MBX_RUN_PROGRAM:
2379 	case MBX_SET_MASK:
2380 	case MBX_SET_VARIABLE:
2381 	case MBX_UNREG_D_ID:
2382 	case MBX_KILL_BOARD:
2383 	case MBX_CONFIG_FARP:
2384 	case MBX_BEACON:
2385 	case MBX_LOAD_AREA:
2386 	case MBX_RUN_BIU_DIAG64:
2387 	case MBX_CONFIG_PORT:
2388 	case MBX_READ_SPARM64:
2389 	case MBX_READ_RPI64:
2390 	case MBX_REG_LOGIN64:
2391 	case MBX_READ_TOPOLOGY:
2392 	case MBX_WRITE_WWN:
2393 	case MBX_SET_DEBUG:
2394 	case MBX_LOAD_EXP_ROM:
2395 	case MBX_ASYNCEVT_ENABLE:
2396 	case MBX_REG_VPI:
2397 	case MBX_UNREG_VPI:
2398 	case MBX_HEARTBEAT:
2399 	case MBX_PORT_CAPABILITIES:
2400 	case MBX_PORT_IOV_CONTROL:
2401 	case MBX_SLI4_CONFIG:
2402 	case MBX_SLI4_REQ_FTRS:
2403 	case MBX_REG_FCFI:
2404 	case MBX_UNREG_FCFI:
2405 	case MBX_REG_VFI:
2406 	case MBX_UNREG_VFI:
2407 	case MBX_INIT_VPI:
2408 	case MBX_INIT_VFI:
2409 	case MBX_RESUME_RPI:
2410 	case MBX_READ_EVENT_LOG_STATUS:
2411 	case MBX_READ_EVENT_LOG:
2412 	case MBX_SECURITY_MGMT:
2413 	case MBX_AUTH_PORT:
2414 	case MBX_ACCESS_VDATA:
2415 		ret = mbxCommand;
2416 		break;
2417 	default:
2418 		ret = MBX_SHUTDOWN;
2419 		break;
2420 	}
2421 	return ret;
2422 }
2423 
2424 /**
2425  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2426  * @phba: Pointer to HBA context object.
2427  * @pmboxq: Pointer to mailbox command.
2428  *
2429  * This is completion handler function for mailbox commands issued from
2430  * lpfc_sli_issue_mbox_wait function. This function is called by the
2431  * mailbox event handler function with no lock held. This function
2432  * will wake up thread waiting on the wait queue pointed by context1
2433  * of the mailbox.
2434  **/
2435 void
2436 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2437 {
2438 	unsigned long drvr_flag;
2439 	struct completion *pmbox_done;
2440 
2441 	/*
2442 	 * If pmbox_done is empty, the driver thread gave up waiting and
2443 	 * continued running.
2444 	 */
2445 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2446 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2447 	pmbox_done = (struct completion *)pmboxq->context3;
2448 	if (pmbox_done)
2449 		complete(pmbox_done);
2450 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2451 	return;
2452 }
2453 
2454 static void
2455 __lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2456 {
2457 	unsigned long iflags;
2458 
2459 	if (ndlp->nlp_flag & NLP_RELEASE_RPI) {
2460 		lpfc_sli4_free_rpi(vport->phba, ndlp->nlp_rpi);
2461 		spin_lock_irqsave(&vport->phba->ndlp_lock, iflags);
2462 		ndlp->nlp_flag &= ~NLP_RELEASE_RPI;
2463 		ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
2464 		spin_unlock_irqrestore(&vport->phba->ndlp_lock, iflags);
2465 	}
2466 	ndlp->nlp_flag &= ~NLP_UNREG_INP;
2467 }
2468 
2469 /**
2470  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2471  * @phba: Pointer to HBA context object.
2472  * @pmb: Pointer to mailbox object.
2473  *
2474  * This function is the default mailbox completion handler. It
2475  * frees the memory resources associated with the completed mailbox
2476  * command. If the completed command is a REG_LOGIN mailbox command,
2477  * this function will issue a UREG_LOGIN to re-claim the RPI.
2478  **/
2479 void
2480 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2481 {
2482 	struct lpfc_vport  *vport = pmb->vport;
2483 	struct lpfc_dmabuf *mp;
2484 	struct lpfc_nodelist *ndlp;
2485 	struct Scsi_Host *shost;
2486 	uint16_t rpi, vpi;
2487 	int rc;
2488 
2489 	mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
2490 
2491 	if (mp) {
2492 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
2493 		kfree(mp);
2494 	}
2495 
2496 	/*
2497 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2498 	 * is in re-discovery driver need to cleanup the RPI.
2499 	 */
2500 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2501 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2502 	    !pmb->u.mb.mbxStatus) {
2503 		rpi = pmb->u.mb.un.varWords[0];
2504 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2505 		if (phba->sli_rev == LPFC_SLI_REV4)
2506 			vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2507 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2508 		pmb->vport = vport;
2509 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2510 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2511 		if (rc != MBX_NOT_FINISHED)
2512 			return;
2513 	}
2514 
2515 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2516 		!(phba->pport->load_flag & FC_UNLOADING) &&
2517 		!pmb->u.mb.mbxStatus) {
2518 		shost = lpfc_shost_from_vport(vport);
2519 		spin_lock_irq(shost->host_lock);
2520 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2521 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2522 		spin_unlock_irq(shost->host_lock);
2523 	}
2524 
2525 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2526 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2527 		lpfc_nlp_put(ndlp);
2528 		pmb->ctx_buf = NULL;
2529 		pmb->ctx_ndlp = NULL;
2530 	}
2531 
2532 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2533 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2534 
2535 		/* Check to see if there are any deferred events to process */
2536 		if (ndlp) {
2537 			lpfc_printf_vlog(
2538 				vport,
2539 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2540 				"1438 UNREG cmpl deferred mbox x%x "
2541 				"on NPort x%x Data: x%x x%x %px\n",
2542 				ndlp->nlp_rpi, ndlp->nlp_DID,
2543 				ndlp->nlp_flag, ndlp->nlp_defer_did, ndlp);
2544 
2545 			if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2546 			    (ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING)) {
2547 				ndlp->nlp_flag &= ~NLP_UNREG_INP;
2548 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2549 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2550 			} else {
2551 				__lpfc_sli_rpi_release(vport, ndlp);
2552 			}
2553 			if (vport->load_flag & FC_UNLOADING)
2554 				lpfc_nlp_put(ndlp);
2555 			pmb->ctx_ndlp = NULL;
2556 		}
2557 	}
2558 
2559 	/* Check security permission status on INIT_LINK mailbox command */
2560 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2561 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2562 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2563 				"2860 SLI authentication is required "
2564 				"for INIT_LINK but has not done yet\n");
2565 
2566 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2567 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2568 	else
2569 		mempool_free(pmb, phba->mbox_mem_pool);
2570 }
2571  /**
2572  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2573  * @phba: Pointer to HBA context object.
2574  * @pmb: Pointer to mailbox object.
2575  *
2576  * This function is the unreg rpi mailbox completion handler. It
2577  * frees the memory resources associated with the completed mailbox
2578  * command. An additional refrenece is put on the ndlp to prevent
2579  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2580  * the unreg mailbox command completes, this routine puts the
2581  * reference back.
2582  *
2583  **/
2584 void
2585 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2586 {
2587 	struct lpfc_vport  *vport = pmb->vport;
2588 	struct lpfc_nodelist *ndlp;
2589 
2590 	ndlp = pmb->ctx_ndlp;
2591 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2592 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2593 		    (bf_get(lpfc_sli_intf_if_type,
2594 		     &phba->sli4_hba.sli_intf) >=
2595 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2596 			if (ndlp) {
2597 				lpfc_printf_vlog(
2598 					vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2599 					 "0010 UNREG_LOGIN vpi:%x "
2600 					 "rpi:%x DID:%x defer x%x flg x%x "
2601 					 "map:%x %px\n",
2602 					 vport->vpi, ndlp->nlp_rpi,
2603 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
2604 					 ndlp->nlp_flag,
2605 					 ndlp->nlp_usg_map, ndlp);
2606 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2607 				lpfc_nlp_put(ndlp);
2608 
2609 				/* Check to see if there are any deferred
2610 				 * events to process
2611 				 */
2612 				if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2613 				    (ndlp->nlp_defer_did !=
2614 				    NLP_EVT_NOTHING_PENDING)) {
2615 					lpfc_printf_vlog(
2616 						vport, KERN_INFO, LOG_DISCOVERY,
2617 						"4111 UNREG cmpl deferred "
2618 						"clr x%x on "
2619 						"NPort x%x Data: x%x x%px\n",
2620 						ndlp->nlp_rpi, ndlp->nlp_DID,
2621 						ndlp->nlp_defer_did, ndlp);
2622 					ndlp->nlp_flag &= ~NLP_UNREG_INP;
2623 					ndlp->nlp_defer_did =
2624 						NLP_EVT_NOTHING_PENDING;
2625 					lpfc_issue_els_plogi(
2626 						vport, ndlp->nlp_DID, 0);
2627 				} else {
2628 					__lpfc_sli_rpi_release(vport, ndlp);
2629 				}
2630 			}
2631 		}
2632 	}
2633 
2634 	mempool_free(pmb, phba->mbox_mem_pool);
2635 }
2636 
2637 /**
2638  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
2639  * @phba: Pointer to HBA context object.
2640  *
2641  * This function is called with no lock held. This function processes all
2642  * the completed mailbox commands and gives it to upper layers. The interrupt
2643  * service routine processes mailbox completion interrupt and adds completed
2644  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
2645  * Worker thread call lpfc_sli_handle_mb_event, which will return the
2646  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
2647  * function returns the mailbox commands to the upper layer by calling the
2648  * completion handler function of each mailbox.
2649  **/
2650 int
2651 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
2652 {
2653 	MAILBOX_t *pmbox;
2654 	LPFC_MBOXQ_t *pmb;
2655 	int rc;
2656 	LIST_HEAD(cmplq);
2657 
2658 	phba->sli.slistat.mbox_event++;
2659 
2660 	/* Get all completed mailboxe buffers into the cmplq */
2661 	spin_lock_irq(&phba->hbalock);
2662 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
2663 	spin_unlock_irq(&phba->hbalock);
2664 
2665 	/* Get a Mailbox buffer to setup mailbox commands for callback */
2666 	do {
2667 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
2668 		if (pmb == NULL)
2669 			break;
2670 
2671 		pmbox = &pmb->u.mb;
2672 
2673 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
2674 			if (pmb->vport) {
2675 				lpfc_debugfs_disc_trc(pmb->vport,
2676 					LPFC_DISC_TRC_MBOX_VPORT,
2677 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
2678 					(uint32_t)pmbox->mbxCommand,
2679 					pmbox->un.varWords[0],
2680 					pmbox->un.varWords[1]);
2681 			}
2682 			else {
2683 				lpfc_debugfs_disc_trc(phba->pport,
2684 					LPFC_DISC_TRC_MBOX,
2685 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
2686 					(uint32_t)pmbox->mbxCommand,
2687 					pmbox->un.varWords[0],
2688 					pmbox->un.varWords[1]);
2689 			}
2690 		}
2691 
2692 		/*
2693 		 * It is a fatal error if unknown mbox command completion.
2694 		 */
2695 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
2696 		    MBX_SHUTDOWN) {
2697 			/* Unknown mailbox command compl */
2698 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2699 					"(%d):0323 Unknown Mailbox command "
2700 					"x%x (x%x/x%x) Cmpl\n",
2701 					pmb->vport ? pmb->vport->vpi :
2702 					LPFC_VPORT_UNKNOWN,
2703 					pmbox->mbxCommand,
2704 					lpfc_sli_config_mbox_subsys_get(phba,
2705 									pmb),
2706 					lpfc_sli_config_mbox_opcode_get(phba,
2707 									pmb));
2708 			phba->link_state = LPFC_HBA_ERROR;
2709 			phba->work_hs = HS_FFER3;
2710 			lpfc_handle_eratt(phba);
2711 			continue;
2712 		}
2713 
2714 		if (pmbox->mbxStatus) {
2715 			phba->sli.slistat.mbox_stat_err++;
2716 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
2717 				/* Mbox cmd cmpl error - RETRYing */
2718 				lpfc_printf_log(phba, KERN_INFO,
2719 					LOG_MBOX | LOG_SLI,
2720 					"(%d):0305 Mbox cmd cmpl "
2721 					"error - RETRYing Data: x%x "
2722 					"(x%x/x%x) x%x x%x x%x\n",
2723 					pmb->vport ? pmb->vport->vpi :
2724 					LPFC_VPORT_UNKNOWN,
2725 					pmbox->mbxCommand,
2726 					lpfc_sli_config_mbox_subsys_get(phba,
2727 									pmb),
2728 					lpfc_sli_config_mbox_opcode_get(phba,
2729 									pmb),
2730 					pmbox->mbxStatus,
2731 					pmbox->un.varWords[0],
2732 					pmb->vport ? pmb->vport->port_state :
2733 					LPFC_VPORT_UNKNOWN);
2734 				pmbox->mbxStatus = 0;
2735 				pmbox->mbxOwner = OWN_HOST;
2736 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2737 				if (rc != MBX_NOT_FINISHED)
2738 					continue;
2739 			}
2740 		}
2741 
2742 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
2743 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
2744 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
2745 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
2746 				"x%x x%x x%x\n",
2747 				pmb->vport ? pmb->vport->vpi : 0,
2748 				pmbox->mbxCommand,
2749 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
2750 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
2751 				pmb->mbox_cmpl,
2752 				*((uint32_t *) pmbox),
2753 				pmbox->un.varWords[0],
2754 				pmbox->un.varWords[1],
2755 				pmbox->un.varWords[2],
2756 				pmbox->un.varWords[3],
2757 				pmbox->un.varWords[4],
2758 				pmbox->un.varWords[5],
2759 				pmbox->un.varWords[6],
2760 				pmbox->un.varWords[7],
2761 				pmbox->un.varWords[8],
2762 				pmbox->un.varWords[9],
2763 				pmbox->un.varWords[10]);
2764 
2765 		if (pmb->mbox_cmpl)
2766 			pmb->mbox_cmpl(phba,pmb);
2767 	} while (1);
2768 	return 0;
2769 }
2770 
2771 /**
2772  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
2773  * @phba: Pointer to HBA context object.
2774  * @pring: Pointer to driver SLI ring object.
2775  * @tag: buffer tag.
2776  *
2777  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
2778  * is set in the tag the buffer is posted for a particular exchange,
2779  * the function will return the buffer without replacing the buffer.
2780  * If the buffer is for unsolicited ELS or CT traffic, this function
2781  * returns the buffer and also posts another buffer to the firmware.
2782  **/
2783 static struct lpfc_dmabuf *
2784 lpfc_sli_get_buff(struct lpfc_hba *phba,
2785 		  struct lpfc_sli_ring *pring,
2786 		  uint32_t tag)
2787 {
2788 	struct hbq_dmabuf *hbq_entry;
2789 
2790 	if (tag & QUE_BUFTAG_BIT)
2791 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
2792 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
2793 	if (!hbq_entry)
2794 		return NULL;
2795 	return &hbq_entry->dbuf;
2796 }
2797 
2798 /**
2799  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
2800  * @phba: Pointer to HBA context object.
2801  * @pring: Pointer to driver SLI ring object.
2802  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
2803  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
2804  * @fch_type: the type for the first frame of the sequence.
2805  *
2806  * This function is called with no lock held. This function uses the r_ctl and
2807  * type of the received sequence to find the correct callback function to call
2808  * to process the sequence.
2809  **/
2810 static int
2811 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2812 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
2813 			 uint32_t fch_type)
2814 {
2815 	int i;
2816 
2817 	switch (fch_type) {
2818 	case FC_TYPE_NVME:
2819 		lpfc_nvmet_unsol_ls_event(phba, pring, saveq);
2820 		return 1;
2821 	default:
2822 		break;
2823 	}
2824 
2825 	/* unSolicited Responses */
2826 	if (pring->prt[0].profile) {
2827 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
2828 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
2829 									saveq);
2830 		return 1;
2831 	}
2832 	/* We must search, based on rctl / type
2833 	   for the right routine */
2834 	for (i = 0; i < pring->num_mask; i++) {
2835 		if ((pring->prt[i].rctl == fch_r_ctl) &&
2836 		    (pring->prt[i].type == fch_type)) {
2837 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
2838 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
2839 						(phba, pring, saveq);
2840 			return 1;
2841 		}
2842 	}
2843 	return 0;
2844 }
2845 
2846 /**
2847  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
2848  * @phba: Pointer to HBA context object.
2849  * @pring: Pointer to driver SLI ring object.
2850  * @saveq: Pointer to the unsolicited iocb.
2851  *
2852  * This function is called with no lock held by the ring event handler
2853  * when there is an unsolicited iocb posted to the response ring by the
2854  * firmware. This function gets the buffer associated with the iocbs
2855  * and calls the event handler for the ring. This function handles both
2856  * qring buffers and hbq buffers.
2857  * When the function returns 1 the caller can free the iocb object otherwise
2858  * upper layer functions will free the iocb objects.
2859  **/
2860 static int
2861 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2862 			    struct lpfc_iocbq *saveq)
2863 {
2864 	IOCB_t           * irsp;
2865 	WORD5            * w5p;
2866 	uint32_t           Rctl, Type;
2867 	struct lpfc_iocbq *iocbq;
2868 	struct lpfc_dmabuf *dmzbuf;
2869 
2870 	irsp = &(saveq->iocb);
2871 
2872 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
2873 		if (pring->lpfc_sli_rcv_async_status)
2874 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
2875 		else
2876 			lpfc_printf_log(phba,
2877 					KERN_WARNING,
2878 					LOG_SLI,
2879 					"0316 Ring %d handler: unexpected "
2880 					"ASYNC_STATUS iocb received evt_code "
2881 					"0x%x\n",
2882 					pring->ringno,
2883 					irsp->un.asyncstat.evt_code);
2884 		return 1;
2885 	}
2886 
2887 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
2888 		(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
2889 		if (irsp->ulpBdeCount > 0) {
2890 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2891 					irsp->un.ulpWord[3]);
2892 			lpfc_in_buf_free(phba, dmzbuf);
2893 		}
2894 
2895 		if (irsp->ulpBdeCount > 1) {
2896 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2897 					irsp->unsli3.sli3Words[3]);
2898 			lpfc_in_buf_free(phba, dmzbuf);
2899 		}
2900 
2901 		if (irsp->ulpBdeCount > 2) {
2902 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2903 				irsp->unsli3.sli3Words[7]);
2904 			lpfc_in_buf_free(phba, dmzbuf);
2905 		}
2906 
2907 		return 1;
2908 	}
2909 
2910 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
2911 		if (irsp->ulpBdeCount != 0) {
2912 			saveq->context2 = lpfc_sli_get_buff(phba, pring,
2913 						irsp->un.ulpWord[3]);
2914 			if (!saveq->context2)
2915 				lpfc_printf_log(phba,
2916 					KERN_ERR,
2917 					LOG_SLI,
2918 					"0341 Ring %d Cannot find buffer for "
2919 					"an unsolicited iocb. tag 0x%x\n",
2920 					pring->ringno,
2921 					irsp->un.ulpWord[3]);
2922 		}
2923 		if (irsp->ulpBdeCount == 2) {
2924 			saveq->context3 = lpfc_sli_get_buff(phba, pring,
2925 						irsp->unsli3.sli3Words[7]);
2926 			if (!saveq->context3)
2927 				lpfc_printf_log(phba,
2928 					KERN_ERR,
2929 					LOG_SLI,
2930 					"0342 Ring %d Cannot find buffer for an"
2931 					" unsolicited iocb. tag 0x%x\n",
2932 					pring->ringno,
2933 					irsp->unsli3.sli3Words[7]);
2934 		}
2935 		list_for_each_entry(iocbq, &saveq->list, list) {
2936 			irsp = &(iocbq->iocb);
2937 			if (irsp->ulpBdeCount != 0) {
2938 				iocbq->context2 = lpfc_sli_get_buff(phba, pring,
2939 							irsp->un.ulpWord[3]);
2940 				if (!iocbq->context2)
2941 					lpfc_printf_log(phba,
2942 						KERN_ERR,
2943 						LOG_SLI,
2944 						"0343 Ring %d Cannot find "
2945 						"buffer for an unsolicited iocb"
2946 						". tag 0x%x\n", pring->ringno,
2947 						irsp->un.ulpWord[3]);
2948 			}
2949 			if (irsp->ulpBdeCount == 2) {
2950 				iocbq->context3 = lpfc_sli_get_buff(phba, pring,
2951 						irsp->unsli3.sli3Words[7]);
2952 				if (!iocbq->context3)
2953 					lpfc_printf_log(phba,
2954 						KERN_ERR,
2955 						LOG_SLI,
2956 						"0344 Ring %d Cannot find "
2957 						"buffer for an unsolicited "
2958 						"iocb. tag 0x%x\n",
2959 						pring->ringno,
2960 						irsp->unsli3.sli3Words[7]);
2961 			}
2962 		}
2963 	}
2964 	if (irsp->ulpBdeCount != 0 &&
2965 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
2966 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
2967 		int found = 0;
2968 
2969 		/* search continue save q for same XRI */
2970 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
2971 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
2972 				saveq->iocb.unsli3.rcvsli3.ox_id) {
2973 				list_add_tail(&saveq->list, &iocbq->list);
2974 				found = 1;
2975 				break;
2976 			}
2977 		}
2978 		if (!found)
2979 			list_add_tail(&saveq->clist,
2980 				      &pring->iocb_continue_saveq);
2981 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
2982 			list_del_init(&iocbq->clist);
2983 			saveq = iocbq;
2984 			irsp = &(saveq->iocb);
2985 		} else
2986 			return 0;
2987 	}
2988 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
2989 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
2990 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
2991 		Rctl = FC_RCTL_ELS_REQ;
2992 		Type = FC_TYPE_ELS;
2993 	} else {
2994 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
2995 		Rctl = w5p->hcsw.Rctl;
2996 		Type = w5p->hcsw.Type;
2997 
2998 		/* Firmware Workaround */
2999 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3000 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3001 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3002 			Rctl = FC_RCTL_ELS_REQ;
3003 			Type = FC_TYPE_ELS;
3004 			w5p->hcsw.Rctl = Rctl;
3005 			w5p->hcsw.Type = Type;
3006 		}
3007 	}
3008 
3009 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3010 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3011 				"0313 Ring %d handler: unexpected Rctl x%x "
3012 				"Type x%x received\n",
3013 				pring->ringno, Rctl, Type);
3014 
3015 	return 1;
3016 }
3017 
3018 /**
3019  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3020  * @phba: Pointer to HBA context object.
3021  * @pring: Pointer to driver SLI ring object.
3022  * @prspiocb: Pointer to response iocb object.
3023  *
3024  * This function looks up the iocb_lookup table to get the command iocb
3025  * corresponding to the given response iocb using the iotag of the
3026  * response iocb. The driver calls this function with the hbalock held
3027  * for SLI3 ports or the ring lock held for SLI4 ports.
3028  * This function returns the command iocb object if it finds the command
3029  * iocb else returns NULL.
3030  **/
3031 static struct lpfc_iocbq *
3032 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3033 		      struct lpfc_sli_ring *pring,
3034 		      struct lpfc_iocbq *prspiocb)
3035 {
3036 	struct lpfc_iocbq *cmd_iocb = NULL;
3037 	uint16_t iotag;
3038 	spinlock_t *temp_lock = NULL;
3039 	unsigned long iflag = 0;
3040 
3041 	if (phba->sli_rev == LPFC_SLI_REV4)
3042 		temp_lock = &pring->ring_lock;
3043 	else
3044 		temp_lock = &phba->hbalock;
3045 
3046 	spin_lock_irqsave(temp_lock, iflag);
3047 	iotag = prspiocb->iocb.ulpIoTag;
3048 
3049 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3050 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3051 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3052 			/* remove from txcmpl queue list */
3053 			list_del_init(&cmd_iocb->list);
3054 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3055 			pring->txcmplq_cnt--;
3056 			spin_unlock_irqrestore(temp_lock, iflag);
3057 			return cmd_iocb;
3058 		}
3059 	}
3060 
3061 	spin_unlock_irqrestore(temp_lock, iflag);
3062 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3063 			"0317 iotag x%x is out of "
3064 			"range: max iotag x%x wd0 x%x\n",
3065 			iotag, phba->sli.last_iotag,
3066 			*(((uint32_t *) &prspiocb->iocb) + 7));
3067 	return NULL;
3068 }
3069 
3070 /**
3071  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3072  * @phba: Pointer to HBA context object.
3073  * @pring: Pointer to driver SLI ring object.
3074  * @iotag: IOCB tag.
3075  *
3076  * This function looks up the iocb_lookup table to get the command iocb
3077  * corresponding to the given iotag. The driver calls this function with
3078  * the ring lock held because this function is an SLI4 port only helper.
3079  * This function returns the command iocb object if it finds the command
3080  * iocb else returns NULL.
3081  **/
3082 static struct lpfc_iocbq *
3083 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3084 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3085 {
3086 	struct lpfc_iocbq *cmd_iocb = NULL;
3087 	spinlock_t *temp_lock = NULL;
3088 	unsigned long iflag = 0;
3089 
3090 	if (phba->sli_rev == LPFC_SLI_REV4)
3091 		temp_lock = &pring->ring_lock;
3092 	else
3093 		temp_lock = &phba->hbalock;
3094 
3095 	spin_lock_irqsave(temp_lock, iflag);
3096 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3097 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3098 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3099 			/* remove from txcmpl queue list */
3100 			list_del_init(&cmd_iocb->list);
3101 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3102 			pring->txcmplq_cnt--;
3103 			spin_unlock_irqrestore(temp_lock, iflag);
3104 			return cmd_iocb;
3105 		}
3106 	}
3107 
3108 	spin_unlock_irqrestore(temp_lock, iflag);
3109 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3110 			"0372 iotag x%x lookup error: max iotag (x%x) "
3111 			"iocb_flag x%x\n",
3112 			iotag, phba->sli.last_iotag,
3113 			cmd_iocb ? cmd_iocb->iocb_flag : 0xffff);
3114 	return NULL;
3115 }
3116 
3117 /**
3118  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3119  * @phba: Pointer to HBA context object.
3120  * @pring: Pointer to driver SLI ring object.
3121  * @saveq: Pointer to the response iocb to be processed.
3122  *
3123  * This function is called by the ring event handler for non-fcp
3124  * rings when there is a new response iocb in the response ring.
3125  * The caller is not required to hold any locks. This function
3126  * gets the command iocb associated with the response iocb and
3127  * calls the completion handler for the command iocb. If there
3128  * is no completion handler, the function will free the resources
3129  * associated with command iocb. If the response iocb is for
3130  * an already aborted command iocb, the status of the completion
3131  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3132  * This function always returns 1.
3133  **/
3134 static int
3135 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3136 			  struct lpfc_iocbq *saveq)
3137 {
3138 	struct lpfc_iocbq *cmdiocbp;
3139 	int rc = 1;
3140 	unsigned long iflag;
3141 
3142 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3143 	if (cmdiocbp) {
3144 		if (cmdiocbp->iocb_cmpl) {
3145 			/*
3146 			 * If an ELS command failed send an event to mgmt
3147 			 * application.
3148 			 */
3149 			if (saveq->iocb.ulpStatus &&
3150 			     (pring->ringno == LPFC_ELS_RING) &&
3151 			     (cmdiocbp->iocb.ulpCommand ==
3152 				CMD_ELS_REQUEST64_CR))
3153 				lpfc_send_els_failure_event(phba,
3154 					cmdiocbp, saveq);
3155 
3156 			/*
3157 			 * Post all ELS completions to the worker thread.
3158 			 * All other are passed to the completion callback.
3159 			 */
3160 			if (pring->ringno == LPFC_ELS_RING) {
3161 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3162 				    (cmdiocbp->iocb_flag &
3163 							LPFC_DRIVER_ABORTED)) {
3164 					spin_lock_irqsave(&phba->hbalock,
3165 							  iflag);
3166 					cmdiocbp->iocb_flag &=
3167 						~LPFC_DRIVER_ABORTED;
3168 					spin_unlock_irqrestore(&phba->hbalock,
3169 							       iflag);
3170 					saveq->iocb.ulpStatus =
3171 						IOSTAT_LOCAL_REJECT;
3172 					saveq->iocb.un.ulpWord[4] =
3173 						IOERR_SLI_ABORTED;
3174 
3175 					/* Firmware could still be in progress
3176 					 * of DMAing payload, so don't free data
3177 					 * buffer till after a hbeat.
3178 					 */
3179 					spin_lock_irqsave(&phba->hbalock,
3180 							  iflag);
3181 					saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
3182 					spin_unlock_irqrestore(&phba->hbalock,
3183 							       iflag);
3184 				}
3185 				if (phba->sli_rev == LPFC_SLI_REV4) {
3186 					if (saveq->iocb_flag &
3187 					    LPFC_EXCHANGE_BUSY) {
3188 						/* Set cmdiocb flag for the
3189 						 * exchange busy so sgl (xri)
3190 						 * will not be released until
3191 						 * the abort xri is received
3192 						 * from hba.
3193 						 */
3194 						spin_lock_irqsave(
3195 							&phba->hbalock, iflag);
3196 						cmdiocbp->iocb_flag |=
3197 							LPFC_EXCHANGE_BUSY;
3198 						spin_unlock_irqrestore(
3199 							&phba->hbalock, iflag);
3200 					}
3201 					if (cmdiocbp->iocb_flag &
3202 					    LPFC_DRIVER_ABORTED) {
3203 						/*
3204 						 * Clear LPFC_DRIVER_ABORTED
3205 						 * bit in case it was driver
3206 						 * initiated abort.
3207 						 */
3208 						spin_lock_irqsave(
3209 							&phba->hbalock, iflag);
3210 						cmdiocbp->iocb_flag &=
3211 							~LPFC_DRIVER_ABORTED;
3212 						spin_unlock_irqrestore(
3213 							&phba->hbalock, iflag);
3214 						cmdiocbp->iocb.ulpStatus =
3215 							IOSTAT_LOCAL_REJECT;
3216 						cmdiocbp->iocb.un.ulpWord[4] =
3217 							IOERR_ABORT_REQUESTED;
3218 						/*
3219 						 * For SLI4, irsiocb contains
3220 						 * NO_XRI in sli_xritag, it
3221 						 * shall not affect releasing
3222 						 * sgl (xri) process.
3223 						 */
3224 						saveq->iocb.ulpStatus =
3225 							IOSTAT_LOCAL_REJECT;
3226 						saveq->iocb.un.ulpWord[4] =
3227 							IOERR_SLI_ABORTED;
3228 						spin_lock_irqsave(
3229 							&phba->hbalock, iflag);
3230 						saveq->iocb_flag |=
3231 							LPFC_DELAY_MEM_FREE;
3232 						spin_unlock_irqrestore(
3233 							&phba->hbalock, iflag);
3234 					}
3235 				}
3236 			}
3237 			(cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
3238 		} else
3239 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3240 	} else {
3241 		/*
3242 		 * Unknown initiating command based on the response iotag.
3243 		 * This could be the case on the ELS ring because of
3244 		 * lpfc_els_abort().
3245 		 */
3246 		if (pring->ringno != LPFC_ELS_RING) {
3247 			/*
3248 			 * Ring <ringno> handler: unexpected completion IoTag
3249 			 * <IoTag>
3250 			 */
3251 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3252 					 "0322 Ring %d handler: "
3253 					 "unexpected completion IoTag x%x "
3254 					 "Data: x%x x%x x%x x%x\n",
3255 					 pring->ringno,
3256 					 saveq->iocb.ulpIoTag,
3257 					 saveq->iocb.ulpStatus,
3258 					 saveq->iocb.un.ulpWord[4],
3259 					 saveq->iocb.ulpCommand,
3260 					 saveq->iocb.ulpContext);
3261 		}
3262 	}
3263 
3264 	return rc;
3265 }
3266 
3267 /**
3268  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3269  * @phba: Pointer to HBA context object.
3270  * @pring: Pointer to driver SLI ring object.
3271  *
3272  * This function is called from the iocb ring event handlers when
3273  * put pointer is ahead of the get pointer for a ring. This function signal
3274  * an error attention condition to the worker thread and the worker
3275  * thread will transition the HBA to offline state.
3276  **/
3277 static void
3278 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3279 {
3280 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3281 	/*
3282 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3283 	 * rsp ring <portRspMax>
3284 	 */
3285 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3286 			"0312 Ring %d handler: portRspPut %d "
3287 			"is bigger than rsp ring %d\n",
3288 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3289 			pring->sli.sli3.numRiocb);
3290 
3291 	phba->link_state = LPFC_HBA_ERROR;
3292 
3293 	/*
3294 	 * All error attention handlers are posted to
3295 	 * worker thread
3296 	 */
3297 	phba->work_ha |= HA_ERATT;
3298 	phba->work_hs = HS_FFER3;
3299 
3300 	lpfc_worker_wake_up(phba);
3301 
3302 	return;
3303 }
3304 
3305 /**
3306  * lpfc_poll_eratt - Error attention polling timer timeout handler
3307  * @ptr: Pointer to address of HBA context object.
3308  *
3309  * This function is invoked by the Error Attention polling timer when the
3310  * timer times out. It will check the SLI Error Attention register for
3311  * possible attention events. If so, it will post an Error Attention event
3312  * and wake up worker thread to process it. Otherwise, it will set up the
3313  * Error Attention polling timer for the next poll.
3314  **/
3315 void lpfc_poll_eratt(struct timer_list *t)
3316 {
3317 	struct lpfc_hba *phba;
3318 	uint32_t eratt = 0;
3319 	uint64_t sli_intr, cnt;
3320 
3321 	phba = from_timer(phba, t, eratt_poll);
3322 
3323 	/* Here we will also keep track of interrupts per sec of the hba */
3324 	sli_intr = phba->sli.slistat.sli_intr;
3325 
3326 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3327 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3328 			sli_intr);
3329 	else
3330 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3331 
3332 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3333 	do_div(cnt, phba->eratt_poll_interval);
3334 	phba->sli.slistat.sli_ips = cnt;
3335 
3336 	phba->sli.slistat.sli_prev_intr = sli_intr;
3337 
3338 	/* Check chip HA register for error event */
3339 	eratt = lpfc_sli_check_eratt(phba);
3340 
3341 	if (eratt)
3342 		/* Tell the worker thread there is work to do */
3343 		lpfc_worker_wake_up(phba);
3344 	else
3345 		/* Restart the timer for next eratt poll */
3346 		mod_timer(&phba->eratt_poll,
3347 			  jiffies +
3348 			  msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3349 	return;
3350 }
3351 
3352 
3353 /**
3354  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3355  * @phba: Pointer to HBA context object.
3356  * @pring: Pointer to driver SLI ring object.
3357  * @mask: Host attention register mask for this ring.
3358  *
3359  * This function is called from the interrupt context when there is a ring
3360  * event for the fcp ring. The caller does not hold any lock.
3361  * The function processes each response iocb in the response ring until it
3362  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3363  * LE bit set. The function will call the completion handler of the command iocb
3364  * if the response iocb indicates a completion for a command iocb or it is
3365  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3366  * function if this is an unsolicited iocb.
3367  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3368  * to check it explicitly.
3369  */
3370 int
3371 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3372 				struct lpfc_sli_ring *pring, uint32_t mask)
3373 {
3374 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3375 	IOCB_t *irsp = NULL;
3376 	IOCB_t *entry = NULL;
3377 	struct lpfc_iocbq *cmdiocbq = NULL;
3378 	struct lpfc_iocbq rspiocbq;
3379 	uint32_t status;
3380 	uint32_t portRspPut, portRspMax;
3381 	int rc = 1;
3382 	lpfc_iocb_type type;
3383 	unsigned long iflag;
3384 	uint32_t rsp_cmpl = 0;
3385 
3386 	spin_lock_irqsave(&phba->hbalock, iflag);
3387 	pring->stats.iocb_event++;
3388 
3389 	/*
3390 	 * The next available response entry should never exceed the maximum
3391 	 * entries.  If it does, treat it as an adapter hardware error.
3392 	 */
3393 	portRspMax = pring->sli.sli3.numRiocb;
3394 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3395 	if (unlikely(portRspPut >= portRspMax)) {
3396 		lpfc_sli_rsp_pointers_error(phba, pring);
3397 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3398 		return 1;
3399 	}
3400 	if (phba->fcp_ring_in_use) {
3401 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3402 		return 1;
3403 	} else
3404 		phba->fcp_ring_in_use = 1;
3405 
3406 	rmb();
3407 	while (pring->sli.sli3.rspidx != portRspPut) {
3408 		/*
3409 		 * Fetch an entry off the ring and copy it into a local data
3410 		 * structure.  The copy involves a byte-swap since the
3411 		 * network byte order and pci byte orders are different.
3412 		 */
3413 		entry = lpfc_resp_iocb(phba, pring);
3414 		phba->last_completion_time = jiffies;
3415 
3416 		if (++pring->sli.sli3.rspidx >= portRspMax)
3417 			pring->sli.sli3.rspidx = 0;
3418 
3419 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3420 				      (uint32_t *) &rspiocbq.iocb,
3421 				      phba->iocb_rsp_size);
3422 		INIT_LIST_HEAD(&(rspiocbq.list));
3423 		irsp = &rspiocbq.iocb;
3424 
3425 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3426 		pring->stats.iocb_rsp++;
3427 		rsp_cmpl++;
3428 
3429 		if (unlikely(irsp->ulpStatus)) {
3430 			/*
3431 			 * If resource errors reported from HBA, reduce
3432 			 * queuedepths of the SCSI device.
3433 			 */
3434 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3435 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3436 			     IOERR_NO_RESOURCES)) {
3437 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3438 				phba->lpfc_rampdown_queue_depth(phba);
3439 				spin_lock_irqsave(&phba->hbalock, iflag);
3440 			}
3441 
3442 			/* Rsp ring <ringno> error: IOCB */
3443 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3444 					"0336 Rsp Ring %d error: IOCB Data: "
3445 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
3446 					pring->ringno,
3447 					irsp->un.ulpWord[0],
3448 					irsp->un.ulpWord[1],
3449 					irsp->un.ulpWord[2],
3450 					irsp->un.ulpWord[3],
3451 					irsp->un.ulpWord[4],
3452 					irsp->un.ulpWord[5],
3453 					*(uint32_t *)&irsp->un1,
3454 					*((uint32_t *)&irsp->un1 + 1));
3455 		}
3456 
3457 		switch (type) {
3458 		case LPFC_ABORT_IOCB:
3459 		case LPFC_SOL_IOCB:
3460 			/*
3461 			 * Idle exchange closed via ABTS from port.  No iocb
3462 			 * resources need to be recovered.
3463 			 */
3464 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3465 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3466 						"0333 IOCB cmd 0x%x"
3467 						" processed. Skipping"
3468 						" completion\n",
3469 						irsp->ulpCommand);
3470 				break;
3471 			}
3472 
3473 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3474 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3475 							 &rspiocbq);
3476 			spin_lock_irqsave(&phba->hbalock, iflag);
3477 			if (unlikely(!cmdiocbq))
3478 				break;
3479 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3480 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3481 			if (cmdiocbq->iocb_cmpl) {
3482 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3483 				(cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
3484 						      &rspiocbq);
3485 				spin_lock_irqsave(&phba->hbalock, iflag);
3486 			}
3487 			break;
3488 		case LPFC_UNSOL_IOCB:
3489 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3490 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
3491 			spin_lock_irqsave(&phba->hbalock, iflag);
3492 			break;
3493 		default:
3494 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3495 				char adaptermsg[LPFC_MAX_ADPTMSG];
3496 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3497 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
3498 				       MAX_MSG_DATA);
3499 				dev_warn(&((phba->pcidev)->dev),
3500 					 "lpfc%d: %s\n",
3501 					 phba->brd_no, adaptermsg);
3502 			} else {
3503 				/* Unknown IOCB command */
3504 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3505 						"0334 Unknown IOCB command "
3506 						"Data: x%x, x%x x%x x%x x%x\n",
3507 						type, irsp->ulpCommand,
3508 						irsp->ulpStatus,
3509 						irsp->ulpIoTag,
3510 						irsp->ulpContext);
3511 			}
3512 			break;
3513 		}
3514 
3515 		/*
3516 		 * The response IOCB has been processed.  Update the ring
3517 		 * pointer in SLIM.  If the port response put pointer has not
3518 		 * been updated, sync the pgp->rspPutInx and fetch the new port
3519 		 * response put pointer.
3520 		 */
3521 		writel(pring->sli.sli3.rspidx,
3522 			&phba->host_gp[pring->ringno].rspGetInx);
3523 
3524 		if (pring->sli.sli3.rspidx == portRspPut)
3525 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3526 	}
3527 
3528 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
3529 		pring->stats.iocb_rsp_full++;
3530 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3531 		writel(status, phba->CAregaddr);
3532 		readl(phba->CAregaddr);
3533 	}
3534 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3535 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3536 		pring->stats.iocb_cmd_empty++;
3537 
3538 		/* Force update of the local copy of cmdGetInx */
3539 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3540 		lpfc_sli_resume_iocb(phba, pring);
3541 
3542 		if ((pring->lpfc_sli_cmd_available))
3543 			(pring->lpfc_sli_cmd_available) (phba, pring);
3544 
3545 	}
3546 
3547 	phba->fcp_ring_in_use = 0;
3548 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3549 	return rc;
3550 }
3551 
3552 /**
3553  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
3554  * @phba: Pointer to HBA context object.
3555  * @pring: Pointer to driver SLI ring object.
3556  * @rspiocbp: Pointer to driver response IOCB object.
3557  *
3558  * This function is called from the worker thread when there is a slow-path
3559  * response IOCB to process. This function chains all the response iocbs until
3560  * seeing the iocb with the LE bit set. The function will call
3561  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
3562  * completion of a command iocb. The function will call the
3563  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
3564  * The function frees the resources or calls the completion handler if this
3565  * iocb is an abort completion. The function returns NULL when the response
3566  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
3567  * this function shall chain the iocb on to the iocb_continueq and return the
3568  * response iocb passed in.
3569  **/
3570 static struct lpfc_iocbq *
3571 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3572 			struct lpfc_iocbq *rspiocbp)
3573 {
3574 	struct lpfc_iocbq *saveq;
3575 	struct lpfc_iocbq *cmdiocbp;
3576 	struct lpfc_iocbq *next_iocb;
3577 	IOCB_t *irsp = NULL;
3578 	uint32_t free_saveq;
3579 	uint8_t iocb_cmd_type;
3580 	lpfc_iocb_type type;
3581 	unsigned long iflag;
3582 	int rc;
3583 
3584 	spin_lock_irqsave(&phba->hbalock, iflag);
3585 	/* First add the response iocb to the countinueq list */
3586 	list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
3587 	pring->iocb_continueq_cnt++;
3588 
3589 	/* Now, determine whether the list is completed for processing */
3590 	irsp = &rspiocbp->iocb;
3591 	if (irsp->ulpLe) {
3592 		/*
3593 		 * By default, the driver expects to free all resources
3594 		 * associated with this iocb completion.
3595 		 */
3596 		free_saveq = 1;
3597 		saveq = list_get_first(&pring->iocb_continueq,
3598 				       struct lpfc_iocbq, list);
3599 		irsp = &(saveq->iocb);
3600 		list_del_init(&pring->iocb_continueq);
3601 		pring->iocb_continueq_cnt = 0;
3602 
3603 		pring->stats.iocb_rsp++;
3604 
3605 		/*
3606 		 * If resource errors reported from HBA, reduce
3607 		 * queuedepths of the SCSI device.
3608 		 */
3609 		if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3610 		    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3611 		     IOERR_NO_RESOURCES)) {
3612 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3613 			phba->lpfc_rampdown_queue_depth(phba);
3614 			spin_lock_irqsave(&phba->hbalock, iflag);
3615 		}
3616 
3617 		if (irsp->ulpStatus) {
3618 			/* Rsp ring <ringno> error: IOCB */
3619 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3620 					"0328 Rsp Ring %d error: "
3621 					"IOCB Data: "
3622 					"x%x x%x x%x x%x "
3623 					"x%x x%x x%x x%x "
3624 					"x%x x%x x%x x%x "
3625 					"x%x x%x x%x x%x\n",
3626 					pring->ringno,
3627 					irsp->un.ulpWord[0],
3628 					irsp->un.ulpWord[1],
3629 					irsp->un.ulpWord[2],
3630 					irsp->un.ulpWord[3],
3631 					irsp->un.ulpWord[4],
3632 					irsp->un.ulpWord[5],
3633 					*(((uint32_t *) irsp) + 6),
3634 					*(((uint32_t *) irsp) + 7),
3635 					*(((uint32_t *) irsp) + 8),
3636 					*(((uint32_t *) irsp) + 9),
3637 					*(((uint32_t *) irsp) + 10),
3638 					*(((uint32_t *) irsp) + 11),
3639 					*(((uint32_t *) irsp) + 12),
3640 					*(((uint32_t *) irsp) + 13),
3641 					*(((uint32_t *) irsp) + 14),
3642 					*(((uint32_t *) irsp) + 15));
3643 		}
3644 
3645 		/*
3646 		 * Fetch the IOCB command type and call the correct completion
3647 		 * routine. Solicited and Unsolicited IOCBs on the ELS ring
3648 		 * get freed back to the lpfc_iocb_list by the discovery
3649 		 * kernel thread.
3650 		 */
3651 		iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
3652 		type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
3653 		switch (type) {
3654 		case LPFC_SOL_IOCB:
3655 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3656 			rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
3657 			spin_lock_irqsave(&phba->hbalock, iflag);
3658 			break;
3659 
3660 		case LPFC_UNSOL_IOCB:
3661 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3662 			rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
3663 			spin_lock_irqsave(&phba->hbalock, iflag);
3664 			if (!rc)
3665 				free_saveq = 0;
3666 			break;
3667 
3668 		case LPFC_ABORT_IOCB:
3669 			cmdiocbp = NULL;
3670 			if (irsp->ulpCommand != CMD_XRI_ABORTED_CX) {
3671 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3672 				cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
3673 								 saveq);
3674 				spin_lock_irqsave(&phba->hbalock, iflag);
3675 			}
3676 			if (cmdiocbp) {
3677 				/* Call the specified completion routine */
3678 				if (cmdiocbp->iocb_cmpl) {
3679 					spin_unlock_irqrestore(&phba->hbalock,
3680 							       iflag);
3681 					(cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
3682 							      saveq);
3683 					spin_lock_irqsave(&phba->hbalock,
3684 							  iflag);
3685 				} else
3686 					__lpfc_sli_release_iocbq(phba,
3687 								 cmdiocbp);
3688 			}
3689 			break;
3690 
3691 		case LPFC_UNKNOWN_IOCB:
3692 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3693 				char adaptermsg[LPFC_MAX_ADPTMSG];
3694 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3695 				memcpy(&adaptermsg[0], (uint8_t *)irsp,
3696 				       MAX_MSG_DATA);
3697 				dev_warn(&((phba->pcidev)->dev),
3698 					 "lpfc%d: %s\n",
3699 					 phba->brd_no, adaptermsg);
3700 			} else {
3701 				/* Unknown IOCB command */
3702 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3703 						"0335 Unknown IOCB "
3704 						"command Data: x%x "
3705 						"x%x x%x x%x\n",
3706 						irsp->ulpCommand,
3707 						irsp->ulpStatus,
3708 						irsp->ulpIoTag,
3709 						irsp->ulpContext);
3710 			}
3711 			break;
3712 		}
3713 
3714 		if (free_saveq) {
3715 			list_for_each_entry_safe(rspiocbp, next_iocb,
3716 						 &saveq->list, list) {
3717 				list_del_init(&rspiocbp->list);
3718 				__lpfc_sli_release_iocbq(phba, rspiocbp);
3719 			}
3720 			__lpfc_sli_release_iocbq(phba, saveq);
3721 		}
3722 		rspiocbp = NULL;
3723 	}
3724 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3725 	return rspiocbp;
3726 }
3727 
3728 /**
3729  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
3730  * @phba: Pointer to HBA context object.
3731  * @pring: Pointer to driver SLI ring object.
3732  * @mask: Host attention register mask for this ring.
3733  *
3734  * This routine wraps the actual slow_ring event process routine from the
3735  * API jump table function pointer from the lpfc_hba struct.
3736  **/
3737 void
3738 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
3739 				struct lpfc_sli_ring *pring, uint32_t mask)
3740 {
3741 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
3742 }
3743 
3744 /**
3745  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
3746  * @phba: Pointer to HBA context object.
3747  * @pring: Pointer to driver SLI ring object.
3748  * @mask: Host attention register mask for this ring.
3749  *
3750  * This function is called from the worker thread when there is a ring event
3751  * for non-fcp rings. The caller does not hold any lock. The function will
3752  * remove each response iocb in the response ring and calls the handle
3753  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3754  **/
3755 static void
3756 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
3757 				   struct lpfc_sli_ring *pring, uint32_t mask)
3758 {
3759 	struct lpfc_pgp *pgp;
3760 	IOCB_t *entry;
3761 	IOCB_t *irsp = NULL;
3762 	struct lpfc_iocbq *rspiocbp = NULL;
3763 	uint32_t portRspPut, portRspMax;
3764 	unsigned long iflag;
3765 	uint32_t status;
3766 
3767 	pgp = &phba->port_gp[pring->ringno];
3768 	spin_lock_irqsave(&phba->hbalock, iflag);
3769 	pring->stats.iocb_event++;
3770 
3771 	/*
3772 	 * The next available response entry should never exceed the maximum
3773 	 * entries.  If it does, treat it as an adapter hardware error.
3774 	 */
3775 	portRspMax = pring->sli.sli3.numRiocb;
3776 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3777 	if (portRspPut >= portRspMax) {
3778 		/*
3779 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3780 		 * rsp ring <portRspMax>
3781 		 */
3782 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3783 				"0303 Ring %d handler: portRspPut %d "
3784 				"is bigger than rsp ring %d\n",
3785 				pring->ringno, portRspPut, portRspMax);
3786 
3787 		phba->link_state = LPFC_HBA_ERROR;
3788 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3789 
3790 		phba->work_hs = HS_FFER3;
3791 		lpfc_handle_eratt(phba);
3792 
3793 		return;
3794 	}
3795 
3796 	rmb();
3797 	while (pring->sli.sli3.rspidx != portRspPut) {
3798 		/*
3799 		 * Build a completion list and call the appropriate handler.
3800 		 * The process is to get the next available response iocb, get
3801 		 * a free iocb from the list, copy the response data into the
3802 		 * free iocb, insert to the continuation list, and update the
3803 		 * next response index to slim.  This process makes response
3804 		 * iocb's in the ring available to DMA as fast as possible but
3805 		 * pays a penalty for a copy operation.  Since the iocb is
3806 		 * only 32 bytes, this penalty is considered small relative to
3807 		 * the PCI reads for register values and a slim write.  When
3808 		 * the ulpLe field is set, the entire Command has been
3809 		 * received.
3810 		 */
3811 		entry = lpfc_resp_iocb(phba, pring);
3812 
3813 		phba->last_completion_time = jiffies;
3814 		rspiocbp = __lpfc_sli_get_iocbq(phba);
3815 		if (rspiocbp == NULL) {
3816 			printk(KERN_ERR "%s: out of buffers! Failing "
3817 			       "completion.\n", __func__);
3818 			break;
3819 		}
3820 
3821 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
3822 				      phba->iocb_rsp_size);
3823 		irsp = &rspiocbp->iocb;
3824 
3825 		if (++pring->sli.sli3.rspidx >= portRspMax)
3826 			pring->sli.sli3.rspidx = 0;
3827 
3828 		if (pring->ringno == LPFC_ELS_RING) {
3829 			lpfc_debugfs_slow_ring_trc(phba,
3830 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
3831 				*(((uint32_t *) irsp) + 4),
3832 				*(((uint32_t *) irsp) + 6),
3833 				*(((uint32_t *) irsp) + 7));
3834 		}
3835 
3836 		writel(pring->sli.sli3.rspidx,
3837 			&phba->host_gp[pring->ringno].rspGetInx);
3838 
3839 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3840 		/* Handle the response IOCB */
3841 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
3842 		spin_lock_irqsave(&phba->hbalock, iflag);
3843 
3844 		/*
3845 		 * If the port response put pointer has not been updated, sync
3846 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
3847 		 * response put pointer.
3848 		 */
3849 		if (pring->sli.sli3.rspidx == portRspPut) {
3850 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3851 		}
3852 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
3853 
3854 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
3855 		/* At least one response entry has been freed */
3856 		pring->stats.iocb_rsp_full++;
3857 		/* SET RxRE_RSP in Chip Att register */
3858 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3859 		writel(status, phba->CAregaddr);
3860 		readl(phba->CAregaddr); /* flush */
3861 	}
3862 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3863 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3864 		pring->stats.iocb_cmd_empty++;
3865 
3866 		/* Force update of the local copy of cmdGetInx */
3867 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3868 		lpfc_sli_resume_iocb(phba, pring);
3869 
3870 		if ((pring->lpfc_sli_cmd_available))
3871 			(pring->lpfc_sli_cmd_available) (phba, pring);
3872 
3873 	}
3874 
3875 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3876 	return;
3877 }
3878 
3879 /**
3880  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
3881  * @phba: Pointer to HBA context object.
3882  * @pring: Pointer to driver SLI ring object.
3883  * @mask: Host attention register mask for this ring.
3884  *
3885  * This function is called from the worker thread when there is a pending
3886  * ELS response iocb on the driver internal slow-path response iocb worker
3887  * queue. The caller does not hold any lock. The function will remove each
3888  * response iocb from the response worker queue and calls the handle
3889  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3890  **/
3891 static void
3892 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
3893 				   struct lpfc_sli_ring *pring, uint32_t mask)
3894 {
3895 	struct lpfc_iocbq *irspiocbq;
3896 	struct hbq_dmabuf *dmabuf;
3897 	struct lpfc_cq_event *cq_event;
3898 	unsigned long iflag;
3899 	int count = 0;
3900 
3901 	spin_lock_irqsave(&phba->hbalock, iflag);
3902 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
3903 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3904 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
3905 		/* Get the response iocb from the head of work queue */
3906 		spin_lock_irqsave(&phba->hbalock, iflag);
3907 		list_remove_head(&phba->sli4_hba.sp_queue_event,
3908 				 cq_event, struct lpfc_cq_event, list);
3909 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3910 
3911 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
3912 		case CQE_CODE_COMPL_WQE:
3913 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
3914 						 cq_event);
3915 			/* Translate ELS WCQE to response IOCBQ */
3916 			irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
3917 								   irspiocbq);
3918 			if (irspiocbq)
3919 				lpfc_sli_sp_handle_rspiocb(phba, pring,
3920 							   irspiocbq);
3921 			count++;
3922 			break;
3923 		case CQE_CODE_RECEIVE:
3924 		case CQE_CODE_RECEIVE_V1:
3925 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
3926 					      cq_event);
3927 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
3928 			count++;
3929 			break;
3930 		default:
3931 			break;
3932 		}
3933 
3934 		/* Limit the number of events to 64 to avoid soft lockups */
3935 		if (count == 64)
3936 			break;
3937 	}
3938 }
3939 
3940 /**
3941  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
3942  * @phba: Pointer to HBA context object.
3943  * @pring: Pointer to driver SLI ring object.
3944  *
3945  * This function aborts all iocbs in the given ring and frees all the iocb
3946  * objects in txq. This function issues an abort iocb for all the iocb commands
3947  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3948  * the return of this function. The caller is not required to hold any locks.
3949  **/
3950 void
3951 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3952 {
3953 	LIST_HEAD(completions);
3954 	struct lpfc_iocbq *iocb, *next_iocb;
3955 
3956 	if (pring->ringno == LPFC_ELS_RING) {
3957 		lpfc_fabric_abort_hba(phba);
3958 	}
3959 
3960 	/* Error everything on txq and txcmplq
3961 	 * First do the txq.
3962 	 */
3963 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3964 		spin_lock_irq(&pring->ring_lock);
3965 		list_splice_init(&pring->txq, &completions);
3966 		pring->txq_cnt = 0;
3967 		spin_unlock_irq(&pring->ring_lock);
3968 
3969 		spin_lock_irq(&phba->hbalock);
3970 		/* Next issue ABTS for everything on the txcmplq */
3971 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3972 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3973 		spin_unlock_irq(&phba->hbalock);
3974 	} else {
3975 		spin_lock_irq(&phba->hbalock);
3976 		list_splice_init(&pring->txq, &completions);
3977 		pring->txq_cnt = 0;
3978 
3979 		/* Next issue ABTS for everything on the txcmplq */
3980 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3981 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3982 		spin_unlock_irq(&phba->hbalock);
3983 	}
3984 
3985 	/* Cancel all the IOCBs from the completions list */
3986 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
3987 			      IOERR_SLI_ABORTED);
3988 }
3989 
3990 /**
3991  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
3992  * @phba: Pointer to HBA context object.
3993  * @pring: Pointer to driver SLI ring object.
3994  *
3995  * This function aborts all iocbs in FCP rings and frees all the iocb
3996  * objects in txq. This function issues an abort iocb for all the iocb commands
3997  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3998  * the return of this function. The caller is not required to hold any locks.
3999  **/
4000 void
4001 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4002 {
4003 	struct lpfc_sli *psli = &phba->sli;
4004 	struct lpfc_sli_ring  *pring;
4005 	uint32_t i;
4006 
4007 	/* Look on all the FCP Rings for the iotag */
4008 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4009 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4010 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4011 			lpfc_sli_abort_iocb_ring(phba, pring);
4012 		}
4013 	} else {
4014 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4015 		lpfc_sli_abort_iocb_ring(phba, pring);
4016 	}
4017 }
4018 
4019 /**
4020  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4021  * @phba: Pointer to HBA context object.
4022  *
4023  * This function flushes all iocbs in the IO ring and frees all the iocb
4024  * objects in txq and txcmplq. This function will not issue abort iocbs
4025  * for all the iocb commands in txcmplq, they will just be returned with
4026  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4027  * slot has been permanently disabled.
4028  **/
4029 void
4030 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4031 {
4032 	LIST_HEAD(txq);
4033 	LIST_HEAD(txcmplq);
4034 	struct lpfc_sli *psli = &phba->sli;
4035 	struct lpfc_sli_ring  *pring;
4036 	uint32_t i;
4037 	struct lpfc_iocbq *piocb, *next_iocb;
4038 
4039 	spin_lock_irq(&phba->hbalock);
4040 	if (phba->hba_flag & HBA_IOQ_FLUSH ||
4041 	    !phba->sli4_hba.hdwq) {
4042 		spin_unlock_irq(&phba->hbalock);
4043 		return;
4044 	}
4045 	/* Indicate the I/O queues are flushed */
4046 	phba->hba_flag |= HBA_IOQ_FLUSH;
4047 	spin_unlock_irq(&phba->hbalock);
4048 
4049 	/* Look on all the FCP Rings for the iotag */
4050 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4051 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4052 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4053 
4054 			spin_lock_irq(&pring->ring_lock);
4055 			/* Retrieve everything on txq */
4056 			list_splice_init(&pring->txq, &txq);
4057 			list_for_each_entry_safe(piocb, next_iocb,
4058 						 &pring->txcmplq, list)
4059 				piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4060 			/* Retrieve everything on the txcmplq */
4061 			list_splice_init(&pring->txcmplq, &txcmplq);
4062 			pring->txq_cnt = 0;
4063 			pring->txcmplq_cnt = 0;
4064 			spin_unlock_irq(&pring->ring_lock);
4065 
4066 			/* Flush the txq */
4067 			lpfc_sli_cancel_iocbs(phba, &txq,
4068 					      IOSTAT_LOCAL_REJECT,
4069 					      IOERR_SLI_DOWN);
4070 			/* Flush the txcmpq */
4071 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4072 					      IOSTAT_LOCAL_REJECT,
4073 					      IOERR_SLI_DOWN);
4074 		}
4075 	} else {
4076 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4077 
4078 		spin_lock_irq(&phba->hbalock);
4079 		/* Retrieve everything on txq */
4080 		list_splice_init(&pring->txq, &txq);
4081 		list_for_each_entry_safe(piocb, next_iocb,
4082 					 &pring->txcmplq, list)
4083 			piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4084 		/* Retrieve everything on the txcmplq */
4085 		list_splice_init(&pring->txcmplq, &txcmplq);
4086 		pring->txq_cnt = 0;
4087 		pring->txcmplq_cnt = 0;
4088 		spin_unlock_irq(&phba->hbalock);
4089 
4090 		/* Flush the txq */
4091 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4092 				      IOERR_SLI_DOWN);
4093 		/* Flush the txcmpq */
4094 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4095 				      IOERR_SLI_DOWN);
4096 	}
4097 }
4098 
4099 /**
4100  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4101  * @phba: Pointer to HBA context object.
4102  * @mask: Bit mask to be checked.
4103  *
4104  * This function reads the host status register and compares
4105  * with the provided bit mask to check if HBA completed
4106  * the restart. This function will wait in a loop for the
4107  * HBA to complete restart. If the HBA does not restart within
4108  * 15 iterations, the function will reset the HBA again. The
4109  * function returns 1 when HBA fail to restart otherwise returns
4110  * zero.
4111  **/
4112 static int
4113 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4114 {
4115 	uint32_t status;
4116 	int i = 0;
4117 	int retval = 0;
4118 
4119 	/* Read the HBA Host Status Register */
4120 	if (lpfc_readl(phba->HSregaddr, &status))
4121 		return 1;
4122 
4123 	/*
4124 	 * Check status register every 100ms for 5 retries, then every
4125 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4126 	 * every 2.5 sec for 4.
4127 	 * Break our of the loop if errors occurred during init.
4128 	 */
4129 	while (((status & mask) != mask) &&
4130 	       !(status & HS_FFERM) &&
4131 	       i++ < 20) {
4132 
4133 		if (i <= 5)
4134 			msleep(10);
4135 		else if (i <= 10)
4136 			msleep(500);
4137 		else
4138 			msleep(2500);
4139 
4140 		if (i == 15) {
4141 				/* Do post */
4142 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4143 			lpfc_sli_brdrestart(phba);
4144 		}
4145 		/* Read the HBA Host Status Register */
4146 		if (lpfc_readl(phba->HSregaddr, &status)) {
4147 			retval = 1;
4148 			break;
4149 		}
4150 	}
4151 
4152 	/* Check to see if any errors occurred during init */
4153 	if ((status & HS_FFERM) || (i >= 20)) {
4154 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4155 				"2751 Adapter failed to restart, "
4156 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4157 				status,
4158 				readl(phba->MBslimaddr + 0xa8),
4159 				readl(phba->MBslimaddr + 0xac));
4160 		phba->link_state = LPFC_HBA_ERROR;
4161 		retval = 1;
4162 	}
4163 
4164 	return retval;
4165 }
4166 
4167 /**
4168  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4169  * @phba: Pointer to HBA context object.
4170  * @mask: Bit mask to be checked.
4171  *
4172  * This function checks the host status register to check if HBA is
4173  * ready. This function will wait in a loop for the HBA to be ready
4174  * If the HBA is not ready , the function will will reset the HBA PCI
4175  * function again. The function returns 1 when HBA fail to be ready
4176  * otherwise returns zero.
4177  **/
4178 static int
4179 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4180 {
4181 	uint32_t status;
4182 	int retval = 0;
4183 
4184 	/* Read the HBA Host Status Register */
4185 	status = lpfc_sli4_post_status_check(phba);
4186 
4187 	if (status) {
4188 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4189 		lpfc_sli_brdrestart(phba);
4190 		status = lpfc_sli4_post_status_check(phba);
4191 	}
4192 
4193 	/* Check to see if any errors occurred during init */
4194 	if (status) {
4195 		phba->link_state = LPFC_HBA_ERROR;
4196 		retval = 1;
4197 	} else
4198 		phba->sli4_hba.intr_enable = 0;
4199 
4200 	return retval;
4201 }
4202 
4203 /**
4204  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4205  * @phba: Pointer to HBA context object.
4206  * @mask: Bit mask to be checked.
4207  *
4208  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4209  * from the API jump table function pointer from the lpfc_hba struct.
4210  **/
4211 int
4212 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4213 {
4214 	return phba->lpfc_sli_brdready(phba, mask);
4215 }
4216 
4217 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4218 
4219 /**
4220  * lpfc_reset_barrier - Make HBA ready for HBA reset
4221  * @phba: Pointer to HBA context object.
4222  *
4223  * This function is called before resetting an HBA. This function is called
4224  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4225  **/
4226 void lpfc_reset_barrier(struct lpfc_hba *phba)
4227 {
4228 	uint32_t __iomem *resp_buf;
4229 	uint32_t __iomem *mbox_buf;
4230 	volatile uint32_t mbox;
4231 	uint32_t hc_copy, ha_copy, resp_data;
4232 	int  i;
4233 	uint8_t hdrtype;
4234 
4235 	lockdep_assert_held(&phba->hbalock);
4236 
4237 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4238 	if (hdrtype != 0x80 ||
4239 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4240 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4241 		return;
4242 
4243 	/*
4244 	 * Tell the other part of the chip to suspend temporarily all
4245 	 * its DMA activity.
4246 	 */
4247 	resp_buf = phba->MBslimaddr;
4248 
4249 	/* Disable the error attention */
4250 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4251 		return;
4252 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4253 	readl(phba->HCregaddr); /* flush */
4254 	phba->link_flag |= LS_IGNORE_ERATT;
4255 
4256 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4257 		return;
4258 	if (ha_copy & HA_ERATT) {
4259 		/* Clear Chip error bit */
4260 		writel(HA_ERATT, phba->HAregaddr);
4261 		phba->pport->stopped = 1;
4262 	}
4263 
4264 	mbox = 0;
4265 	((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
4266 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
4267 
4268 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4269 	mbox_buf = phba->MBslimaddr;
4270 	writel(mbox, mbox_buf);
4271 
4272 	for (i = 0; i < 50; i++) {
4273 		if (lpfc_readl((resp_buf + 1), &resp_data))
4274 			return;
4275 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4276 			mdelay(1);
4277 		else
4278 			break;
4279 	}
4280 	resp_data = 0;
4281 	if (lpfc_readl((resp_buf + 1), &resp_data))
4282 		return;
4283 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4284 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4285 		    phba->pport->stopped)
4286 			goto restore_hc;
4287 		else
4288 			goto clear_errat;
4289 	}
4290 
4291 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
4292 	resp_data = 0;
4293 	for (i = 0; i < 500; i++) {
4294 		if (lpfc_readl(resp_buf, &resp_data))
4295 			return;
4296 		if (resp_data != mbox)
4297 			mdelay(1);
4298 		else
4299 			break;
4300 	}
4301 
4302 clear_errat:
4303 
4304 	while (++i < 500) {
4305 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4306 			return;
4307 		if (!(ha_copy & HA_ERATT))
4308 			mdelay(1);
4309 		else
4310 			break;
4311 	}
4312 
4313 	if (readl(phba->HAregaddr) & HA_ERATT) {
4314 		writel(HA_ERATT, phba->HAregaddr);
4315 		phba->pport->stopped = 1;
4316 	}
4317 
4318 restore_hc:
4319 	phba->link_flag &= ~LS_IGNORE_ERATT;
4320 	writel(hc_copy, phba->HCregaddr);
4321 	readl(phba->HCregaddr); /* flush */
4322 }
4323 
4324 /**
4325  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4326  * @phba: Pointer to HBA context object.
4327  *
4328  * This function issues a kill_board mailbox command and waits for
4329  * the error attention interrupt. This function is called for stopping
4330  * the firmware processing. The caller is not required to hold any
4331  * locks. This function calls lpfc_hba_down_post function to free
4332  * any pending commands after the kill. The function will return 1 when it
4333  * fails to kill the board else will return 0.
4334  **/
4335 int
4336 lpfc_sli_brdkill(struct lpfc_hba *phba)
4337 {
4338 	struct lpfc_sli *psli;
4339 	LPFC_MBOXQ_t *pmb;
4340 	uint32_t status;
4341 	uint32_t ha_copy;
4342 	int retval;
4343 	int i = 0;
4344 
4345 	psli = &phba->sli;
4346 
4347 	/* Kill HBA */
4348 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4349 			"0329 Kill HBA Data: x%x x%x\n",
4350 			phba->pport->port_state, psli->sli_flag);
4351 
4352 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4353 	if (!pmb)
4354 		return 1;
4355 
4356 	/* Disable the error attention */
4357 	spin_lock_irq(&phba->hbalock);
4358 	if (lpfc_readl(phba->HCregaddr, &status)) {
4359 		spin_unlock_irq(&phba->hbalock);
4360 		mempool_free(pmb, phba->mbox_mem_pool);
4361 		return 1;
4362 	}
4363 	status &= ~HC_ERINT_ENA;
4364 	writel(status, phba->HCregaddr);
4365 	readl(phba->HCregaddr); /* flush */
4366 	phba->link_flag |= LS_IGNORE_ERATT;
4367 	spin_unlock_irq(&phba->hbalock);
4368 
4369 	lpfc_kill_board(phba, pmb);
4370 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4371 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4372 
4373 	if (retval != MBX_SUCCESS) {
4374 		if (retval != MBX_BUSY)
4375 			mempool_free(pmb, phba->mbox_mem_pool);
4376 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4377 				"2752 KILL_BOARD command failed retval %d\n",
4378 				retval);
4379 		spin_lock_irq(&phba->hbalock);
4380 		phba->link_flag &= ~LS_IGNORE_ERATT;
4381 		spin_unlock_irq(&phba->hbalock);
4382 		return 1;
4383 	}
4384 
4385 	spin_lock_irq(&phba->hbalock);
4386 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
4387 	spin_unlock_irq(&phba->hbalock);
4388 
4389 	mempool_free(pmb, phba->mbox_mem_pool);
4390 
4391 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
4392 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
4393 	 * 3 seconds we still set HBA_ERROR state because the status of the
4394 	 * board is now undefined.
4395 	 */
4396 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4397 		return 1;
4398 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
4399 		mdelay(100);
4400 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4401 			return 1;
4402 	}
4403 
4404 	del_timer_sync(&psli->mbox_tmo);
4405 	if (ha_copy & HA_ERATT) {
4406 		writel(HA_ERATT, phba->HAregaddr);
4407 		phba->pport->stopped = 1;
4408 	}
4409 	spin_lock_irq(&phba->hbalock);
4410 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4411 	psli->mbox_active = NULL;
4412 	phba->link_flag &= ~LS_IGNORE_ERATT;
4413 	spin_unlock_irq(&phba->hbalock);
4414 
4415 	lpfc_hba_down_post(phba);
4416 	phba->link_state = LPFC_HBA_ERROR;
4417 
4418 	return ha_copy & HA_ERATT ? 0 : 1;
4419 }
4420 
4421 /**
4422  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
4423  * @phba: Pointer to HBA context object.
4424  *
4425  * This function resets the HBA by writing HC_INITFF to the control
4426  * register. After the HBA resets, this function resets all the iocb ring
4427  * indices. This function disables PCI layer parity checking during
4428  * the reset.
4429  * This function returns 0 always.
4430  * The caller is not required to hold any locks.
4431  **/
4432 int
4433 lpfc_sli_brdreset(struct lpfc_hba *phba)
4434 {
4435 	struct lpfc_sli *psli;
4436 	struct lpfc_sli_ring *pring;
4437 	uint16_t cfg_value;
4438 	int i;
4439 
4440 	psli = &phba->sli;
4441 
4442 	/* Reset HBA */
4443 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4444 			"0325 Reset HBA Data: x%x x%x\n",
4445 			(phba->pport) ? phba->pport->port_state : 0,
4446 			psli->sli_flag);
4447 
4448 	/* perform board reset */
4449 	phba->fc_eventTag = 0;
4450 	phba->link_events = 0;
4451 	if (phba->pport) {
4452 		phba->pport->fc_myDID = 0;
4453 		phba->pport->fc_prevDID = 0;
4454 	}
4455 
4456 	/* Turn off parity checking and serr during the physical reset */
4457 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
4458 		return -EIO;
4459 
4460 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
4461 			      (cfg_value &
4462 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4463 
4464 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4465 
4466 	/* Now toggle INITFF bit in the Host Control Register */
4467 	writel(HC_INITFF, phba->HCregaddr);
4468 	mdelay(1);
4469 	readl(phba->HCregaddr); /* flush */
4470 	writel(0, phba->HCregaddr);
4471 	readl(phba->HCregaddr); /* flush */
4472 
4473 	/* Restore PCI cmd register */
4474 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4475 
4476 	/* Initialize relevant SLI info */
4477 	for (i = 0; i < psli->num_rings; i++) {
4478 		pring = &psli->sli3_ring[i];
4479 		pring->flag = 0;
4480 		pring->sli.sli3.rspidx = 0;
4481 		pring->sli.sli3.next_cmdidx  = 0;
4482 		pring->sli.sli3.local_getidx = 0;
4483 		pring->sli.sli3.cmdidx = 0;
4484 		pring->missbufcnt = 0;
4485 	}
4486 
4487 	phba->link_state = LPFC_WARM_START;
4488 	return 0;
4489 }
4490 
4491 /**
4492  * lpfc_sli4_brdreset - Reset a sli-4 HBA
4493  * @phba: Pointer to HBA context object.
4494  *
4495  * This function resets a SLI4 HBA. This function disables PCI layer parity
4496  * checking during resets the device. The caller is not required to hold
4497  * any locks.
4498  *
4499  * This function returns 0 on success else returns negative error code.
4500  **/
4501 int
4502 lpfc_sli4_brdreset(struct lpfc_hba *phba)
4503 {
4504 	struct lpfc_sli *psli = &phba->sli;
4505 	uint16_t cfg_value;
4506 	int rc = 0;
4507 
4508 	/* Reset HBA */
4509 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4510 			"0295 Reset HBA Data: x%x x%x x%x\n",
4511 			phba->pport->port_state, psli->sli_flag,
4512 			phba->hba_flag);
4513 
4514 	/* perform board reset */
4515 	phba->fc_eventTag = 0;
4516 	phba->link_events = 0;
4517 	phba->pport->fc_myDID = 0;
4518 	phba->pport->fc_prevDID = 0;
4519 
4520 	spin_lock_irq(&phba->hbalock);
4521 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
4522 	phba->fcf.fcf_flag = 0;
4523 	spin_unlock_irq(&phba->hbalock);
4524 
4525 	/* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
4526 	if (phba->hba_flag & HBA_FW_DUMP_OP) {
4527 		phba->hba_flag &= ~HBA_FW_DUMP_OP;
4528 		return rc;
4529 	}
4530 
4531 	/* Now physically reset the device */
4532 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4533 			"0389 Performing PCI function reset!\n");
4534 
4535 	/* Turn off parity checking and serr during the physical reset */
4536 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
4537 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4538 				"3205 PCI read Config failed\n");
4539 		return -EIO;
4540 	}
4541 
4542 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
4543 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4544 
4545 	/* Perform FCoE PCI function reset before freeing queue memory */
4546 	rc = lpfc_pci_function_reset(phba);
4547 
4548 	/* Restore PCI cmd register */
4549 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4550 
4551 	return rc;
4552 }
4553 
4554 /**
4555  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
4556  * @phba: Pointer to HBA context object.
4557  *
4558  * This function is called in the SLI initialization code path to
4559  * restart the HBA. The caller is not required to hold any lock.
4560  * This function writes MBX_RESTART mailbox command to the SLIM and
4561  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
4562  * function to free any pending commands. The function enables
4563  * POST only during the first initialization. The function returns zero.
4564  * The function does not guarantee completion of MBX_RESTART mailbox
4565  * command before the return of this function.
4566  **/
4567 static int
4568 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
4569 {
4570 	MAILBOX_t *mb;
4571 	struct lpfc_sli *psli;
4572 	volatile uint32_t word0;
4573 	void __iomem *to_slim;
4574 	uint32_t hba_aer_enabled;
4575 
4576 	spin_lock_irq(&phba->hbalock);
4577 
4578 	/* Take PCIe device Advanced Error Reporting (AER) state */
4579 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4580 
4581 	psli = &phba->sli;
4582 
4583 	/* Restart HBA */
4584 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4585 			"0337 Restart HBA Data: x%x x%x\n",
4586 			(phba->pport) ? phba->pport->port_state : 0,
4587 			psli->sli_flag);
4588 
4589 	word0 = 0;
4590 	mb = (MAILBOX_t *) &word0;
4591 	mb->mbxCommand = MBX_RESTART;
4592 	mb->mbxHc = 1;
4593 
4594 	lpfc_reset_barrier(phba);
4595 
4596 	to_slim = phba->MBslimaddr;
4597 	writel(*(uint32_t *) mb, to_slim);
4598 	readl(to_slim); /* flush */
4599 
4600 	/* Only skip post after fc_ffinit is completed */
4601 	if (phba->pport && phba->pport->port_state)
4602 		word0 = 1;	/* This is really setting up word1 */
4603 	else
4604 		word0 = 0;	/* This is really setting up word1 */
4605 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
4606 	writel(*(uint32_t *) mb, to_slim);
4607 	readl(to_slim); /* flush */
4608 
4609 	lpfc_sli_brdreset(phba);
4610 	if (phba->pport)
4611 		phba->pport->stopped = 0;
4612 	phba->link_state = LPFC_INIT_START;
4613 	phba->hba_flag = 0;
4614 	spin_unlock_irq(&phba->hbalock);
4615 
4616 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4617 	psli->stats_start = ktime_get_seconds();
4618 
4619 	/* Give the INITFF and Post time to settle. */
4620 	mdelay(100);
4621 
4622 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4623 	if (hba_aer_enabled)
4624 		pci_disable_pcie_error_reporting(phba->pcidev);
4625 
4626 	lpfc_hba_down_post(phba);
4627 
4628 	return 0;
4629 }
4630 
4631 /**
4632  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
4633  * @phba: Pointer to HBA context object.
4634  *
4635  * This function is called in the SLI initialization code path to restart
4636  * a SLI4 HBA. The caller is not required to hold any lock.
4637  * At the end of the function, it calls lpfc_hba_down_post function to
4638  * free any pending commands.
4639  **/
4640 static int
4641 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
4642 {
4643 	struct lpfc_sli *psli = &phba->sli;
4644 	uint32_t hba_aer_enabled;
4645 	int rc;
4646 
4647 	/* Restart HBA */
4648 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4649 			"0296 Restart HBA Data: x%x x%x\n",
4650 			phba->pport->port_state, psli->sli_flag);
4651 
4652 	/* Take PCIe device Advanced Error Reporting (AER) state */
4653 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4654 
4655 	rc = lpfc_sli4_brdreset(phba);
4656 	if (rc) {
4657 		phba->link_state = LPFC_HBA_ERROR;
4658 		goto hba_down_queue;
4659 	}
4660 
4661 	spin_lock_irq(&phba->hbalock);
4662 	phba->pport->stopped = 0;
4663 	phba->link_state = LPFC_INIT_START;
4664 	phba->hba_flag = 0;
4665 	spin_unlock_irq(&phba->hbalock);
4666 
4667 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4668 	psli->stats_start = ktime_get_seconds();
4669 
4670 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4671 	if (hba_aer_enabled)
4672 		pci_disable_pcie_error_reporting(phba->pcidev);
4673 
4674 hba_down_queue:
4675 	lpfc_hba_down_post(phba);
4676 	lpfc_sli4_queue_destroy(phba);
4677 
4678 	return rc;
4679 }
4680 
4681 /**
4682  * lpfc_sli_brdrestart - Wrapper func for restarting hba
4683  * @phba: Pointer to HBA context object.
4684  *
4685  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
4686  * API jump table function pointer from the lpfc_hba struct.
4687 **/
4688 int
4689 lpfc_sli_brdrestart(struct lpfc_hba *phba)
4690 {
4691 	return phba->lpfc_sli_brdrestart(phba);
4692 }
4693 
4694 /**
4695  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
4696  * @phba: Pointer to HBA context object.
4697  *
4698  * This function is called after a HBA restart to wait for successful
4699  * restart of the HBA. Successful restart of the HBA is indicated by
4700  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
4701  * iteration, the function will restart the HBA again. The function returns
4702  * zero if HBA successfully restarted else returns negative error code.
4703  **/
4704 int
4705 lpfc_sli_chipset_init(struct lpfc_hba *phba)
4706 {
4707 	uint32_t status, i = 0;
4708 
4709 	/* Read the HBA Host Status Register */
4710 	if (lpfc_readl(phba->HSregaddr, &status))
4711 		return -EIO;
4712 
4713 	/* Check status register to see what current state is */
4714 	i = 0;
4715 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
4716 
4717 		/* Check every 10ms for 10 retries, then every 100ms for 90
4718 		 * retries, then every 1 sec for 50 retires for a total of
4719 		 * ~60 seconds before reset the board again and check every
4720 		 * 1 sec for 50 retries. The up to 60 seconds before the
4721 		 * board ready is required by the Falcon FIPS zeroization
4722 		 * complete, and any reset the board in between shall cause
4723 		 * restart of zeroization, further delay the board ready.
4724 		 */
4725 		if (i++ >= 200) {
4726 			/* Adapter failed to init, timeout, status reg
4727 			   <status> */
4728 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4729 					"0436 Adapter failed to init, "
4730 					"timeout, status reg x%x, "
4731 					"FW Data: A8 x%x AC x%x\n", status,
4732 					readl(phba->MBslimaddr + 0xa8),
4733 					readl(phba->MBslimaddr + 0xac));
4734 			phba->link_state = LPFC_HBA_ERROR;
4735 			return -ETIMEDOUT;
4736 		}
4737 
4738 		/* Check to see if any errors occurred during init */
4739 		if (status & HS_FFERM) {
4740 			/* ERROR: During chipset initialization */
4741 			/* Adapter failed to init, chipset, status reg
4742 			   <status> */
4743 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4744 					"0437 Adapter failed to init, "
4745 					"chipset, status reg x%x, "
4746 					"FW Data: A8 x%x AC x%x\n", status,
4747 					readl(phba->MBslimaddr + 0xa8),
4748 					readl(phba->MBslimaddr + 0xac));
4749 			phba->link_state = LPFC_HBA_ERROR;
4750 			return -EIO;
4751 		}
4752 
4753 		if (i <= 10)
4754 			msleep(10);
4755 		else if (i <= 100)
4756 			msleep(100);
4757 		else
4758 			msleep(1000);
4759 
4760 		if (i == 150) {
4761 			/* Do post */
4762 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4763 			lpfc_sli_brdrestart(phba);
4764 		}
4765 		/* Read the HBA Host Status Register */
4766 		if (lpfc_readl(phba->HSregaddr, &status))
4767 			return -EIO;
4768 	}
4769 
4770 	/* Check to see if any errors occurred during init */
4771 	if (status & HS_FFERM) {
4772 		/* ERROR: During chipset initialization */
4773 		/* Adapter failed to init, chipset, status reg <status> */
4774 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4775 				"0438 Adapter failed to init, chipset, "
4776 				"status reg x%x, "
4777 				"FW Data: A8 x%x AC x%x\n", status,
4778 				readl(phba->MBslimaddr + 0xa8),
4779 				readl(phba->MBslimaddr + 0xac));
4780 		phba->link_state = LPFC_HBA_ERROR;
4781 		return -EIO;
4782 	}
4783 
4784 	/* Clear all interrupt enable conditions */
4785 	writel(0, phba->HCregaddr);
4786 	readl(phba->HCregaddr); /* flush */
4787 
4788 	/* setup host attn register */
4789 	writel(0xffffffff, phba->HAregaddr);
4790 	readl(phba->HAregaddr); /* flush */
4791 	return 0;
4792 }
4793 
4794 /**
4795  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
4796  *
4797  * This function calculates and returns the number of HBQs required to be
4798  * configured.
4799  **/
4800 int
4801 lpfc_sli_hbq_count(void)
4802 {
4803 	return ARRAY_SIZE(lpfc_hbq_defs);
4804 }
4805 
4806 /**
4807  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
4808  *
4809  * This function adds the number of hbq entries in every HBQ to get
4810  * the total number of hbq entries required for the HBA and returns
4811  * the total count.
4812  **/
4813 static int
4814 lpfc_sli_hbq_entry_count(void)
4815 {
4816 	int  hbq_count = lpfc_sli_hbq_count();
4817 	int  count = 0;
4818 	int  i;
4819 
4820 	for (i = 0; i < hbq_count; ++i)
4821 		count += lpfc_hbq_defs[i]->entry_count;
4822 	return count;
4823 }
4824 
4825 /**
4826  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
4827  *
4828  * This function calculates amount of memory required for all hbq entries
4829  * to be configured and returns the total memory required.
4830  **/
4831 int
4832 lpfc_sli_hbq_size(void)
4833 {
4834 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
4835 }
4836 
4837 /**
4838  * lpfc_sli_hbq_setup - configure and initialize HBQs
4839  * @phba: Pointer to HBA context object.
4840  *
4841  * This function is called during the SLI initialization to configure
4842  * all the HBQs and post buffers to the HBQ. The caller is not
4843  * required to hold any locks. This function will return zero if successful
4844  * else it will return negative error code.
4845  **/
4846 static int
4847 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
4848 {
4849 	int  hbq_count = lpfc_sli_hbq_count();
4850 	LPFC_MBOXQ_t *pmb;
4851 	MAILBOX_t *pmbox;
4852 	uint32_t hbqno;
4853 	uint32_t hbq_entry_index;
4854 
4855 				/* Get a Mailbox buffer to setup mailbox
4856 				 * commands for HBA initialization
4857 				 */
4858 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4859 
4860 	if (!pmb)
4861 		return -ENOMEM;
4862 
4863 	pmbox = &pmb->u.mb;
4864 
4865 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
4866 	phba->link_state = LPFC_INIT_MBX_CMDS;
4867 	phba->hbq_in_use = 1;
4868 
4869 	hbq_entry_index = 0;
4870 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
4871 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
4872 		phba->hbqs[hbqno].hbqPutIdx      = 0;
4873 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
4874 		phba->hbqs[hbqno].entry_count =
4875 			lpfc_hbq_defs[hbqno]->entry_count;
4876 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
4877 			hbq_entry_index, pmb);
4878 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
4879 
4880 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
4881 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
4882 			   mbxStatus <status>, ring <num> */
4883 
4884 			lpfc_printf_log(phba, KERN_ERR,
4885 					LOG_SLI | LOG_VPORT,
4886 					"1805 Adapter failed to init. "
4887 					"Data: x%x x%x x%x\n",
4888 					pmbox->mbxCommand,
4889 					pmbox->mbxStatus, hbqno);
4890 
4891 			phba->link_state = LPFC_HBA_ERROR;
4892 			mempool_free(pmb, phba->mbox_mem_pool);
4893 			return -ENXIO;
4894 		}
4895 	}
4896 	phba->hbq_count = hbq_count;
4897 
4898 	mempool_free(pmb, phba->mbox_mem_pool);
4899 
4900 	/* Initially populate or replenish the HBQs */
4901 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
4902 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
4903 	return 0;
4904 }
4905 
4906 /**
4907  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
4908  * @phba: Pointer to HBA context object.
4909  *
4910  * This function is called during the SLI initialization to configure
4911  * all the HBQs and post buffers to the HBQ. The caller is not
4912  * required to hold any locks. This function will return zero if successful
4913  * else it will return negative error code.
4914  **/
4915 static int
4916 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
4917 {
4918 	phba->hbq_in_use = 1;
4919 	/**
4920 	 * Specific case when the MDS diagnostics is enabled and supported.
4921 	 * The receive buffer count is truncated to manage the incoming
4922 	 * traffic.
4923 	 **/
4924 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
4925 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
4926 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
4927 	else
4928 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
4929 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
4930 	phba->hbq_count = 1;
4931 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
4932 	/* Initially populate or replenish the HBQs */
4933 	return 0;
4934 }
4935 
4936 /**
4937  * lpfc_sli_config_port - Issue config port mailbox command
4938  * @phba: Pointer to HBA context object.
4939  * @sli_mode: sli mode - 2/3
4940  *
4941  * This function is called by the sli initialization code path
4942  * to issue config_port mailbox command. This function restarts the
4943  * HBA firmware and issues a config_port mailbox command to configure
4944  * the SLI interface in the sli mode specified by sli_mode
4945  * variable. The caller is not required to hold any locks.
4946  * The function returns 0 if successful, else returns negative error
4947  * code.
4948  **/
4949 int
4950 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
4951 {
4952 	LPFC_MBOXQ_t *pmb;
4953 	uint32_t resetcount = 0, rc = 0, done = 0;
4954 
4955 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4956 	if (!pmb) {
4957 		phba->link_state = LPFC_HBA_ERROR;
4958 		return -ENOMEM;
4959 	}
4960 
4961 	phba->sli_rev = sli_mode;
4962 	while (resetcount < 2 && !done) {
4963 		spin_lock_irq(&phba->hbalock);
4964 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
4965 		spin_unlock_irq(&phba->hbalock);
4966 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4967 		lpfc_sli_brdrestart(phba);
4968 		rc = lpfc_sli_chipset_init(phba);
4969 		if (rc)
4970 			break;
4971 
4972 		spin_lock_irq(&phba->hbalock);
4973 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4974 		spin_unlock_irq(&phba->hbalock);
4975 		resetcount++;
4976 
4977 		/* Call pre CONFIG_PORT mailbox command initialization.  A
4978 		 * value of 0 means the call was successful.  Any other
4979 		 * nonzero value is a failure, but if ERESTART is returned,
4980 		 * the driver may reset the HBA and try again.
4981 		 */
4982 		rc = lpfc_config_port_prep(phba);
4983 		if (rc == -ERESTART) {
4984 			phba->link_state = LPFC_LINK_UNKNOWN;
4985 			continue;
4986 		} else if (rc)
4987 			break;
4988 
4989 		phba->link_state = LPFC_INIT_MBX_CMDS;
4990 		lpfc_config_port(phba, pmb);
4991 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
4992 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
4993 					LPFC_SLI3_HBQ_ENABLED |
4994 					LPFC_SLI3_CRP_ENABLED |
4995 					LPFC_SLI3_DSS_ENABLED);
4996 		if (rc != MBX_SUCCESS) {
4997 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4998 				"0442 Adapter failed to init, mbxCmd x%x "
4999 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5000 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5001 			spin_lock_irq(&phba->hbalock);
5002 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5003 			spin_unlock_irq(&phba->hbalock);
5004 			rc = -ENXIO;
5005 		} else {
5006 			/* Allow asynchronous mailbox command to go through */
5007 			spin_lock_irq(&phba->hbalock);
5008 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5009 			spin_unlock_irq(&phba->hbalock);
5010 			done = 1;
5011 
5012 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5013 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5014 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5015 					"3110 Port did not grant ASABT\n");
5016 		}
5017 	}
5018 	if (!done) {
5019 		rc = -EINVAL;
5020 		goto do_prep_failed;
5021 	}
5022 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5023 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5024 			rc = -ENXIO;
5025 			goto do_prep_failed;
5026 		}
5027 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5028 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5029 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5030 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5031 				phba->max_vpi : phba->max_vports;
5032 
5033 		} else
5034 			phba->max_vpi = 0;
5035 		if (pmb->u.mb.un.varCfgPort.gerbm)
5036 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5037 		if (pmb->u.mb.un.varCfgPort.gcrp)
5038 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5039 
5040 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5041 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5042 
5043 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5044 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5045 				phba->cfg_enable_bg = 0;
5046 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5047 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5048 						"0443 Adapter did not grant "
5049 						"BlockGuard\n");
5050 			}
5051 		}
5052 	} else {
5053 		phba->hbq_get = NULL;
5054 		phba->port_gp = phba->mbox->us.s2.port;
5055 		phba->max_vpi = 0;
5056 	}
5057 do_prep_failed:
5058 	mempool_free(pmb, phba->mbox_mem_pool);
5059 	return rc;
5060 }
5061 
5062 
5063 /**
5064  * lpfc_sli_hba_setup - SLI initialization function
5065  * @phba: Pointer to HBA context object.
5066  *
5067  * This function is the main SLI initialization function. This function
5068  * is called by the HBA initialization code, HBA reset code and HBA
5069  * error attention handler code. Caller is not required to hold any
5070  * locks. This function issues config_port mailbox command to configure
5071  * the SLI, setup iocb rings and HBQ rings. In the end the function
5072  * calls the config_port_post function to issue init_link mailbox
5073  * command and to start the discovery. The function will return zero
5074  * if successful, else it will return negative error code.
5075  **/
5076 int
5077 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5078 {
5079 	uint32_t rc;
5080 	int  mode = 3, i;
5081 	int longs;
5082 
5083 	switch (phba->cfg_sli_mode) {
5084 	case 2:
5085 		if (phba->cfg_enable_npiv) {
5086 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
5087 				"1824 NPIV enabled: Override sli_mode "
5088 				"parameter (%d) to auto (0).\n",
5089 				phba->cfg_sli_mode);
5090 			break;
5091 		}
5092 		mode = 2;
5093 		break;
5094 	case 0:
5095 	case 3:
5096 		break;
5097 	default:
5098 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
5099 				"1819 Unrecognized sli_mode parameter: %d.\n",
5100 				phba->cfg_sli_mode);
5101 
5102 		break;
5103 	}
5104 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5105 
5106 	rc = lpfc_sli_config_port(phba, mode);
5107 
5108 	if (rc && phba->cfg_sli_mode == 3)
5109 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
5110 				"1820 Unable to select SLI-3.  "
5111 				"Not supported by adapter.\n");
5112 	if (rc && mode != 2)
5113 		rc = lpfc_sli_config_port(phba, 2);
5114 	else if (rc && mode == 2)
5115 		rc = lpfc_sli_config_port(phba, 3);
5116 	if (rc)
5117 		goto lpfc_sli_hba_setup_error;
5118 
5119 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
5120 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
5121 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
5122 		if (!rc) {
5123 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5124 					"2709 This device supports "
5125 					"Advanced Error Reporting (AER)\n");
5126 			spin_lock_irq(&phba->hbalock);
5127 			phba->hba_flag |= HBA_AER_ENABLED;
5128 			spin_unlock_irq(&phba->hbalock);
5129 		} else {
5130 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5131 					"2708 This device does not support "
5132 					"Advanced Error Reporting (AER): %d\n",
5133 					rc);
5134 			phba->cfg_aer_support = 0;
5135 		}
5136 	}
5137 
5138 	if (phba->sli_rev == 3) {
5139 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5140 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5141 	} else {
5142 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5143 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5144 		phba->sli3_options = 0;
5145 	}
5146 
5147 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5148 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5149 			phba->sli_rev, phba->max_vpi);
5150 	rc = lpfc_sli_ring_map(phba);
5151 
5152 	if (rc)
5153 		goto lpfc_sli_hba_setup_error;
5154 
5155 	/* Initialize VPIs. */
5156 	if (phba->sli_rev == LPFC_SLI_REV3) {
5157 		/*
5158 		 * The VPI bitmask and physical ID array are allocated
5159 		 * and initialized once only - at driver load.  A port
5160 		 * reset doesn't need to reinitialize this memory.
5161 		 */
5162 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5163 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5164 			phba->vpi_bmask = kcalloc(longs,
5165 						  sizeof(unsigned long),
5166 						  GFP_KERNEL);
5167 			if (!phba->vpi_bmask) {
5168 				rc = -ENOMEM;
5169 				goto lpfc_sli_hba_setup_error;
5170 			}
5171 
5172 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5173 						sizeof(uint16_t),
5174 						GFP_KERNEL);
5175 			if (!phba->vpi_ids) {
5176 				kfree(phba->vpi_bmask);
5177 				rc = -ENOMEM;
5178 				goto lpfc_sli_hba_setup_error;
5179 			}
5180 			for (i = 0; i < phba->max_vpi; i++)
5181 				phba->vpi_ids[i] = i;
5182 		}
5183 	}
5184 
5185 	/* Init HBQs */
5186 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5187 		rc = lpfc_sli_hbq_setup(phba);
5188 		if (rc)
5189 			goto lpfc_sli_hba_setup_error;
5190 	}
5191 	spin_lock_irq(&phba->hbalock);
5192 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5193 	spin_unlock_irq(&phba->hbalock);
5194 
5195 	rc = lpfc_config_port_post(phba);
5196 	if (rc)
5197 		goto lpfc_sli_hba_setup_error;
5198 
5199 	return rc;
5200 
5201 lpfc_sli_hba_setup_error:
5202 	phba->link_state = LPFC_HBA_ERROR;
5203 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5204 			"0445 Firmware initialization failed\n");
5205 	return rc;
5206 }
5207 
5208 /**
5209  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5210  * @phba: Pointer to HBA context object.
5211  * @mboxq: mailbox pointer.
5212  * This function issue a dump mailbox command to read config region
5213  * 23 and parse the records in the region and populate driver
5214  * data structure.
5215  **/
5216 static int
5217 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5218 {
5219 	LPFC_MBOXQ_t *mboxq;
5220 	struct lpfc_dmabuf *mp;
5221 	struct lpfc_mqe *mqe;
5222 	uint32_t data_length;
5223 	int rc;
5224 
5225 	/* Program the default value of vlan_id and fc_map */
5226 	phba->valid_vlan = 0;
5227 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5228 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5229 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5230 
5231 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5232 	if (!mboxq)
5233 		return -ENOMEM;
5234 
5235 	mqe = &mboxq->u.mqe;
5236 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5237 		rc = -ENOMEM;
5238 		goto out_free_mboxq;
5239 	}
5240 
5241 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5242 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5243 
5244 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5245 			"(%d):2571 Mailbox cmd x%x Status x%x "
5246 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5247 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5248 			"CQ: x%x x%x x%x x%x\n",
5249 			mboxq->vport ? mboxq->vport->vpi : 0,
5250 			bf_get(lpfc_mqe_command, mqe),
5251 			bf_get(lpfc_mqe_status, mqe),
5252 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5253 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5254 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5255 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5256 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5257 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5258 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5259 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5260 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5261 			mboxq->mcqe.word0,
5262 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5263 			mboxq->mcqe.trailer);
5264 
5265 	if (rc) {
5266 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5267 		kfree(mp);
5268 		rc = -EIO;
5269 		goto out_free_mboxq;
5270 	}
5271 	data_length = mqe->un.mb_words[5];
5272 	if (data_length > DMP_RGN23_SIZE) {
5273 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5274 		kfree(mp);
5275 		rc = -EIO;
5276 		goto out_free_mboxq;
5277 	}
5278 
5279 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5280 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
5281 	kfree(mp);
5282 	rc = 0;
5283 
5284 out_free_mboxq:
5285 	mempool_free(mboxq, phba->mbox_mem_pool);
5286 	return rc;
5287 }
5288 
5289 /**
5290  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5291  * @phba: pointer to lpfc hba data structure.
5292  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5293  * @vpd: pointer to the memory to hold resulting port vpd data.
5294  * @vpd_size: On input, the number of bytes allocated to @vpd.
5295  *	      On output, the number of data bytes in @vpd.
5296  *
5297  * This routine executes a READ_REV SLI4 mailbox command.  In
5298  * addition, this routine gets the port vpd data.
5299  *
5300  * Return codes
5301  * 	0 - successful
5302  * 	-ENOMEM - could not allocated memory.
5303  **/
5304 static int
5305 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5306 		    uint8_t *vpd, uint32_t *vpd_size)
5307 {
5308 	int rc = 0;
5309 	uint32_t dma_size;
5310 	struct lpfc_dmabuf *dmabuf;
5311 	struct lpfc_mqe *mqe;
5312 
5313 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5314 	if (!dmabuf)
5315 		return -ENOMEM;
5316 
5317 	/*
5318 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5319 	 * mailbox command.
5320 	 */
5321 	dma_size = *vpd_size;
5322 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5323 					  &dmabuf->phys, GFP_KERNEL);
5324 	if (!dmabuf->virt) {
5325 		kfree(dmabuf);
5326 		return -ENOMEM;
5327 	}
5328 
5329 	/*
5330 	 * The SLI4 implementation of READ_REV conflicts at word1,
5331 	 * bits 31:16 and SLI4 adds vpd functionality not present
5332 	 * in SLI3.  This code corrects the conflicts.
5333 	 */
5334 	lpfc_read_rev(phba, mboxq);
5335 	mqe = &mboxq->u.mqe;
5336 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5337 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5338 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5339 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5340 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5341 
5342 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5343 	if (rc) {
5344 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5345 				  dmabuf->virt, dmabuf->phys);
5346 		kfree(dmabuf);
5347 		return -EIO;
5348 	}
5349 
5350 	/*
5351 	 * The available vpd length cannot be bigger than the
5352 	 * DMA buffer passed to the port.  Catch the less than
5353 	 * case and update the caller's size.
5354 	 */
5355 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5356 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5357 
5358 	memcpy(vpd, dmabuf->virt, *vpd_size);
5359 
5360 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5361 			  dmabuf->virt, dmabuf->phys);
5362 	kfree(dmabuf);
5363 	return 0;
5364 }
5365 
5366 /**
5367  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5368  * @phba: pointer to lpfc hba data structure.
5369  *
5370  * This routine retrieves SLI4 device physical port name this PCI function
5371  * is attached to.
5372  *
5373  * Return codes
5374  *      0 - successful
5375  *      otherwise - failed to retrieve controller attributes
5376  **/
5377 static int
5378 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5379 {
5380 	LPFC_MBOXQ_t *mboxq;
5381 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5382 	struct lpfc_controller_attribute *cntl_attr;
5383 	void *virtaddr = NULL;
5384 	uint32_t alloclen, reqlen;
5385 	uint32_t shdr_status, shdr_add_status;
5386 	union lpfc_sli4_cfg_shdr *shdr;
5387 	int rc;
5388 
5389 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5390 	if (!mboxq)
5391 		return -ENOMEM;
5392 
5393 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5394 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5395 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5396 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5397 			LPFC_SLI4_MBX_NEMBED);
5398 
5399 	if (alloclen < reqlen) {
5400 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5401 				"3084 Allocated DMA memory size (%d) is "
5402 				"less than the requested DMA memory size "
5403 				"(%d)\n", alloclen, reqlen);
5404 		rc = -ENOMEM;
5405 		goto out_free_mboxq;
5406 	}
5407 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5408 	virtaddr = mboxq->sge_array->addr[0];
5409 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5410 	shdr = &mbx_cntl_attr->cfg_shdr;
5411 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5412 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5413 	if (shdr_status || shdr_add_status || rc) {
5414 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5415 				"3085 Mailbox x%x (x%x/x%x) failed, "
5416 				"rc:x%x, status:x%x, add_status:x%x\n",
5417 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5418 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5419 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5420 				rc, shdr_status, shdr_add_status);
5421 		rc = -ENXIO;
5422 		goto out_free_mboxq;
5423 	}
5424 
5425 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5426 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5427 	phba->sli4_hba.lnk_info.lnk_tp =
5428 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5429 	phba->sli4_hba.lnk_info.lnk_no =
5430 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5431 
5432 	memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
5433 	strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
5434 		sizeof(phba->BIOSVersion));
5435 
5436 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5437 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s\n",
5438 			phba->sli4_hba.lnk_info.lnk_tp,
5439 			phba->sli4_hba.lnk_info.lnk_no,
5440 			phba->BIOSVersion);
5441 out_free_mboxq:
5442 	if (rc != MBX_TIMEOUT) {
5443 		if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5444 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
5445 		else
5446 			mempool_free(mboxq, phba->mbox_mem_pool);
5447 	}
5448 	return rc;
5449 }
5450 
5451 /**
5452  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
5453  * @phba: pointer to lpfc hba data structure.
5454  *
5455  * This routine retrieves SLI4 device physical port name this PCI function
5456  * is attached to.
5457  *
5458  * Return codes
5459  *      0 - successful
5460  *      otherwise - failed to retrieve physical port name
5461  **/
5462 static int
5463 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
5464 {
5465 	LPFC_MBOXQ_t *mboxq;
5466 	struct lpfc_mbx_get_port_name *get_port_name;
5467 	uint32_t shdr_status, shdr_add_status;
5468 	union lpfc_sli4_cfg_shdr *shdr;
5469 	char cport_name = 0;
5470 	int rc;
5471 
5472 	/* We assume nothing at this point */
5473 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5474 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
5475 
5476 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5477 	if (!mboxq)
5478 		return -ENOMEM;
5479 	/* obtain link type and link number via READ_CONFIG */
5480 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5481 	lpfc_sli4_read_config(phba);
5482 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
5483 		goto retrieve_ppname;
5484 
5485 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
5486 	rc = lpfc_sli4_get_ctl_attr(phba);
5487 	if (rc)
5488 		goto out_free_mboxq;
5489 
5490 retrieve_ppname:
5491 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5492 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
5493 		sizeof(struct lpfc_mbx_get_port_name) -
5494 		sizeof(struct lpfc_sli4_cfg_mhdr),
5495 		LPFC_SLI4_MBX_EMBED);
5496 	get_port_name = &mboxq->u.mqe.un.get_port_name;
5497 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5498 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
5499 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
5500 		phba->sli4_hba.lnk_info.lnk_tp);
5501 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5502 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5503 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5504 	if (shdr_status || shdr_add_status || rc) {
5505 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5506 				"3087 Mailbox x%x (x%x/x%x) failed: "
5507 				"rc:x%x, status:x%x, add_status:x%x\n",
5508 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5509 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5510 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5511 				rc, shdr_status, shdr_add_status);
5512 		rc = -ENXIO;
5513 		goto out_free_mboxq;
5514 	}
5515 	switch (phba->sli4_hba.lnk_info.lnk_no) {
5516 	case LPFC_LINK_NUMBER_0:
5517 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
5518 				&get_port_name->u.response);
5519 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5520 		break;
5521 	case LPFC_LINK_NUMBER_1:
5522 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
5523 				&get_port_name->u.response);
5524 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5525 		break;
5526 	case LPFC_LINK_NUMBER_2:
5527 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
5528 				&get_port_name->u.response);
5529 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5530 		break;
5531 	case LPFC_LINK_NUMBER_3:
5532 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
5533 				&get_port_name->u.response);
5534 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5535 		break;
5536 	default:
5537 		break;
5538 	}
5539 
5540 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
5541 		phba->Port[0] = cport_name;
5542 		phba->Port[1] = '\0';
5543 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5544 				"3091 SLI get port name: %s\n", phba->Port);
5545 	}
5546 
5547 out_free_mboxq:
5548 	if (rc != MBX_TIMEOUT) {
5549 		if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5550 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
5551 		else
5552 			mempool_free(mboxq, phba->mbox_mem_pool);
5553 	}
5554 	return rc;
5555 }
5556 
5557 /**
5558  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
5559  * @phba: pointer to lpfc hba data structure.
5560  *
5561  * This routine is called to explicitly arm the SLI4 device's completion and
5562  * event queues
5563  **/
5564 static void
5565 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
5566 {
5567 	int qidx;
5568 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
5569 	struct lpfc_sli4_hdw_queue *qp;
5570 	struct lpfc_queue *eq;
5571 
5572 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
5573 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
5574 	if (sli4_hba->nvmels_cq)
5575 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
5576 					   LPFC_QUEUE_REARM);
5577 
5578 	if (sli4_hba->hdwq) {
5579 		/* Loop thru all Hardware Queues */
5580 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
5581 			qp = &sli4_hba->hdwq[qidx];
5582 			/* ARM the corresponding CQ */
5583 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
5584 						LPFC_QUEUE_REARM);
5585 		}
5586 
5587 		/* Loop thru all IRQ vectors */
5588 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
5589 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
5590 			/* ARM the corresponding EQ */
5591 			sli4_hba->sli4_write_eq_db(phba, eq,
5592 						   0, LPFC_QUEUE_REARM);
5593 		}
5594 	}
5595 
5596 	if (phba->nvmet_support) {
5597 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
5598 			sli4_hba->sli4_write_cq_db(phba,
5599 				sli4_hba->nvmet_cqset[qidx], 0,
5600 				LPFC_QUEUE_REARM);
5601 		}
5602 	}
5603 }
5604 
5605 /**
5606  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
5607  * @phba: Pointer to HBA context object.
5608  * @type: The resource extent type.
5609  * @extnt_count: buffer to hold port available extent count.
5610  * @extnt_size: buffer to hold element count per extent.
5611  *
5612  * This function calls the port and retrievs the number of available
5613  * extents and their size for a particular extent type.
5614  *
5615  * Returns: 0 if successful.  Nonzero otherwise.
5616  **/
5617 int
5618 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
5619 			       uint16_t *extnt_count, uint16_t *extnt_size)
5620 {
5621 	int rc = 0;
5622 	uint32_t length;
5623 	uint32_t mbox_tmo;
5624 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
5625 	LPFC_MBOXQ_t *mbox;
5626 
5627 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5628 	if (!mbox)
5629 		return -ENOMEM;
5630 
5631 	/* Find out how many extents are available for this resource type */
5632 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
5633 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5634 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5635 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
5636 			 length, LPFC_SLI4_MBX_EMBED);
5637 
5638 	/* Send an extents count of 0 - the GET doesn't use it. */
5639 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5640 					LPFC_SLI4_MBX_EMBED);
5641 	if (unlikely(rc)) {
5642 		rc = -EIO;
5643 		goto err_exit;
5644 	}
5645 
5646 	if (!phba->sli4_hba.intr_enable)
5647 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5648 	else {
5649 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5650 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5651 	}
5652 	if (unlikely(rc)) {
5653 		rc = -EIO;
5654 		goto err_exit;
5655 	}
5656 
5657 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
5658 	if (bf_get(lpfc_mbox_hdr_status,
5659 		   &rsrc_info->header.cfg_shdr.response)) {
5660 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5661 				"2930 Failed to get resource extents "
5662 				"Status 0x%x Add'l Status 0x%x\n",
5663 				bf_get(lpfc_mbox_hdr_status,
5664 				       &rsrc_info->header.cfg_shdr.response),
5665 				bf_get(lpfc_mbox_hdr_add_status,
5666 				       &rsrc_info->header.cfg_shdr.response));
5667 		rc = -EIO;
5668 		goto err_exit;
5669 	}
5670 
5671 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
5672 			      &rsrc_info->u.rsp);
5673 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
5674 			     &rsrc_info->u.rsp);
5675 
5676 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5677 			"3162 Retrieved extents type-%d from port: count:%d, "
5678 			"size:%d\n", type, *extnt_count, *extnt_size);
5679 
5680 err_exit:
5681 	mempool_free(mbox, phba->mbox_mem_pool);
5682 	return rc;
5683 }
5684 
5685 /**
5686  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
5687  * @phba: Pointer to HBA context object.
5688  * @type: The extent type to check.
5689  *
5690  * This function reads the current available extents from the port and checks
5691  * if the extent count or extent size has changed since the last access.
5692  * Callers use this routine post port reset to understand if there is a
5693  * extent reprovisioning requirement.
5694  *
5695  * Returns:
5696  *   -Error: error indicates problem.
5697  *   1: Extent count or size has changed.
5698  *   0: No changes.
5699  **/
5700 static int
5701 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
5702 {
5703 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
5704 	uint16_t size_diff, rsrc_ext_size;
5705 	int rc = 0;
5706 	struct lpfc_rsrc_blks *rsrc_entry;
5707 	struct list_head *rsrc_blk_list = NULL;
5708 
5709 	size_diff = 0;
5710 	curr_ext_cnt = 0;
5711 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5712 					    &rsrc_ext_cnt,
5713 					    &rsrc_ext_size);
5714 	if (unlikely(rc))
5715 		return -EIO;
5716 
5717 	switch (type) {
5718 	case LPFC_RSC_TYPE_FCOE_RPI:
5719 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5720 		break;
5721 	case LPFC_RSC_TYPE_FCOE_VPI:
5722 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
5723 		break;
5724 	case LPFC_RSC_TYPE_FCOE_XRI:
5725 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5726 		break;
5727 	case LPFC_RSC_TYPE_FCOE_VFI:
5728 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5729 		break;
5730 	default:
5731 		break;
5732 	}
5733 
5734 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
5735 		curr_ext_cnt++;
5736 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
5737 			size_diff++;
5738 	}
5739 
5740 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
5741 		rc = 1;
5742 
5743 	return rc;
5744 }
5745 
5746 /**
5747  * lpfc_sli4_cfg_post_extnts -
5748  * @phba: Pointer to HBA context object.
5749  * @extnt_cnt - number of available extents.
5750  * @type - the extent type (rpi, xri, vfi, vpi).
5751  * @emb - buffer to hold either MBX_EMBED or MBX_NEMBED operation.
5752  * @mbox - pointer to the caller's allocated mailbox structure.
5753  *
5754  * This function executes the extents allocation request.  It also
5755  * takes care of the amount of memory needed to allocate or get the
5756  * allocated extents. It is the caller's responsibility to evaluate
5757  * the response.
5758  *
5759  * Returns:
5760  *   -Error:  Error value describes the condition found.
5761  *   0: if successful
5762  **/
5763 static int
5764 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
5765 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
5766 {
5767 	int rc = 0;
5768 	uint32_t req_len;
5769 	uint32_t emb_len;
5770 	uint32_t alloc_len, mbox_tmo;
5771 
5772 	/* Calculate the total requested length of the dma memory */
5773 	req_len = extnt_cnt * sizeof(uint16_t);
5774 
5775 	/*
5776 	 * Calculate the size of an embedded mailbox.  The uint32_t
5777 	 * accounts for extents-specific word.
5778 	 */
5779 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
5780 		sizeof(uint32_t);
5781 
5782 	/*
5783 	 * Presume the allocation and response will fit into an embedded
5784 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
5785 	 */
5786 	*emb = LPFC_SLI4_MBX_EMBED;
5787 	if (req_len > emb_len) {
5788 		req_len = extnt_cnt * sizeof(uint16_t) +
5789 			sizeof(union lpfc_sli4_cfg_shdr) +
5790 			sizeof(uint32_t);
5791 		*emb = LPFC_SLI4_MBX_NEMBED;
5792 	}
5793 
5794 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5795 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
5796 				     req_len, *emb);
5797 	if (alloc_len < req_len) {
5798 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5799 			"2982 Allocated DMA memory size (x%x) is "
5800 			"less than the requested DMA memory "
5801 			"size (x%x)\n", alloc_len, req_len);
5802 		return -ENOMEM;
5803 	}
5804 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
5805 	if (unlikely(rc))
5806 		return -EIO;
5807 
5808 	if (!phba->sli4_hba.intr_enable)
5809 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5810 	else {
5811 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5812 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5813 	}
5814 
5815 	if (unlikely(rc))
5816 		rc = -EIO;
5817 	return rc;
5818 }
5819 
5820 /**
5821  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
5822  * @phba: Pointer to HBA context object.
5823  * @type:  The resource extent type to allocate.
5824  *
5825  * This function allocates the number of elements for the specified
5826  * resource type.
5827  **/
5828 static int
5829 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
5830 {
5831 	bool emb = false;
5832 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
5833 	uint16_t rsrc_id, rsrc_start, j, k;
5834 	uint16_t *ids;
5835 	int i, rc;
5836 	unsigned long longs;
5837 	unsigned long *bmask;
5838 	struct lpfc_rsrc_blks *rsrc_blks;
5839 	LPFC_MBOXQ_t *mbox;
5840 	uint32_t length;
5841 	struct lpfc_id_range *id_array = NULL;
5842 	void *virtaddr = NULL;
5843 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
5844 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
5845 	struct list_head *ext_blk_list;
5846 
5847 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5848 					    &rsrc_cnt,
5849 					    &rsrc_size);
5850 	if (unlikely(rc))
5851 		return -EIO;
5852 
5853 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
5854 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5855 			"3009 No available Resource Extents "
5856 			"for resource type 0x%x: Count: 0x%x, "
5857 			"Size 0x%x\n", type, rsrc_cnt,
5858 			rsrc_size);
5859 		return -ENOMEM;
5860 	}
5861 
5862 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
5863 			"2903 Post resource extents type-0x%x: "
5864 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
5865 
5866 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5867 	if (!mbox)
5868 		return -ENOMEM;
5869 
5870 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
5871 	if (unlikely(rc)) {
5872 		rc = -EIO;
5873 		goto err_exit;
5874 	}
5875 
5876 	/*
5877 	 * Figure out where the response is located.  Then get local pointers
5878 	 * to the response data.  The port does not guarantee to respond to
5879 	 * all extents counts request so update the local variable with the
5880 	 * allocated count from the port.
5881 	 */
5882 	if (emb == LPFC_SLI4_MBX_EMBED) {
5883 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
5884 		id_array = &rsrc_ext->u.rsp.id[0];
5885 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
5886 	} else {
5887 		virtaddr = mbox->sge_array->addr[0];
5888 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
5889 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
5890 		id_array = &n_rsrc->id;
5891 	}
5892 
5893 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
5894 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
5895 
5896 	/*
5897 	 * Based on the resource size and count, correct the base and max
5898 	 * resource values.
5899 	 */
5900 	length = sizeof(struct lpfc_rsrc_blks);
5901 	switch (type) {
5902 	case LPFC_RSC_TYPE_FCOE_RPI:
5903 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
5904 						   sizeof(unsigned long),
5905 						   GFP_KERNEL);
5906 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
5907 			rc = -ENOMEM;
5908 			goto err_exit;
5909 		}
5910 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
5911 						 sizeof(uint16_t),
5912 						 GFP_KERNEL);
5913 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
5914 			kfree(phba->sli4_hba.rpi_bmask);
5915 			rc = -ENOMEM;
5916 			goto err_exit;
5917 		}
5918 
5919 		/*
5920 		 * The next_rpi was initialized with the maximum available
5921 		 * count but the port may allocate a smaller number.  Catch
5922 		 * that case and update the next_rpi.
5923 		 */
5924 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
5925 
5926 		/* Initialize local ptrs for common extent processing later. */
5927 		bmask = phba->sli4_hba.rpi_bmask;
5928 		ids = phba->sli4_hba.rpi_ids;
5929 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5930 		break;
5931 	case LPFC_RSC_TYPE_FCOE_VPI:
5932 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
5933 					  GFP_KERNEL);
5934 		if (unlikely(!phba->vpi_bmask)) {
5935 			rc = -ENOMEM;
5936 			goto err_exit;
5937 		}
5938 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
5939 					 GFP_KERNEL);
5940 		if (unlikely(!phba->vpi_ids)) {
5941 			kfree(phba->vpi_bmask);
5942 			rc = -ENOMEM;
5943 			goto err_exit;
5944 		}
5945 
5946 		/* Initialize local ptrs for common extent processing later. */
5947 		bmask = phba->vpi_bmask;
5948 		ids = phba->vpi_ids;
5949 		ext_blk_list = &phba->lpfc_vpi_blk_list;
5950 		break;
5951 	case LPFC_RSC_TYPE_FCOE_XRI:
5952 		phba->sli4_hba.xri_bmask = kcalloc(longs,
5953 						   sizeof(unsigned long),
5954 						   GFP_KERNEL);
5955 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
5956 			rc = -ENOMEM;
5957 			goto err_exit;
5958 		}
5959 		phba->sli4_hba.max_cfg_param.xri_used = 0;
5960 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
5961 						 sizeof(uint16_t),
5962 						 GFP_KERNEL);
5963 		if (unlikely(!phba->sli4_hba.xri_ids)) {
5964 			kfree(phba->sli4_hba.xri_bmask);
5965 			rc = -ENOMEM;
5966 			goto err_exit;
5967 		}
5968 
5969 		/* Initialize local ptrs for common extent processing later. */
5970 		bmask = phba->sli4_hba.xri_bmask;
5971 		ids = phba->sli4_hba.xri_ids;
5972 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5973 		break;
5974 	case LPFC_RSC_TYPE_FCOE_VFI:
5975 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
5976 						   sizeof(unsigned long),
5977 						   GFP_KERNEL);
5978 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
5979 			rc = -ENOMEM;
5980 			goto err_exit;
5981 		}
5982 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
5983 						 sizeof(uint16_t),
5984 						 GFP_KERNEL);
5985 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
5986 			kfree(phba->sli4_hba.vfi_bmask);
5987 			rc = -ENOMEM;
5988 			goto err_exit;
5989 		}
5990 
5991 		/* Initialize local ptrs for common extent processing later. */
5992 		bmask = phba->sli4_hba.vfi_bmask;
5993 		ids = phba->sli4_hba.vfi_ids;
5994 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5995 		break;
5996 	default:
5997 		/* Unsupported Opcode.  Fail call. */
5998 		id_array = NULL;
5999 		bmask = NULL;
6000 		ids = NULL;
6001 		ext_blk_list = NULL;
6002 		goto err_exit;
6003 	}
6004 
6005 	/*
6006 	 * Complete initializing the extent configuration with the
6007 	 * allocated ids assigned to this function.  The bitmask serves
6008 	 * as an index into the array and manages the available ids.  The
6009 	 * array just stores the ids communicated to the port via the wqes.
6010 	 */
6011 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6012 		if ((i % 2) == 0)
6013 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6014 					 &id_array[k]);
6015 		else
6016 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6017 					 &id_array[k]);
6018 
6019 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6020 		if (unlikely(!rsrc_blks)) {
6021 			rc = -ENOMEM;
6022 			kfree(bmask);
6023 			kfree(ids);
6024 			goto err_exit;
6025 		}
6026 		rsrc_blks->rsrc_start = rsrc_id;
6027 		rsrc_blks->rsrc_size = rsrc_size;
6028 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6029 		rsrc_start = rsrc_id;
6030 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6031 			phba->sli4_hba.io_xri_start = rsrc_start +
6032 				lpfc_sli4_get_iocb_cnt(phba);
6033 		}
6034 
6035 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6036 			ids[j] = rsrc_id;
6037 			rsrc_id++;
6038 			j++;
6039 		}
6040 		/* Entire word processed.  Get next word.*/
6041 		if ((i % 2) == 1)
6042 			k++;
6043 	}
6044  err_exit:
6045 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6046 	return rc;
6047 }
6048 
6049 
6050 
6051 /**
6052  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6053  * @phba: Pointer to HBA context object.
6054  * @type: the extent's type.
6055  *
6056  * This function deallocates all extents of a particular resource type.
6057  * SLI4 does not allow for deallocating a particular extent range.  It
6058  * is the caller's responsibility to release all kernel memory resources.
6059  **/
6060 static int
6061 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6062 {
6063 	int rc;
6064 	uint32_t length, mbox_tmo = 0;
6065 	LPFC_MBOXQ_t *mbox;
6066 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6067 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6068 
6069 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6070 	if (!mbox)
6071 		return -ENOMEM;
6072 
6073 	/*
6074 	 * This function sends an embedded mailbox because it only sends the
6075 	 * the resource type.  All extents of this type are released by the
6076 	 * port.
6077 	 */
6078 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6079 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6080 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6081 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6082 			 length, LPFC_SLI4_MBX_EMBED);
6083 
6084 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6085 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6086 					LPFC_SLI4_MBX_EMBED);
6087 	if (unlikely(rc)) {
6088 		rc = -EIO;
6089 		goto out_free_mbox;
6090 	}
6091 	if (!phba->sli4_hba.intr_enable)
6092 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6093 	else {
6094 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6095 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6096 	}
6097 	if (unlikely(rc)) {
6098 		rc = -EIO;
6099 		goto out_free_mbox;
6100 	}
6101 
6102 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6103 	if (bf_get(lpfc_mbox_hdr_status,
6104 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6105 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
6106 				"2919 Failed to release resource extents "
6107 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6108 				"Resource memory not released.\n",
6109 				type,
6110 				bf_get(lpfc_mbox_hdr_status,
6111 				    &dealloc_rsrc->header.cfg_shdr.response),
6112 				bf_get(lpfc_mbox_hdr_add_status,
6113 				    &dealloc_rsrc->header.cfg_shdr.response));
6114 		rc = -EIO;
6115 		goto out_free_mbox;
6116 	}
6117 
6118 	/* Release kernel memory resources for the specific type. */
6119 	switch (type) {
6120 	case LPFC_RSC_TYPE_FCOE_VPI:
6121 		kfree(phba->vpi_bmask);
6122 		kfree(phba->vpi_ids);
6123 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6124 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6125 				    &phba->lpfc_vpi_blk_list, list) {
6126 			list_del_init(&rsrc_blk->list);
6127 			kfree(rsrc_blk);
6128 		}
6129 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6130 		break;
6131 	case LPFC_RSC_TYPE_FCOE_XRI:
6132 		kfree(phba->sli4_hba.xri_bmask);
6133 		kfree(phba->sli4_hba.xri_ids);
6134 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6135 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6136 			list_del_init(&rsrc_blk->list);
6137 			kfree(rsrc_blk);
6138 		}
6139 		break;
6140 	case LPFC_RSC_TYPE_FCOE_VFI:
6141 		kfree(phba->sli4_hba.vfi_bmask);
6142 		kfree(phba->sli4_hba.vfi_ids);
6143 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6144 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6145 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6146 			list_del_init(&rsrc_blk->list);
6147 			kfree(rsrc_blk);
6148 		}
6149 		break;
6150 	case LPFC_RSC_TYPE_FCOE_RPI:
6151 		/* RPI bitmask and physical id array are cleaned up earlier. */
6152 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6153 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6154 			list_del_init(&rsrc_blk->list);
6155 			kfree(rsrc_blk);
6156 		}
6157 		break;
6158 	default:
6159 		break;
6160 	}
6161 
6162 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6163 
6164  out_free_mbox:
6165 	mempool_free(mbox, phba->mbox_mem_pool);
6166 	return rc;
6167 }
6168 
6169 static void
6170 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6171 		  uint32_t feature)
6172 {
6173 	uint32_t len;
6174 
6175 	len = sizeof(struct lpfc_mbx_set_feature) -
6176 		sizeof(struct lpfc_sli4_cfg_mhdr);
6177 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6178 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6179 			 LPFC_SLI4_MBX_EMBED);
6180 
6181 	switch (feature) {
6182 	case LPFC_SET_UE_RECOVERY:
6183 		bf_set(lpfc_mbx_set_feature_UER,
6184 		       &mbox->u.mqe.un.set_feature, 1);
6185 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6186 		mbox->u.mqe.un.set_feature.param_len = 8;
6187 		break;
6188 	case LPFC_SET_MDS_DIAGS:
6189 		bf_set(lpfc_mbx_set_feature_mds,
6190 		       &mbox->u.mqe.un.set_feature, 1);
6191 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6192 		       &mbox->u.mqe.un.set_feature, 1);
6193 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6194 		mbox->u.mqe.un.set_feature.param_len = 8;
6195 		break;
6196 	case LPFC_SET_DUAL_DUMP:
6197 		bf_set(lpfc_mbx_set_feature_dd,
6198 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6199 		bf_set(lpfc_mbx_set_feature_ddquery,
6200 		       &mbox->u.mqe.un.set_feature, 0);
6201 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6202 		mbox->u.mqe.un.set_feature.param_len = 4;
6203 		break;
6204 	}
6205 
6206 	return;
6207 }
6208 
6209 /**
6210  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6211  * @phba: Pointer to HBA context object.
6212  *
6213  * Disable FW logging into host memory on the adapter. To
6214  * be done before reading logs from the host memory.
6215  **/
6216 void
6217 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6218 {
6219 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6220 
6221 	spin_lock_irq(&phba->hbalock);
6222 	ras_fwlog->state = INACTIVE;
6223 	spin_unlock_irq(&phba->hbalock);
6224 
6225 	/* Disable FW logging to host memory */
6226 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6227 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6228 
6229 	/* Wait 10ms for firmware to stop using DMA buffer */
6230 	usleep_range(10 * 1000, 20 * 1000);
6231 }
6232 
6233 /**
6234  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6235  * @phba: Pointer to HBA context object.
6236  *
6237  * This function is called to free memory allocated for RAS FW logging
6238  * support in the driver.
6239  **/
6240 void
6241 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6242 {
6243 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6244 	struct lpfc_dmabuf *dmabuf, *next;
6245 
6246 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6247 		list_for_each_entry_safe(dmabuf, next,
6248 				    &ras_fwlog->fwlog_buff_list,
6249 				    list) {
6250 			list_del(&dmabuf->list);
6251 			dma_free_coherent(&phba->pcidev->dev,
6252 					  LPFC_RAS_MAX_ENTRY_SIZE,
6253 					  dmabuf->virt, dmabuf->phys);
6254 			kfree(dmabuf);
6255 		}
6256 	}
6257 
6258 	if (ras_fwlog->lwpd.virt) {
6259 		dma_free_coherent(&phba->pcidev->dev,
6260 				  sizeof(uint32_t) * 2,
6261 				  ras_fwlog->lwpd.virt,
6262 				  ras_fwlog->lwpd.phys);
6263 		ras_fwlog->lwpd.virt = NULL;
6264 	}
6265 
6266 	spin_lock_irq(&phba->hbalock);
6267 	ras_fwlog->state = INACTIVE;
6268 	spin_unlock_irq(&phba->hbalock);
6269 }
6270 
6271 /**
6272  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6273  * @phba: Pointer to HBA context object.
6274  * @fwlog_buff_count: Count of buffers to be created.
6275  *
6276  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6277  * to update FW log is posted to the adapter.
6278  * Buffer count is calculated based on module param ras_fwlog_buffsize
6279  * Size of each buffer posted to FW is 64K.
6280  **/
6281 
6282 static int
6283 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6284 			uint32_t fwlog_buff_count)
6285 {
6286 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6287 	struct lpfc_dmabuf *dmabuf;
6288 	int rc = 0, i = 0;
6289 
6290 	/* Initialize List */
6291 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6292 
6293 	/* Allocate memory for the LWPD */
6294 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6295 					    sizeof(uint32_t) * 2,
6296 					    &ras_fwlog->lwpd.phys,
6297 					    GFP_KERNEL);
6298 	if (!ras_fwlog->lwpd.virt) {
6299 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6300 				"6185 LWPD Memory Alloc Failed\n");
6301 
6302 		return -ENOMEM;
6303 	}
6304 
6305 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6306 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6307 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6308 				 GFP_KERNEL);
6309 		if (!dmabuf) {
6310 			rc = -ENOMEM;
6311 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6312 					"6186 Memory Alloc failed FW logging");
6313 			goto free_mem;
6314 		}
6315 
6316 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6317 						  LPFC_RAS_MAX_ENTRY_SIZE,
6318 						  &dmabuf->phys, GFP_KERNEL);
6319 		if (!dmabuf->virt) {
6320 			kfree(dmabuf);
6321 			rc = -ENOMEM;
6322 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6323 					"6187 DMA Alloc Failed FW logging");
6324 			goto free_mem;
6325 		}
6326 		dmabuf->buffer_tag = i;
6327 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6328 	}
6329 
6330 free_mem:
6331 	if (rc)
6332 		lpfc_sli4_ras_dma_free(phba);
6333 
6334 	return rc;
6335 }
6336 
6337 /**
6338  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6339  * @phba: pointer to lpfc hba data structure.
6340  * @pmboxq: pointer to the driver internal queue element for mailbox command.
6341  *
6342  * Completion handler for driver's RAS MBX command to the device.
6343  **/
6344 static void
6345 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6346 {
6347 	MAILBOX_t *mb;
6348 	union lpfc_sli4_cfg_shdr *shdr;
6349 	uint32_t shdr_status, shdr_add_status;
6350 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6351 
6352 	mb = &pmb->u.mb;
6353 
6354 	shdr = (union lpfc_sli4_cfg_shdr *)
6355 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6356 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6357 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6358 
6359 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6360 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
6361 				"6188 FW LOG mailbox "
6362 				"completed with status x%x add_status x%x,"
6363 				" mbx status x%x\n",
6364 				shdr_status, shdr_add_status, mb->mbxStatus);
6365 
6366 		ras_fwlog->ras_hwsupport = false;
6367 		goto disable_ras;
6368 	}
6369 
6370 	spin_lock_irq(&phba->hbalock);
6371 	ras_fwlog->state = ACTIVE;
6372 	spin_unlock_irq(&phba->hbalock);
6373 	mempool_free(pmb, phba->mbox_mem_pool);
6374 
6375 	return;
6376 
6377 disable_ras:
6378 	/* Free RAS DMA memory */
6379 	lpfc_sli4_ras_dma_free(phba);
6380 	mempool_free(pmb, phba->mbox_mem_pool);
6381 }
6382 
6383 /**
6384  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
6385  * @phba: pointer to lpfc hba data structure.
6386  * @fwlog_level: Logging verbosity level.
6387  * @fwlog_enable: Enable/Disable logging.
6388  *
6389  * Initialize memory and post mailbox command to enable FW logging in host
6390  * memory.
6391  **/
6392 int
6393 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
6394 			 uint32_t fwlog_level,
6395 			 uint32_t fwlog_enable)
6396 {
6397 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6398 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
6399 	struct lpfc_dmabuf *dmabuf;
6400 	LPFC_MBOXQ_t *mbox;
6401 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
6402 	int rc = 0;
6403 
6404 	spin_lock_irq(&phba->hbalock);
6405 	ras_fwlog->state = INACTIVE;
6406 	spin_unlock_irq(&phba->hbalock);
6407 
6408 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
6409 			  phba->cfg_ras_fwlog_buffsize);
6410 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
6411 
6412 	/*
6413 	 * If re-enabling FW logging support use earlier allocated
6414 	 * DMA buffers while posting MBX command.
6415 	 **/
6416 	if (!ras_fwlog->lwpd.virt) {
6417 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
6418 		if (rc) {
6419 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6420 					"6189 FW Log Memory Allocation Failed");
6421 			return rc;
6422 		}
6423 	}
6424 
6425 	/* Setup Mailbox command */
6426 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6427 	if (!mbox) {
6428 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6429 				"6190 RAS MBX Alloc Failed");
6430 		rc = -ENOMEM;
6431 		goto mem_free;
6432 	}
6433 
6434 	ras_fwlog->fw_loglevel = fwlog_level;
6435 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
6436 		sizeof(struct lpfc_sli4_cfg_mhdr));
6437 
6438 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
6439 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
6440 			 len, LPFC_SLI4_MBX_EMBED);
6441 
6442 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
6443 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
6444 	       fwlog_enable);
6445 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
6446 	       ras_fwlog->fw_loglevel);
6447 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
6448 	       ras_fwlog->fw_buffcount);
6449 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
6450 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
6451 
6452 	/* Update DMA buffer address */
6453 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
6454 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
6455 
6456 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
6457 			putPaddrLow(dmabuf->phys);
6458 
6459 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
6460 			putPaddrHigh(dmabuf->phys);
6461 	}
6462 
6463 	/* Update LPWD address */
6464 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
6465 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
6466 
6467 	spin_lock_irq(&phba->hbalock);
6468 	ras_fwlog->state = REG_INPROGRESS;
6469 	spin_unlock_irq(&phba->hbalock);
6470 	mbox->vport = phba->pport;
6471 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
6472 
6473 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
6474 
6475 	if (rc == MBX_NOT_FINISHED) {
6476 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6477 				"6191 FW-Log Mailbox failed. "
6478 				"status %d mbxStatus : x%x", rc,
6479 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
6480 		mempool_free(mbox, phba->mbox_mem_pool);
6481 		rc = -EIO;
6482 		goto mem_free;
6483 	} else
6484 		rc = 0;
6485 mem_free:
6486 	if (rc)
6487 		lpfc_sli4_ras_dma_free(phba);
6488 
6489 	return rc;
6490 }
6491 
6492 /**
6493  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
6494  * @phba: Pointer to HBA context object.
6495  *
6496  * Check if RAS is supported on the adapter and initialize it.
6497  **/
6498 void
6499 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
6500 {
6501 	/* Check RAS FW Log needs to be enabled or not */
6502 	if (lpfc_check_fwlog_support(phba))
6503 		return;
6504 
6505 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
6506 				 LPFC_RAS_ENABLE_LOGGING);
6507 }
6508 
6509 /**
6510  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
6511  * @phba: Pointer to HBA context object.
6512  *
6513  * This function allocates all SLI4 resource identifiers.
6514  **/
6515 int
6516 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
6517 {
6518 	int i, rc, error = 0;
6519 	uint16_t count, base;
6520 	unsigned long longs;
6521 
6522 	if (!phba->sli4_hba.rpi_hdrs_in_use)
6523 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
6524 	if (phba->sli4_hba.extents_in_use) {
6525 		/*
6526 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
6527 		 * resource extent count must be read and allocated before
6528 		 * provisioning the resource id arrays.
6529 		 */
6530 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6531 		    LPFC_IDX_RSRC_RDY) {
6532 			/*
6533 			 * Extent-based resources are set - the driver could
6534 			 * be in a port reset. Figure out if any corrective
6535 			 * actions need to be taken.
6536 			 */
6537 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6538 						 LPFC_RSC_TYPE_FCOE_VFI);
6539 			if (rc != 0)
6540 				error++;
6541 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6542 						 LPFC_RSC_TYPE_FCOE_VPI);
6543 			if (rc != 0)
6544 				error++;
6545 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6546 						 LPFC_RSC_TYPE_FCOE_XRI);
6547 			if (rc != 0)
6548 				error++;
6549 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6550 						 LPFC_RSC_TYPE_FCOE_RPI);
6551 			if (rc != 0)
6552 				error++;
6553 
6554 			/*
6555 			 * It's possible that the number of resources
6556 			 * provided to this port instance changed between
6557 			 * resets.  Detect this condition and reallocate
6558 			 * resources.  Otherwise, there is no action.
6559 			 */
6560 			if (error) {
6561 				lpfc_printf_log(phba, KERN_INFO,
6562 						LOG_MBOX | LOG_INIT,
6563 						"2931 Detected extent resource "
6564 						"change.  Reallocating all "
6565 						"extents.\n");
6566 				rc = lpfc_sli4_dealloc_extent(phba,
6567 						 LPFC_RSC_TYPE_FCOE_VFI);
6568 				rc = lpfc_sli4_dealloc_extent(phba,
6569 						 LPFC_RSC_TYPE_FCOE_VPI);
6570 				rc = lpfc_sli4_dealloc_extent(phba,
6571 						 LPFC_RSC_TYPE_FCOE_XRI);
6572 				rc = lpfc_sli4_dealloc_extent(phba,
6573 						 LPFC_RSC_TYPE_FCOE_RPI);
6574 			} else
6575 				return 0;
6576 		}
6577 
6578 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6579 		if (unlikely(rc))
6580 			goto err_exit;
6581 
6582 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6583 		if (unlikely(rc))
6584 			goto err_exit;
6585 
6586 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6587 		if (unlikely(rc))
6588 			goto err_exit;
6589 
6590 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6591 		if (unlikely(rc))
6592 			goto err_exit;
6593 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6594 		       LPFC_IDX_RSRC_RDY);
6595 		return rc;
6596 	} else {
6597 		/*
6598 		 * The port does not support resource extents.  The XRI, VPI,
6599 		 * VFI, RPI resource ids were determined from READ_CONFIG.
6600 		 * Just allocate the bitmasks and provision the resource id
6601 		 * arrays.  If a port reset is active, the resources don't
6602 		 * need any action - just exit.
6603 		 */
6604 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6605 		    LPFC_IDX_RSRC_RDY) {
6606 			lpfc_sli4_dealloc_resource_identifiers(phba);
6607 			lpfc_sli4_remove_rpis(phba);
6608 		}
6609 		/* RPIs. */
6610 		count = phba->sli4_hba.max_cfg_param.max_rpi;
6611 		if (count <= 0) {
6612 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6613 					"3279 Invalid provisioning of "
6614 					"rpi:%d\n", count);
6615 			rc = -EINVAL;
6616 			goto err_exit;
6617 		}
6618 		base = phba->sli4_hba.max_cfg_param.rpi_base;
6619 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6620 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6621 						   sizeof(unsigned long),
6622 						   GFP_KERNEL);
6623 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6624 			rc = -ENOMEM;
6625 			goto err_exit;
6626 		}
6627 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
6628 						 GFP_KERNEL);
6629 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6630 			rc = -ENOMEM;
6631 			goto free_rpi_bmask;
6632 		}
6633 
6634 		for (i = 0; i < count; i++)
6635 			phba->sli4_hba.rpi_ids[i] = base + i;
6636 
6637 		/* VPIs. */
6638 		count = phba->sli4_hba.max_cfg_param.max_vpi;
6639 		if (count <= 0) {
6640 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6641 					"3280 Invalid provisioning of "
6642 					"vpi:%d\n", count);
6643 			rc = -EINVAL;
6644 			goto free_rpi_ids;
6645 		}
6646 		base = phba->sli4_hba.max_cfg_param.vpi_base;
6647 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6648 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6649 					  GFP_KERNEL);
6650 		if (unlikely(!phba->vpi_bmask)) {
6651 			rc = -ENOMEM;
6652 			goto free_rpi_ids;
6653 		}
6654 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
6655 					GFP_KERNEL);
6656 		if (unlikely(!phba->vpi_ids)) {
6657 			rc = -ENOMEM;
6658 			goto free_vpi_bmask;
6659 		}
6660 
6661 		for (i = 0; i < count; i++)
6662 			phba->vpi_ids[i] = base + i;
6663 
6664 		/* XRIs. */
6665 		count = phba->sli4_hba.max_cfg_param.max_xri;
6666 		if (count <= 0) {
6667 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6668 					"3281 Invalid provisioning of "
6669 					"xri:%d\n", count);
6670 			rc = -EINVAL;
6671 			goto free_vpi_ids;
6672 		}
6673 		base = phba->sli4_hba.max_cfg_param.xri_base;
6674 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6675 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6676 						   sizeof(unsigned long),
6677 						   GFP_KERNEL);
6678 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6679 			rc = -ENOMEM;
6680 			goto free_vpi_ids;
6681 		}
6682 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6683 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
6684 						 GFP_KERNEL);
6685 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6686 			rc = -ENOMEM;
6687 			goto free_xri_bmask;
6688 		}
6689 
6690 		for (i = 0; i < count; i++)
6691 			phba->sli4_hba.xri_ids[i] = base + i;
6692 
6693 		/* VFIs. */
6694 		count = phba->sli4_hba.max_cfg_param.max_vfi;
6695 		if (count <= 0) {
6696 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6697 					"3282 Invalid provisioning of "
6698 					"vfi:%d\n", count);
6699 			rc = -EINVAL;
6700 			goto free_xri_ids;
6701 		}
6702 		base = phba->sli4_hba.max_cfg_param.vfi_base;
6703 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6704 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6705 						   sizeof(unsigned long),
6706 						   GFP_KERNEL);
6707 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6708 			rc = -ENOMEM;
6709 			goto free_xri_ids;
6710 		}
6711 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
6712 						 GFP_KERNEL);
6713 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6714 			rc = -ENOMEM;
6715 			goto free_vfi_bmask;
6716 		}
6717 
6718 		for (i = 0; i < count; i++)
6719 			phba->sli4_hba.vfi_ids[i] = base + i;
6720 
6721 		/*
6722 		 * Mark all resources ready.  An HBA reset doesn't need
6723 		 * to reset the initialization.
6724 		 */
6725 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6726 		       LPFC_IDX_RSRC_RDY);
6727 		return 0;
6728 	}
6729 
6730  free_vfi_bmask:
6731 	kfree(phba->sli4_hba.vfi_bmask);
6732 	phba->sli4_hba.vfi_bmask = NULL;
6733  free_xri_ids:
6734 	kfree(phba->sli4_hba.xri_ids);
6735 	phba->sli4_hba.xri_ids = NULL;
6736  free_xri_bmask:
6737 	kfree(phba->sli4_hba.xri_bmask);
6738 	phba->sli4_hba.xri_bmask = NULL;
6739  free_vpi_ids:
6740 	kfree(phba->vpi_ids);
6741 	phba->vpi_ids = NULL;
6742  free_vpi_bmask:
6743 	kfree(phba->vpi_bmask);
6744 	phba->vpi_bmask = NULL;
6745  free_rpi_ids:
6746 	kfree(phba->sli4_hba.rpi_ids);
6747 	phba->sli4_hba.rpi_ids = NULL;
6748  free_rpi_bmask:
6749 	kfree(phba->sli4_hba.rpi_bmask);
6750 	phba->sli4_hba.rpi_bmask = NULL;
6751  err_exit:
6752 	return rc;
6753 }
6754 
6755 /**
6756  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
6757  * @phba: Pointer to HBA context object.
6758  *
6759  * This function allocates the number of elements for the specified
6760  * resource type.
6761  **/
6762 int
6763 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
6764 {
6765 	if (phba->sli4_hba.extents_in_use) {
6766 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6767 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6768 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6769 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6770 	} else {
6771 		kfree(phba->vpi_bmask);
6772 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6773 		kfree(phba->vpi_ids);
6774 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6775 		kfree(phba->sli4_hba.xri_bmask);
6776 		kfree(phba->sli4_hba.xri_ids);
6777 		kfree(phba->sli4_hba.vfi_bmask);
6778 		kfree(phba->sli4_hba.vfi_ids);
6779 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6780 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6781 	}
6782 
6783 	return 0;
6784 }
6785 
6786 /**
6787  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
6788  * @phba: Pointer to HBA context object.
6789  * @type: The resource extent type.
6790  * @extnt_count: buffer to hold port extent count response
6791  * @extnt_size: buffer to hold port extent size response.
6792  *
6793  * This function calls the port to read the host allocated extents
6794  * for a particular type.
6795  **/
6796 int
6797 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
6798 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
6799 {
6800 	bool emb;
6801 	int rc = 0;
6802 	uint16_t curr_blks = 0;
6803 	uint32_t req_len, emb_len;
6804 	uint32_t alloc_len, mbox_tmo;
6805 	struct list_head *blk_list_head;
6806 	struct lpfc_rsrc_blks *rsrc_blk;
6807 	LPFC_MBOXQ_t *mbox;
6808 	void *virtaddr = NULL;
6809 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6810 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6811 	union  lpfc_sli4_cfg_shdr *shdr;
6812 
6813 	switch (type) {
6814 	case LPFC_RSC_TYPE_FCOE_VPI:
6815 		blk_list_head = &phba->lpfc_vpi_blk_list;
6816 		break;
6817 	case LPFC_RSC_TYPE_FCOE_XRI:
6818 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
6819 		break;
6820 	case LPFC_RSC_TYPE_FCOE_VFI:
6821 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
6822 		break;
6823 	case LPFC_RSC_TYPE_FCOE_RPI:
6824 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
6825 		break;
6826 	default:
6827 		return -EIO;
6828 	}
6829 
6830 	/* Count the number of extents currently allocatd for this type. */
6831 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
6832 		if (curr_blks == 0) {
6833 			/*
6834 			 * The GET_ALLOCATED mailbox does not return the size,
6835 			 * just the count.  The size should be just the size
6836 			 * stored in the current allocated block and all sizes
6837 			 * for an extent type are the same so set the return
6838 			 * value now.
6839 			 */
6840 			*extnt_size = rsrc_blk->rsrc_size;
6841 		}
6842 		curr_blks++;
6843 	}
6844 
6845 	/*
6846 	 * Calculate the size of an embedded mailbox.  The uint32_t
6847 	 * accounts for extents-specific word.
6848 	 */
6849 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6850 		sizeof(uint32_t);
6851 
6852 	/*
6853 	 * Presume the allocation and response will fit into an embedded
6854 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6855 	 */
6856 	emb = LPFC_SLI4_MBX_EMBED;
6857 	req_len = emb_len;
6858 	if (req_len > emb_len) {
6859 		req_len = curr_blks * sizeof(uint16_t) +
6860 			sizeof(union lpfc_sli4_cfg_shdr) +
6861 			sizeof(uint32_t);
6862 		emb = LPFC_SLI4_MBX_NEMBED;
6863 	}
6864 
6865 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6866 	if (!mbox)
6867 		return -ENOMEM;
6868 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
6869 
6870 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6871 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
6872 				     req_len, emb);
6873 	if (alloc_len < req_len) {
6874 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6875 			"2983 Allocated DMA memory size (x%x) is "
6876 			"less than the requested DMA memory "
6877 			"size (x%x)\n", alloc_len, req_len);
6878 		rc = -ENOMEM;
6879 		goto err_exit;
6880 	}
6881 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
6882 	if (unlikely(rc)) {
6883 		rc = -EIO;
6884 		goto err_exit;
6885 	}
6886 
6887 	if (!phba->sli4_hba.intr_enable)
6888 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6889 	else {
6890 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6891 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6892 	}
6893 
6894 	if (unlikely(rc)) {
6895 		rc = -EIO;
6896 		goto err_exit;
6897 	}
6898 
6899 	/*
6900 	 * Figure out where the response is located.  Then get local pointers
6901 	 * to the response data.  The port does not guarantee to respond to
6902 	 * all extents counts request so update the local variable with the
6903 	 * allocated count from the port.
6904 	 */
6905 	if (emb == LPFC_SLI4_MBX_EMBED) {
6906 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6907 		shdr = &rsrc_ext->header.cfg_shdr;
6908 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6909 	} else {
6910 		virtaddr = mbox->sge_array->addr[0];
6911 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6912 		shdr = &n_rsrc->cfg_shdr;
6913 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6914 	}
6915 
6916 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
6917 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
6918 			"2984 Failed to read allocated resources "
6919 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
6920 			type,
6921 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
6922 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
6923 		rc = -EIO;
6924 		goto err_exit;
6925 	}
6926  err_exit:
6927 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6928 	return rc;
6929 }
6930 
6931 /**
6932  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
6933  * @phba: pointer to lpfc hba data structure.
6934  * @pring: Pointer to driver SLI ring object.
6935  * @sgl_list: linked link of sgl buffers to post
6936  * @cnt: number of linked list buffers
6937  *
6938  * This routine walks the list of buffers that have been allocated and
6939  * repost them to the port by using SGL block post. This is needed after a
6940  * pci_function_reset/warm_start or start. It attempts to construct blocks
6941  * of buffer sgls which contains contiguous xris and uses the non-embedded
6942  * SGL block post mailbox commands to post them to the port. For single
6943  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
6944  * mailbox command for posting.
6945  *
6946  * Returns: 0 = success, non-zero failure.
6947  **/
6948 static int
6949 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
6950 			  struct list_head *sgl_list, int cnt)
6951 {
6952 	struct lpfc_sglq *sglq_entry = NULL;
6953 	struct lpfc_sglq *sglq_entry_next = NULL;
6954 	struct lpfc_sglq *sglq_entry_first = NULL;
6955 	int status, total_cnt;
6956 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
6957 	int last_xritag = NO_XRI;
6958 	LIST_HEAD(prep_sgl_list);
6959 	LIST_HEAD(blck_sgl_list);
6960 	LIST_HEAD(allc_sgl_list);
6961 	LIST_HEAD(post_sgl_list);
6962 	LIST_HEAD(free_sgl_list);
6963 
6964 	spin_lock_irq(&phba->hbalock);
6965 	spin_lock(&phba->sli4_hba.sgl_list_lock);
6966 	list_splice_init(sgl_list, &allc_sgl_list);
6967 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
6968 	spin_unlock_irq(&phba->hbalock);
6969 
6970 	total_cnt = cnt;
6971 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
6972 				 &allc_sgl_list, list) {
6973 		list_del_init(&sglq_entry->list);
6974 		block_cnt++;
6975 		if ((last_xritag != NO_XRI) &&
6976 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
6977 			/* a hole in xri block, form a sgl posting block */
6978 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
6979 			post_cnt = block_cnt - 1;
6980 			/* prepare list for next posting block */
6981 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6982 			block_cnt = 1;
6983 		} else {
6984 			/* prepare list for next posting block */
6985 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6986 			/* enough sgls for non-embed sgl mbox command */
6987 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
6988 				list_splice_init(&prep_sgl_list,
6989 						 &blck_sgl_list);
6990 				post_cnt = block_cnt;
6991 				block_cnt = 0;
6992 			}
6993 		}
6994 		num_posted++;
6995 
6996 		/* keep track of last sgl's xritag */
6997 		last_xritag = sglq_entry->sli4_xritag;
6998 
6999 		/* end of repost sgl list condition for buffers */
7000 		if (num_posted == total_cnt) {
7001 			if (post_cnt == 0) {
7002 				list_splice_init(&prep_sgl_list,
7003 						 &blck_sgl_list);
7004 				post_cnt = block_cnt;
7005 			} else if (block_cnt == 1) {
7006 				status = lpfc_sli4_post_sgl(phba,
7007 						sglq_entry->phys, 0,
7008 						sglq_entry->sli4_xritag);
7009 				if (!status) {
7010 					/* successful, put sgl to posted list */
7011 					list_add_tail(&sglq_entry->list,
7012 						      &post_sgl_list);
7013 				} else {
7014 					/* Failure, put sgl to free list */
7015 					lpfc_printf_log(phba, KERN_WARNING,
7016 						LOG_SLI,
7017 						"3159 Failed to post "
7018 						"sgl, xritag:x%x\n",
7019 						sglq_entry->sli4_xritag);
7020 					list_add_tail(&sglq_entry->list,
7021 						      &free_sgl_list);
7022 					total_cnt--;
7023 				}
7024 			}
7025 		}
7026 
7027 		/* continue until a nembed page worth of sgls */
7028 		if (post_cnt == 0)
7029 			continue;
7030 
7031 		/* post the buffer list sgls as a block */
7032 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7033 						 post_cnt);
7034 
7035 		if (!status) {
7036 			/* success, put sgl list to posted sgl list */
7037 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7038 		} else {
7039 			/* Failure, put sgl list to free sgl list */
7040 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7041 							    struct lpfc_sglq,
7042 							    list);
7043 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7044 					"3160 Failed to post sgl-list, "
7045 					"xritag:x%x-x%x\n",
7046 					sglq_entry_first->sli4_xritag,
7047 					(sglq_entry_first->sli4_xritag +
7048 					 post_cnt - 1));
7049 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7050 			total_cnt -= post_cnt;
7051 		}
7052 
7053 		/* don't reset xirtag due to hole in xri block */
7054 		if (block_cnt == 0)
7055 			last_xritag = NO_XRI;
7056 
7057 		/* reset sgl post count for next round of posting */
7058 		post_cnt = 0;
7059 	}
7060 
7061 	/* free the sgls failed to post */
7062 	lpfc_free_sgl_list(phba, &free_sgl_list);
7063 
7064 	/* push sgls posted to the available list */
7065 	if (!list_empty(&post_sgl_list)) {
7066 		spin_lock_irq(&phba->hbalock);
7067 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7068 		list_splice_init(&post_sgl_list, sgl_list);
7069 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7070 		spin_unlock_irq(&phba->hbalock);
7071 	} else {
7072 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7073 				"3161 Failure to post sgl to port.\n");
7074 		return -EIO;
7075 	}
7076 
7077 	/* return the number of XRIs actually posted */
7078 	return total_cnt;
7079 }
7080 
7081 /**
7082  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7083  * @phba: pointer to lpfc hba data structure.
7084  *
7085  * This routine walks the list of nvme buffers that have been allocated and
7086  * repost them to the port by using SGL block post. This is needed after a
7087  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7088  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7089  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7090  *
7091  * Returns: 0 = success, non-zero failure.
7092  **/
7093 static int
7094 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7095 {
7096 	LIST_HEAD(post_nblist);
7097 	int num_posted, rc = 0;
7098 
7099 	/* get all NVME buffers need to repost to a local list */
7100 	lpfc_io_buf_flush(phba, &post_nblist);
7101 
7102 	/* post the list of nvme buffer sgls to port if available */
7103 	if (!list_empty(&post_nblist)) {
7104 		num_posted = lpfc_sli4_post_io_sgl_list(
7105 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7106 		/* failed to post any nvme buffer, return error */
7107 		if (num_posted == 0)
7108 			rc = -EIO;
7109 	}
7110 	return rc;
7111 }
7112 
7113 static void
7114 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7115 {
7116 	uint32_t len;
7117 
7118 	len = sizeof(struct lpfc_mbx_set_host_data) -
7119 		sizeof(struct lpfc_sli4_cfg_mhdr);
7120 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7121 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7122 			 LPFC_SLI4_MBX_EMBED);
7123 
7124 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7125 	mbox->u.mqe.un.set_host_data.param_len =
7126 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7127 	snprintf(mbox->u.mqe.un.set_host_data.data,
7128 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7129 		 "Linux %s v"LPFC_DRIVER_VERSION,
7130 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7131 }
7132 
7133 int
7134 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7135 		    struct lpfc_queue *drq, int count, int idx)
7136 {
7137 	int rc, i;
7138 	struct lpfc_rqe hrqe;
7139 	struct lpfc_rqe drqe;
7140 	struct lpfc_rqb *rqbp;
7141 	unsigned long flags;
7142 	struct rqb_dmabuf *rqb_buffer;
7143 	LIST_HEAD(rqb_buf_list);
7144 
7145 	spin_lock_irqsave(&phba->hbalock, flags);
7146 	rqbp = hrq->rqbp;
7147 	for (i = 0; i < count; i++) {
7148 		/* IF RQ is already full, don't bother */
7149 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1)
7150 			break;
7151 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7152 		if (!rqb_buffer)
7153 			break;
7154 		rqb_buffer->hrq = hrq;
7155 		rqb_buffer->drq = drq;
7156 		rqb_buffer->idx = idx;
7157 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7158 	}
7159 	while (!list_empty(&rqb_buf_list)) {
7160 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7161 				 hbuf.list);
7162 
7163 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7164 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7165 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7166 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7167 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7168 		if (rc < 0) {
7169 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7170 					"6421 Cannot post to HRQ %d: %x %x %x "
7171 					"DRQ %x %x\n",
7172 					hrq->queue_id,
7173 					hrq->host_index,
7174 					hrq->hba_index,
7175 					hrq->entry_count,
7176 					drq->host_index,
7177 					drq->hba_index);
7178 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7179 		} else {
7180 			list_add_tail(&rqb_buffer->hbuf.list,
7181 				      &rqbp->rqb_buffer_list);
7182 			rqbp->buffer_count++;
7183 		}
7184 	}
7185 	spin_unlock_irqrestore(&phba->hbalock, flags);
7186 	return 1;
7187 }
7188 
7189 /**
7190  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
7191  * @phba: Pointer to HBA context object.
7192  *
7193  * This function is the main SLI4 device initialization PCI function. This
7194  * function is called by the HBA initialization code, HBA reset code and
7195  * HBA error attention handler code. Caller is not required to hold any
7196  * locks.
7197  **/
7198 int
7199 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
7200 {
7201 	int rc, i, cnt, len, dd;
7202 	LPFC_MBOXQ_t *mboxq;
7203 	struct lpfc_mqe *mqe;
7204 	uint8_t *vpd;
7205 	uint32_t vpd_size;
7206 	uint32_t ftr_rsp = 0;
7207 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
7208 	struct lpfc_vport *vport = phba->pport;
7209 	struct lpfc_dmabuf *mp;
7210 	struct lpfc_rqb *rqbp;
7211 
7212 	/* Perform a PCI function reset to start from clean */
7213 	rc = lpfc_pci_function_reset(phba);
7214 	if (unlikely(rc))
7215 		return -ENODEV;
7216 
7217 	/* Check the HBA Host Status Register for readyness */
7218 	rc = lpfc_sli4_post_status_check(phba);
7219 	if (unlikely(rc))
7220 		return -ENODEV;
7221 	else {
7222 		spin_lock_irq(&phba->hbalock);
7223 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
7224 		spin_unlock_irq(&phba->hbalock);
7225 	}
7226 
7227 	/*
7228 	 * Allocate a single mailbox container for initializing the
7229 	 * port.
7230 	 */
7231 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7232 	if (!mboxq)
7233 		return -ENOMEM;
7234 
7235 	/* Issue READ_REV to collect vpd and FW information. */
7236 	vpd_size = SLI4_PAGE_SIZE;
7237 	vpd = kzalloc(vpd_size, GFP_KERNEL);
7238 	if (!vpd) {
7239 		rc = -ENOMEM;
7240 		goto out_free_mbox;
7241 	}
7242 
7243 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
7244 	if (unlikely(rc)) {
7245 		kfree(vpd);
7246 		goto out_free_mbox;
7247 	}
7248 
7249 	mqe = &mboxq->u.mqe;
7250 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
7251 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
7252 		phba->hba_flag |= HBA_FCOE_MODE;
7253 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
7254 	} else {
7255 		phba->hba_flag &= ~HBA_FCOE_MODE;
7256 	}
7257 
7258 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
7259 		LPFC_DCBX_CEE_MODE)
7260 		phba->hba_flag |= HBA_FIP_SUPPORT;
7261 	else
7262 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
7263 
7264 	phba->hba_flag &= ~HBA_IOQ_FLUSH;
7265 
7266 	if (phba->sli_rev != LPFC_SLI_REV4) {
7267 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7268 			"0376 READ_REV Error. SLI Level %d "
7269 			"FCoE enabled %d\n",
7270 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
7271 		rc = -EIO;
7272 		kfree(vpd);
7273 		goto out_free_mbox;
7274 	}
7275 
7276 	/*
7277 	 * Continue initialization with default values even if driver failed
7278 	 * to read FCoE param config regions, only read parameters if the
7279 	 * board is FCoE
7280 	 */
7281 	if (phba->hba_flag & HBA_FCOE_MODE &&
7282 	    lpfc_sli4_read_fcoe_params(phba))
7283 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
7284 			"2570 Failed to read FCoE parameters\n");
7285 
7286 	/*
7287 	 * Retrieve sli4 device physical port name, failure of doing it
7288 	 * is considered as non-fatal.
7289 	 */
7290 	rc = lpfc_sli4_retrieve_pport_name(phba);
7291 	if (!rc)
7292 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7293 				"3080 Successful retrieving SLI4 device "
7294 				"physical port name: %s.\n", phba->Port);
7295 
7296 	rc = lpfc_sli4_get_ctl_attr(phba);
7297 	if (!rc)
7298 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7299 				"8351 Successful retrieving SLI4 device "
7300 				"CTL ATTR\n");
7301 
7302 	/*
7303 	 * Evaluate the read rev and vpd data. Populate the driver
7304 	 * state with the results. If this routine fails, the failure
7305 	 * is not fatal as the driver will use generic values.
7306 	 */
7307 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
7308 	if (unlikely(!rc)) {
7309 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7310 				"0377 Error %d parsing vpd. "
7311 				"Using defaults.\n", rc);
7312 		rc = 0;
7313 	}
7314 	kfree(vpd);
7315 
7316 	/* Save information as VPD data */
7317 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
7318 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
7319 
7320 	/*
7321 	 * This is because first G7 ASIC doesn't support the standard
7322 	 * 0x5a NVME cmd descriptor type/subtype
7323 	 */
7324 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7325 			LPFC_SLI_INTF_IF_TYPE_6) &&
7326 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
7327 	    (phba->vpd.rev.smRev == 0) &&
7328 	    (phba->cfg_nvme_embed_cmd == 1))
7329 		phba->cfg_nvme_embed_cmd = 0;
7330 
7331 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
7332 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
7333 					 &mqe->un.read_rev);
7334 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
7335 				       &mqe->un.read_rev);
7336 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
7337 					    &mqe->un.read_rev);
7338 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
7339 					   &mqe->un.read_rev);
7340 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
7341 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
7342 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
7343 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
7344 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
7345 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
7346 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7347 			"(%d):0380 READ_REV Status x%x "
7348 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
7349 			mboxq->vport ? mboxq->vport->vpi : 0,
7350 			bf_get(lpfc_mqe_status, mqe),
7351 			phba->vpd.rev.opFwName,
7352 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
7353 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
7354 
7355 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7356 	    LPFC_SLI_INTF_IF_TYPE_0) {
7357 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
7358 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7359 		if (rc == MBX_SUCCESS) {
7360 			phba->hba_flag |= HBA_RECOVERABLE_UE;
7361 			/* Set 1Sec interval to detect UE */
7362 			phba->eratt_poll_interval = 1;
7363 			phba->sli4_hba.ue_to_sr = bf_get(
7364 					lpfc_mbx_set_feature_UESR,
7365 					&mboxq->u.mqe.un.set_feature);
7366 			phba->sli4_hba.ue_to_rp = bf_get(
7367 					lpfc_mbx_set_feature_UERP,
7368 					&mboxq->u.mqe.un.set_feature);
7369 		}
7370 	}
7371 
7372 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
7373 		/* Enable MDS Diagnostics only if the SLI Port supports it */
7374 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
7375 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7376 		if (rc != MBX_SUCCESS)
7377 			phba->mds_diags_support = 0;
7378 	}
7379 
7380 	/*
7381 	 * Discover the port's supported feature set and match it against the
7382 	 * hosts requests.
7383 	 */
7384 	lpfc_request_features(phba, mboxq);
7385 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7386 	if (unlikely(rc)) {
7387 		rc = -EIO;
7388 		goto out_free_mbox;
7389 	}
7390 
7391 	/*
7392 	 * The port must support FCP initiator mode as this is the
7393 	 * only mode running in the host.
7394 	 */
7395 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
7396 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7397 				"0378 No support for fcpi mode.\n");
7398 		ftr_rsp++;
7399 	}
7400 
7401 	/* Performance Hints are ONLY for FCoE */
7402 	if (phba->hba_flag & HBA_FCOE_MODE) {
7403 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
7404 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
7405 		else
7406 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
7407 	}
7408 
7409 	/*
7410 	 * If the port cannot support the host's requested features
7411 	 * then turn off the global config parameters to disable the
7412 	 * feature in the driver.  This is not a fatal error.
7413 	 */
7414 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
7415 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
7416 			phba->cfg_enable_bg = 0;
7417 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
7418 			ftr_rsp++;
7419 		}
7420 	}
7421 
7422 	if (phba->max_vpi && phba->cfg_enable_npiv &&
7423 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7424 		ftr_rsp++;
7425 
7426 	if (ftr_rsp) {
7427 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7428 				"0379 Feature Mismatch Data: x%08x %08x "
7429 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
7430 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
7431 				phba->cfg_enable_npiv, phba->max_vpi);
7432 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
7433 			phba->cfg_enable_bg = 0;
7434 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7435 			phba->cfg_enable_npiv = 0;
7436 	}
7437 
7438 	/* These SLI3 features are assumed in SLI4 */
7439 	spin_lock_irq(&phba->hbalock);
7440 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
7441 	spin_unlock_irq(&phba->hbalock);
7442 
7443 	/* Always try to enable dual dump feature if we can */
7444 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
7445 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7446 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
7447 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
7448 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_INIT,
7449 				"6448 Dual Dump is enabled\n");
7450 	else
7451 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
7452 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
7453 				"rc:x%x dd:x%x\n",
7454 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7455 				lpfc_sli_config_mbox_subsys_get(
7456 					phba, mboxq),
7457 				lpfc_sli_config_mbox_opcode_get(
7458 					phba, mboxq),
7459 				rc, dd);
7460 	/*
7461 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
7462 	 * calls depends on these resources to complete port setup.
7463 	 */
7464 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
7465 	if (rc) {
7466 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7467 				"2920 Failed to alloc Resource IDs "
7468 				"rc = x%x\n", rc);
7469 		goto out_free_mbox;
7470 	}
7471 
7472 	lpfc_set_host_data(phba, mboxq);
7473 
7474 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7475 	if (rc) {
7476 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7477 				"2134 Failed to set host os driver version %x",
7478 				rc);
7479 	}
7480 
7481 	/* Read the port's service parameters. */
7482 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
7483 	if (rc) {
7484 		phba->link_state = LPFC_HBA_ERROR;
7485 		rc = -ENOMEM;
7486 		goto out_free_mbox;
7487 	}
7488 
7489 	mboxq->vport = vport;
7490 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7491 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
7492 	if (rc == MBX_SUCCESS) {
7493 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
7494 		rc = 0;
7495 	}
7496 
7497 	/*
7498 	 * This memory was allocated by the lpfc_read_sparam routine. Release
7499 	 * it to the mbuf pool.
7500 	 */
7501 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
7502 	kfree(mp);
7503 	mboxq->ctx_buf = NULL;
7504 	if (unlikely(rc)) {
7505 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7506 				"0382 READ_SPARAM command failed "
7507 				"status %d, mbxStatus x%x\n",
7508 				rc, bf_get(lpfc_mqe_status, mqe));
7509 		phba->link_state = LPFC_HBA_ERROR;
7510 		rc = -EIO;
7511 		goto out_free_mbox;
7512 	}
7513 
7514 	lpfc_update_vport_wwn(vport);
7515 
7516 	/* Update the fc_host data structures with new wwn. */
7517 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
7518 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
7519 
7520 	/* Create all the SLI4 queues */
7521 	rc = lpfc_sli4_queue_create(phba);
7522 	if (rc) {
7523 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7524 				"3089 Failed to allocate queues\n");
7525 		rc = -ENODEV;
7526 		goto out_free_mbox;
7527 	}
7528 	/* Set up all the queues to the device */
7529 	rc = lpfc_sli4_queue_setup(phba);
7530 	if (unlikely(rc)) {
7531 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7532 				"0381 Error %d during queue setup.\n ", rc);
7533 		goto out_stop_timers;
7534 	}
7535 	/* Initialize the driver internal SLI layer lists. */
7536 	lpfc_sli4_setup(phba);
7537 	lpfc_sli4_queue_init(phba);
7538 
7539 	/* update host els xri-sgl sizes and mappings */
7540 	rc = lpfc_sli4_els_sgl_update(phba);
7541 	if (unlikely(rc)) {
7542 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7543 				"1400 Failed to update xri-sgl size and "
7544 				"mapping: %d\n", rc);
7545 		goto out_destroy_queue;
7546 	}
7547 
7548 	/* register the els sgl pool to the port */
7549 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
7550 				       phba->sli4_hba.els_xri_cnt);
7551 	if (unlikely(rc < 0)) {
7552 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7553 				"0582 Error %d during els sgl post "
7554 				"operation\n", rc);
7555 		rc = -ENODEV;
7556 		goto out_destroy_queue;
7557 	}
7558 	phba->sli4_hba.els_xri_cnt = rc;
7559 
7560 	if (phba->nvmet_support) {
7561 		/* update host nvmet xri-sgl sizes and mappings */
7562 		rc = lpfc_sli4_nvmet_sgl_update(phba);
7563 		if (unlikely(rc)) {
7564 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7565 					"6308 Failed to update nvmet-sgl size "
7566 					"and mapping: %d\n", rc);
7567 			goto out_destroy_queue;
7568 		}
7569 
7570 		/* register the nvmet sgl pool to the port */
7571 		rc = lpfc_sli4_repost_sgl_list(
7572 			phba,
7573 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
7574 			phba->sli4_hba.nvmet_xri_cnt);
7575 		if (unlikely(rc < 0)) {
7576 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7577 					"3117 Error %d during nvmet "
7578 					"sgl post\n", rc);
7579 			rc = -ENODEV;
7580 			goto out_destroy_queue;
7581 		}
7582 		phba->sli4_hba.nvmet_xri_cnt = rc;
7583 
7584 		/* We allocate an iocbq for every receive context SGL.
7585 		 * The additional allocation is for abort and ls handling.
7586 		 */
7587 		cnt = phba->sli4_hba.nvmet_xri_cnt +
7588 			phba->sli4_hba.max_cfg_param.max_xri;
7589 	} else {
7590 		/* update host common xri-sgl sizes and mappings */
7591 		rc = lpfc_sli4_io_sgl_update(phba);
7592 		if (unlikely(rc)) {
7593 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7594 					"6082 Failed to update nvme-sgl size "
7595 					"and mapping: %d\n", rc);
7596 			goto out_destroy_queue;
7597 		}
7598 
7599 		/* register the allocated common sgl pool to the port */
7600 		rc = lpfc_sli4_repost_io_sgl_list(phba);
7601 		if (unlikely(rc)) {
7602 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7603 					"6116 Error %d during nvme sgl post "
7604 					"operation\n", rc);
7605 			/* Some NVME buffers were moved to abort nvme list */
7606 			/* A pci function reset will repost them */
7607 			rc = -ENODEV;
7608 			goto out_destroy_queue;
7609 		}
7610 		/* Each lpfc_io_buf job structure has an iocbq element.
7611 		 * This cnt provides for abort, els, ct and ls requests.
7612 		 */
7613 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
7614 	}
7615 
7616 	if (!phba->sli.iocbq_lookup) {
7617 		/* Initialize and populate the iocb list per host */
7618 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7619 				"2821 initialize iocb list with %d entries\n",
7620 				cnt);
7621 		rc = lpfc_init_iocb_list(phba, cnt);
7622 		if (rc) {
7623 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7624 					"1413 Failed to init iocb list.\n");
7625 			goto out_destroy_queue;
7626 		}
7627 	}
7628 
7629 	if (phba->nvmet_support)
7630 		lpfc_nvmet_create_targetport(phba);
7631 
7632 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
7633 		/* Post initial buffers to all RQs created */
7634 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
7635 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
7636 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
7637 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
7638 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
7639 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
7640 			rqbp->buffer_count = 0;
7641 
7642 			lpfc_post_rq_buffer(
7643 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
7644 				phba->sli4_hba.nvmet_mrq_data[i],
7645 				phba->cfg_nvmet_mrq_post, i);
7646 		}
7647 	}
7648 
7649 	/* Post the rpi header region to the device. */
7650 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
7651 	if (unlikely(rc)) {
7652 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7653 				"0393 Error %d during rpi post operation\n",
7654 				rc);
7655 		rc = -ENODEV;
7656 		goto out_destroy_queue;
7657 	}
7658 	lpfc_sli4_node_prep(phba);
7659 
7660 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
7661 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
7662 			/*
7663 			 * The FC Port needs to register FCFI (index 0)
7664 			 */
7665 			lpfc_reg_fcfi(phba, mboxq);
7666 			mboxq->vport = phba->pport;
7667 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7668 			if (rc != MBX_SUCCESS)
7669 				goto out_unset_queue;
7670 			rc = 0;
7671 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
7672 						&mboxq->u.mqe.un.reg_fcfi);
7673 		} else {
7674 			/* We are a NVME Target mode with MRQ > 1 */
7675 
7676 			/* First register the FCFI */
7677 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
7678 			mboxq->vport = phba->pport;
7679 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7680 			if (rc != MBX_SUCCESS)
7681 				goto out_unset_queue;
7682 			rc = 0;
7683 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
7684 						&mboxq->u.mqe.un.reg_fcfi_mrq);
7685 
7686 			/* Next register the MRQs */
7687 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
7688 			mboxq->vport = phba->pport;
7689 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7690 			if (rc != MBX_SUCCESS)
7691 				goto out_unset_queue;
7692 			rc = 0;
7693 		}
7694 		/* Check if the port is configured to be disabled */
7695 		lpfc_sli_read_link_ste(phba);
7696 	}
7697 
7698 	/* Don't post more new bufs if repost already recovered
7699 	 * the nvme sgls.
7700 	 */
7701 	if (phba->nvmet_support == 0) {
7702 		if (phba->sli4_hba.io_xri_cnt == 0) {
7703 			len = lpfc_new_io_buf(
7704 					      phba, phba->sli4_hba.io_xri_max);
7705 			if (len == 0) {
7706 				rc = -ENOMEM;
7707 				goto out_unset_queue;
7708 			}
7709 
7710 			if (phba->cfg_xri_rebalancing)
7711 				lpfc_create_multixri_pools(phba);
7712 		}
7713 	} else {
7714 		phba->cfg_xri_rebalancing = 0;
7715 	}
7716 
7717 	/* Allow asynchronous mailbox command to go through */
7718 	spin_lock_irq(&phba->hbalock);
7719 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7720 	spin_unlock_irq(&phba->hbalock);
7721 
7722 	/* Post receive buffers to the device */
7723 	lpfc_sli4_rb_setup(phba);
7724 
7725 	/* Reset HBA FCF states after HBA reset */
7726 	phba->fcf.fcf_flag = 0;
7727 	phba->fcf.current_rec.flag = 0;
7728 
7729 	/* Start the ELS watchdog timer */
7730 	mod_timer(&vport->els_tmofunc,
7731 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
7732 
7733 	/* Start heart beat timer */
7734 	mod_timer(&phba->hb_tmofunc,
7735 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
7736 	phba->hb_outstanding = 0;
7737 	phba->last_completion_time = jiffies;
7738 
7739 	/* start eq_delay heartbeat */
7740 	if (phba->cfg_auto_imax)
7741 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
7742 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
7743 
7744 	/* Start error attention (ERATT) polling timer */
7745 	mod_timer(&phba->eratt_poll,
7746 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
7747 
7748 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
7749 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
7750 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
7751 		if (!rc) {
7752 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7753 					"2829 This device supports "
7754 					"Advanced Error Reporting (AER)\n");
7755 			spin_lock_irq(&phba->hbalock);
7756 			phba->hba_flag |= HBA_AER_ENABLED;
7757 			spin_unlock_irq(&phba->hbalock);
7758 		} else {
7759 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7760 					"2830 This device does not support "
7761 					"Advanced Error Reporting (AER)\n");
7762 			phba->cfg_aer_support = 0;
7763 		}
7764 		rc = 0;
7765 	}
7766 
7767 	/*
7768 	 * The port is ready, set the host's link state to LINK_DOWN
7769 	 * in preparation for link interrupts.
7770 	 */
7771 	spin_lock_irq(&phba->hbalock);
7772 	phba->link_state = LPFC_LINK_DOWN;
7773 
7774 	/* Check if physical ports are trunked */
7775 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
7776 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
7777 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
7778 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
7779 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
7780 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
7781 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
7782 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
7783 	spin_unlock_irq(&phba->hbalock);
7784 
7785 	/* Arm the CQs and then EQs on device */
7786 	lpfc_sli4_arm_cqeq_intr(phba);
7787 
7788 	/* Indicate device interrupt mode */
7789 	phba->sli4_hba.intr_enable = 1;
7790 
7791 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
7792 	    (phba->hba_flag & LINK_DISABLED)) {
7793 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
7794 				"3103 Adapter Link is disabled.\n");
7795 		lpfc_down_link(phba, mboxq);
7796 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7797 		if (rc != MBX_SUCCESS) {
7798 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
7799 					"3104 Adapter failed to issue "
7800 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
7801 			goto out_io_buff_free;
7802 		}
7803 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
7804 		/* don't perform init_link on SLI4 FC port loopback test */
7805 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
7806 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
7807 			if (rc)
7808 				goto out_io_buff_free;
7809 		}
7810 	}
7811 	mempool_free(mboxq, phba->mbox_mem_pool);
7812 	return rc;
7813 out_io_buff_free:
7814 	/* Free allocated IO Buffers */
7815 	lpfc_io_free(phba);
7816 out_unset_queue:
7817 	/* Unset all the queues set up in this routine when error out */
7818 	lpfc_sli4_queue_unset(phba);
7819 out_destroy_queue:
7820 	lpfc_free_iocb_list(phba);
7821 	lpfc_sli4_queue_destroy(phba);
7822 out_stop_timers:
7823 	lpfc_stop_hba_timers(phba);
7824 out_free_mbox:
7825 	mempool_free(mboxq, phba->mbox_mem_pool);
7826 	return rc;
7827 }
7828 
7829 /**
7830  * lpfc_mbox_timeout - Timeout call back function for mbox timer
7831  * @ptr: context object - pointer to hba structure.
7832  *
7833  * This is the callback function for mailbox timer. The mailbox
7834  * timer is armed when a new mailbox command is issued and the timer
7835  * is deleted when the mailbox complete. The function is called by
7836  * the kernel timer code when a mailbox does not complete within
7837  * expected time. This function wakes up the worker thread to
7838  * process the mailbox timeout and returns. All the processing is
7839  * done by the worker thread function lpfc_mbox_timeout_handler.
7840  **/
7841 void
7842 lpfc_mbox_timeout(struct timer_list *t)
7843 {
7844 	struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
7845 	unsigned long iflag;
7846 	uint32_t tmo_posted;
7847 
7848 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
7849 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
7850 	if (!tmo_posted)
7851 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
7852 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
7853 
7854 	if (!tmo_posted)
7855 		lpfc_worker_wake_up(phba);
7856 	return;
7857 }
7858 
7859 /**
7860  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
7861  *                                    are pending
7862  * @phba: Pointer to HBA context object.
7863  *
7864  * This function checks if any mailbox completions are present on the mailbox
7865  * completion queue.
7866  **/
7867 static bool
7868 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
7869 {
7870 
7871 	uint32_t idx;
7872 	struct lpfc_queue *mcq;
7873 	struct lpfc_mcqe *mcqe;
7874 	bool pending_completions = false;
7875 	uint8_t	qe_valid;
7876 
7877 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
7878 		return false;
7879 
7880 	/* Check for completions on mailbox completion queue */
7881 
7882 	mcq = phba->sli4_hba.mbx_cq;
7883 	idx = mcq->hba_index;
7884 	qe_valid = mcq->qe_valid;
7885 	while (bf_get_le32(lpfc_cqe_valid,
7886 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
7887 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
7888 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
7889 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
7890 			pending_completions = true;
7891 			break;
7892 		}
7893 		idx = (idx + 1) % mcq->entry_count;
7894 		if (mcq->hba_index == idx)
7895 			break;
7896 
7897 		/* if the index wrapped around, toggle the valid bit */
7898 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
7899 			qe_valid = (qe_valid) ? 0 : 1;
7900 	}
7901 	return pending_completions;
7902 
7903 }
7904 
7905 /**
7906  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
7907  *					      that were missed.
7908  * @phba: Pointer to HBA context object.
7909  *
7910  * For sli4, it is possible to miss an interrupt. As such mbox completions
7911  * maybe missed causing erroneous mailbox timeouts to occur. This function
7912  * checks to see if mbox completions are on the mailbox completion queue
7913  * and will process all the completions associated with the eq for the
7914  * mailbox completion queue.
7915  **/
7916 static bool
7917 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
7918 {
7919 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
7920 	uint32_t eqidx;
7921 	struct lpfc_queue *fpeq = NULL;
7922 	struct lpfc_queue *eq;
7923 	bool mbox_pending;
7924 
7925 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
7926 		return false;
7927 
7928 	/* Find the EQ associated with the mbox CQ */
7929 	if (sli4_hba->hdwq) {
7930 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
7931 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
7932 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
7933 				fpeq = eq;
7934 				break;
7935 			}
7936 		}
7937 	}
7938 	if (!fpeq)
7939 		return false;
7940 
7941 	/* Turn off interrupts from this EQ */
7942 
7943 	sli4_hba->sli4_eq_clr_intr(fpeq);
7944 
7945 	/* Check to see if a mbox completion is pending */
7946 
7947 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
7948 
7949 	/*
7950 	 * If a mbox completion is pending, process all the events on EQ
7951 	 * associated with the mbox completion queue (this could include
7952 	 * mailbox commands, async events, els commands, receive queue data
7953 	 * and fcp commands)
7954 	 */
7955 
7956 	if (mbox_pending)
7957 		/* process and rearm the EQ */
7958 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
7959 	else
7960 		/* Always clear and re-arm the EQ */
7961 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
7962 
7963 	return mbox_pending;
7964 
7965 }
7966 
7967 /**
7968  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
7969  * @phba: Pointer to HBA context object.
7970  *
7971  * This function is called from worker thread when a mailbox command times out.
7972  * The caller is not required to hold any locks. This function will reset the
7973  * HBA and recover all the pending commands.
7974  **/
7975 void
7976 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
7977 {
7978 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
7979 	MAILBOX_t *mb = NULL;
7980 
7981 	struct lpfc_sli *psli = &phba->sli;
7982 
7983 	/* If the mailbox completed, process the completion and return */
7984 	if (lpfc_sli4_process_missed_mbox_completions(phba))
7985 		return;
7986 
7987 	if (pmbox != NULL)
7988 		mb = &pmbox->u.mb;
7989 	/* Check the pmbox pointer first.  There is a race condition
7990 	 * between the mbox timeout handler getting executed in the
7991 	 * worklist and the mailbox actually completing. When this
7992 	 * race condition occurs, the mbox_active will be NULL.
7993 	 */
7994 	spin_lock_irq(&phba->hbalock);
7995 	if (pmbox == NULL) {
7996 		lpfc_printf_log(phba, KERN_WARNING,
7997 				LOG_MBOX | LOG_SLI,
7998 				"0353 Active Mailbox cleared - mailbox timeout "
7999 				"exiting\n");
8000 		spin_unlock_irq(&phba->hbalock);
8001 		return;
8002 	}
8003 
8004 	/* Mbox cmd <mbxCommand> timeout */
8005 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8006 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
8007 			mb->mbxCommand,
8008 			phba->pport->port_state,
8009 			phba->sli.sli_flag,
8010 			phba->sli.mbox_active);
8011 	spin_unlock_irq(&phba->hbalock);
8012 
8013 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
8014 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
8015 	 * it to fail all outstanding SCSI IO.
8016 	 */
8017 	spin_lock_irq(&phba->pport->work_port_lock);
8018 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
8019 	spin_unlock_irq(&phba->pport->work_port_lock);
8020 	spin_lock_irq(&phba->hbalock);
8021 	phba->link_state = LPFC_LINK_UNKNOWN;
8022 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
8023 	spin_unlock_irq(&phba->hbalock);
8024 
8025 	lpfc_sli_abort_fcp_rings(phba);
8026 
8027 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8028 			"0345 Resetting board due to mailbox timeout\n");
8029 
8030 	/* Reset the HBA device */
8031 	lpfc_reset_hba(phba);
8032 }
8033 
8034 /**
8035  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
8036  * @phba: Pointer to HBA context object.
8037  * @pmbox: Pointer to mailbox object.
8038  * @flag: Flag indicating how the mailbox need to be processed.
8039  *
8040  * This function is called by discovery code and HBA management code
8041  * to submit a mailbox command to firmware with SLI-3 interface spec. This
8042  * function gets the hbalock to protect the data structures.
8043  * The mailbox command can be submitted in polling mode, in which case
8044  * this function will wait in a polling loop for the completion of the
8045  * mailbox.
8046  * If the mailbox is submitted in no_wait mode (not polling) the
8047  * function will submit the command and returns immediately without waiting
8048  * for the mailbox completion. The no_wait is supported only when HBA
8049  * is in SLI2/SLI3 mode - interrupts are enabled.
8050  * The SLI interface allows only one mailbox pending at a time. If the
8051  * mailbox is issued in polling mode and there is already a mailbox
8052  * pending, then the function will return an error. If the mailbox is issued
8053  * in NO_WAIT mode and there is a mailbox pending already, the function
8054  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
8055  * The sli layer owns the mailbox object until the completion of mailbox
8056  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
8057  * return codes the caller owns the mailbox command after the return of
8058  * the function.
8059  **/
8060 static int
8061 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
8062 		       uint32_t flag)
8063 {
8064 	MAILBOX_t *mbx;
8065 	struct lpfc_sli *psli = &phba->sli;
8066 	uint32_t status, evtctr;
8067 	uint32_t ha_copy, hc_copy;
8068 	int i;
8069 	unsigned long timeout;
8070 	unsigned long drvr_flag = 0;
8071 	uint32_t word0, ldata;
8072 	void __iomem *to_slim;
8073 	int processing_queue = 0;
8074 
8075 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
8076 	if (!pmbox) {
8077 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8078 		/* processing mbox queue from intr_handler */
8079 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8080 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8081 			return MBX_SUCCESS;
8082 		}
8083 		processing_queue = 1;
8084 		pmbox = lpfc_mbox_get(phba);
8085 		if (!pmbox) {
8086 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8087 			return MBX_SUCCESS;
8088 		}
8089 	}
8090 
8091 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
8092 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
8093 		if(!pmbox->vport) {
8094 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8095 			lpfc_printf_log(phba, KERN_ERR,
8096 					LOG_MBOX | LOG_VPORT,
8097 					"1806 Mbox x%x failed. No vport\n",
8098 					pmbox->u.mb.mbxCommand);
8099 			dump_stack();
8100 			goto out_not_finished;
8101 		}
8102 	}
8103 
8104 	/* If the PCI channel is in offline state, do not post mbox. */
8105 	if (unlikely(pci_channel_offline(phba->pcidev))) {
8106 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8107 		goto out_not_finished;
8108 	}
8109 
8110 	/* If HBA has a deferred error attention, fail the iocb. */
8111 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
8112 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8113 		goto out_not_finished;
8114 	}
8115 
8116 	psli = &phba->sli;
8117 
8118 	mbx = &pmbox->u.mb;
8119 	status = MBX_SUCCESS;
8120 
8121 	if (phba->link_state == LPFC_HBA_ERROR) {
8122 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8123 
8124 		/* Mbox command <mbxCommand> cannot issue */
8125 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8126 				"(%d):0311 Mailbox command x%x cannot "
8127 				"issue Data: x%x x%x\n",
8128 				pmbox->vport ? pmbox->vport->vpi : 0,
8129 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8130 		goto out_not_finished;
8131 	}
8132 
8133 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
8134 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
8135 			!(hc_copy & HC_MBINT_ENA)) {
8136 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8137 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8138 				"(%d):2528 Mailbox command x%x cannot "
8139 				"issue Data: x%x x%x\n",
8140 				pmbox->vport ? pmbox->vport->vpi : 0,
8141 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8142 			goto out_not_finished;
8143 		}
8144 	}
8145 
8146 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8147 		/* Polling for a mbox command when another one is already active
8148 		 * is not allowed in SLI. Also, the driver must have established
8149 		 * SLI2 mode to queue and process multiple mbox commands.
8150 		 */
8151 
8152 		if (flag & MBX_POLL) {
8153 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8154 
8155 			/* Mbox command <mbxCommand> cannot issue */
8156 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8157 					"(%d):2529 Mailbox command x%x "
8158 					"cannot issue Data: x%x x%x\n",
8159 					pmbox->vport ? pmbox->vport->vpi : 0,
8160 					pmbox->u.mb.mbxCommand,
8161 					psli->sli_flag, flag);
8162 			goto out_not_finished;
8163 		}
8164 
8165 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
8166 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8167 			/* Mbox command <mbxCommand> cannot issue */
8168 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8169 					"(%d):2530 Mailbox command x%x "
8170 					"cannot issue Data: x%x x%x\n",
8171 					pmbox->vport ? pmbox->vport->vpi : 0,
8172 					pmbox->u.mb.mbxCommand,
8173 					psli->sli_flag, flag);
8174 			goto out_not_finished;
8175 		}
8176 
8177 		/* Another mailbox command is still being processed, queue this
8178 		 * command to be processed later.
8179 		 */
8180 		lpfc_mbox_put(phba, pmbox);
8181 
8182 		/* Mbox cmd issue - BUSY */
8183 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8184 				"(%d):0308 Mbox cmd issue - BUSY Data: "
8185 				"x%x x%x x%x x%x\n",
8186 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
8187 				mbx->mbxCommand,
8188 				phba->pport ? phba->pport->port_state : 0xff,
8189 				psli->sli_flag, flag);
8190 
8191 		psli->slistat.mbox_busy++;
8192 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8193 
8194 		if (pmbox->vport) {
8195 			lpfc_debugfs_disc_trc(pmbox->vport,
8196 				LPFC_DISC_TRC_MBOX_VPORT,
8197 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
8198 				(uint32_t)mbx->mbxCommand,
8199 				mbx->un.varWords[0], mbx->un.varWords[1]);
8200 		}
8201 		else {
8202 			lpfc_debugfs_disc_trc(phba->pport,
8203 				LPFC_DISC_TRC_MBOX,
8204 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
8205 				(uint32_t)mbx->mbxCommand,
8206 				mbx->un.varWords[0], mbx->un.varWords[1]);
8207 		}
8208 
8209 		return MBX_BUSY;
8210 	}
8211 
8212 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8213 
8214 	/* If we are not polling, we MUST be in SLI2 mode */
8215 	if (flag != MBX_POLL) {
8216 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
8217 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
8218 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8219 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8220 			/* Mbox command <mbxCommand> cannot issue */
8221 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8222 					"(%d):2531 Mailbox command x%x "
8223 					"cannot issue Data: x%x x%x\n",
8224 					pmbox->vport ? pmbox->vport->vpi : 0,
8225 					pmbox->u.mb.mbxCommand,
8226 					psli->sli_flag, flag);
8227 			goto out_not_finished;
8228 		}
8229 		/* timeout active mbox command */
8230 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8231 					   1000);
8232 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
8233 	}
8234 
8235 	/* Mailbox cmd <cmd> issue */
8236 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8237 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
8238 			"x%x\n",
8239 			pmbox->vport ? pmbox->vport->vpi : 0,
8240 			mbx->mbxCommand,
8241 			phba->pport ? phba->pport->port_state : 0xff,
8242 			psli->sli_flag, flag);
8243 
8244 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
8245 		if (pmbox->vport) {
8246 			lpfc_debugfs_disc_trc(pmbox->vport,
8247 				LPFC_DISC_TRC_MBOX_VPORT,
8248 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
8249 				(uint32_t)mbx->mbxCommand,
8250 				mbx->un.varWords[0], mbx->un.varWords[1]);
8251 		}
8252 		else {
8253 			lpfc_debugfs_disc_trc(phba->pport,
8254 				LPFC_DISC_TRC_MBOX,
8255 				"MBOX Send:       cmd:x%x mb:x%x x%x",
8256 				(uint32_t)mbx->mbxCommand,
8257 				mbx->un.varWords[0], mbx->un.varWords[1]);
8258 		}
8259 	}
8260 
8261 	psli->slistat.mbox_cmd++;
8262 	evtctr = psli->slistat.mbox_event;
8263 
8264 	/* next set own bit for the adapter and copy over command word */
8265 	mbx->mbxOwner = OWN_CHIP;
8266 
8267 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8268 		/* Populate mbox extension offset word. */
8269 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
8270 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8271 				= (uint8_t *)phba->mbox_ext
8272 				  - (uint8_t *)phba->mbox;
8273 		}
8274 
8275 		/* Copy the mailbox extension data */
8276 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
8277 			lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
8278 					      (uint8_t *)phba->mbox_ext,
8279 					      pmbox->in_ext_byte_len);
8280 		}
8281 		/* Copy command data to host SLIM area */
8282 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
8283 	} else {
8284 		/* Populate mbox extension offset word. */
8285 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
8286 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8287 				= MAILBOX_HBA_EXT_OFFSET;
8288 
8289 		/* Copy the mailbox extension data */
8290 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
8291 			lpfc_memcpy_to_slim(phba->MBslimaddr +
8292 				MAILBOX_HBA_EXT_OFFSET,
8293 				pmbox->ctx_buf, pmbox->in_ext_byte_len);
8294 
8295 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8296 			/* copy command data into host mbox for cmpl */
8297 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
8298 					      MAILBOX_CMD_SIZE);
8299 
8300 		/* First copy mbox command data to HBA SLIM, skip past first
8301 		   word */
8302 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
8303 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
8304 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
8305 
8306 		/* Next copy over first word, with mbxOwner set */
8307 		ldata = *((uint32_t *)mbx);
8308 		to_slim = phba->MBslimaddr;
8309 		writel(ldata, to_slim);
8310 		readl(to_slim); /* flush */
8311 
8312 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8313 			/* switch over to host mailbox */
8314 			psli->sli_flag |= LPFC_SLI_ACTIVE;
8315 	}
8316 
8317 	wmb();
8318 
8319 	switch (flag) {
8320 	case MBX_NOWAIT:
8321 		/* Set up reference to mailbox command */
8322 		psli->mbox_active = pmbox;
8323 		/* Interrupt board to do it */
8324 		writel(CA_MBATT, phba->CAregaddr);
8325 		readl(phba->CAregaddr); /* flush */
8326 		/* Don't wait for it to finish, just return */
8327 		break;
8328 
8329 	case MBX_POLL:
8330 		/* Set up null reference to mailbox command */
8331 		psli->mbox_active = NULL;
8332 		/* Interrupt board to do it */
8333 		writel(CA_MBATT, phba->CAregaddr);
8334 		readl(phba->CAregaddr); /* flush */
8335 
8336 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8337 			/* First read mbox status word */
8338 			word0 = *((uint32_t *)phba->mbox);
8339 			word0 = le32_to_cpu(word0);
8340 		} else {
8341 			/* First read mbox status word */
8342 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
8343 				spin_unlock_irqrestore(&phba->hbalock,
8344 						       drvr_flag);
8345 				goto out_not_finished;
8346 			}
8347 		}
8348 
8349 		/* Read the HBA Host Attention Register */
8350 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8351 			spin_unlock_irqrestore(&phba->hbalock,
8352 						       drvr_flag);
8353 			goto out_not_finished;
8354 		}
8355 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8356 							1000) + jiffies;
8357 		i = 0;
8358 		/* Wait for command to complete */
8359 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
8360 		       (!(ha_copy & HA_MBATT) &&
8361 			(phba->link_state > LPFC_WARM_START))) {
8362 			if (time_after(jiffies, timeout)) {
8363 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8364 				spin_unlock_irqrestore(&phba->hbalock,
8365 						       drvr_flag);
8366 				goto out_not_finished;
8367 			}
8368 
8369 			/* Check if we took a mbox interrupt while we were
8370 			   polling */
8371 			if (((word0 & OWN_CHIP) != OWN_CHIP)
8372 			    && (evtctr != psli->slistat.mbox_event))
8373 				break;
8374 
8375 			if (i++ > 10) {
8376 				spin_unlock_irqrestore(&phba->hbalock,
8377 						       drvr_flag);
8378 				msleep(1);
8379 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
8380 			}
8381 
8382 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8383 				/* First copy command data */
8384 				word0 = *((uint32_t *)phba->mbox);
8385 				word0 = le32_to_cpu(word0);
8386 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
8387 					MAILBOX_t *slimmb;
8388 					uint32_t slimword0;
8389 					/* Check real SLIM for any errors */
8390 					slimword0 = readl(phba->MBslimaddr);
8391 					slimmb = (MAILBOX_t *) & slimword0;
8392 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
8393 					    && slimmb->mbxStatus) {
8394 						psli->sli_flag &=
8395 						    ~LPFC_SLI_ACTIVE;
8396 						word0 = slimword0;
8397 					}
8398 				}
8399 			} else {
8400 				/* First copy command data */
8401 				word0 = readl(phba->MBslimaddr);
8402 			}
8403 			/* Read the HBA Host Attention Register */
8404 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8405 				spin_unlock_irqrestore(&phba->hbalock,
8406 						       drvr_flag);
8407 				goto out_not_finished;
8408 			}
8409 		}
8410 
8411 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8412 			/* copy results back to user */
8413 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
8414 						MAILBOX_CMD_SIZE);
8415 			/* Copy the mailbox extension data */
8416 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8417 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
8418 						      pmbox->ctx_buf,
8419 						      pmbox->out_ext_byte_len);
8420 			}
8421 		} else {
8422 			/* First copy command data */
8423 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
8424 						MAILBOX_CMD_SIZE);
8425 			/* Copy the mailbox extension data */
8426 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8427 				lpfc_memcpy_from_slim(
8428 					pmbox->ctx_buf,
8429 					phba->MBslimaddr +
8430 					MAILBOX_HBA_EXT_OFFSET,
8431 					pmbox->out_ext_byte_len);
8432 			}
8433 		}
8434 
8435 		writel(HA_MBATT, phba->HAregaddr);
8436 		readl(phba->HAregaddr); /* flush */
8437 
8438 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8439 		status = mbx->mbxStatus;
8440 	}
8441 
8442 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8443 	return status;
8444 
8445 out_not_finished:
8446 	if (processing_queue) {
8447 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
8448 		lpfc_mbox_cmpl_put(phba, pmbox);
8449 	}
8450 	return MBX_NOT_FINISHED;
8451 }
8452 
8453 /**
8454  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
8455  * @phba: Pointer to HBA context object.
8456  *
8457  * The function blocks the posting of SLI4 asynchronous mailbox commands from
8458  * the driver internal pending mailbox queue. It will then try to wait out the
8459  * possible outstanding mailbox command before return.
8460  *
8461  * Returns:
8462  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
8463  * 	the outstanding mailbox command timed out.
8464  **/
8465 static int
8466 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
8467 {
8468 	struct lpfc_sli *psli = &phba->sli;
8469 	int rc = 0;
8470 	unsigned long timeout = 0;
8471 
8472 	/* Mark the asynchronous mailbox command posting as blocked */
8473 	spin_lock_irq(&phba->hbalock);
8474 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
8475 	/* Determine how long we might wait for the active mailbox
8476 	 * command to be gracefully completed by firmware.
8477 	 */
8478 	if (phba->sli.mbox_active)
8479 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
8480 						phba->sli.mbox_active) *
8481 						1000) + jiffies;
8482 	spin_unlock_irq(&phba->hbalock);
8483 
8484 	/* Make sure the mailbox is really active */
8485 	if (timeout)
8486 		lpfc_sli4_process_missed_mbox_completions(phba);
8487 
8488 	/* Wait for the outstnading mailbox command to complete */
8489 	while (phba->sli.mbox_active) {
8490 		/* Check active mailbox complete status every 2ms */
8491 		msleep(2);
8492 		if (time_after(jiffies, timeout)) {
8493 			/* Timeout, marked the outstanding cmd not complete */
8494 			rc = 1;
8495 			break;
8496 		}
8497 	}
8498 
8499 	/* Can not cleanly block async mailbox command, fails it */
8500 	if (rc) {
8501 		spin_lock_irq(&phba->hbalock);
8502 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8503 		spin_unlock_irq(&phba->hbalock);
8504 	}
8505 	return rc;
8506 }
8507 
8508 /**
8509  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
8510  * @phba: Pointer to HBA context object.
8511  *
8512  * The function unblocks and resume posting of SLI4 asynchronous mailbox
8513  * commands from the driver internal pending mailbox queue. It makes sure
8514  * that there is no outstanding mailbox command before resuming posting
8515  * asynchronous mailbox commands. If, for any reason, there is outstanding
8516  * mailbox command, it will try to wait it out before resuming asynchronous
8517  * mailbox command posting.
8518  **/
8519 static void
8520 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
8521 {
8522 	struct lpfc_sli *psli = &phba->sli;
8523 
8524 	spin_lock_irq(&phba->hbalock);
8525 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8526 		/* Asynchronous mailbox posting is not blocked, do nothing */
8527 		spin_unlock_irq(&phba->hbalock);
8528 		return;
8529 	}
8530 
8531 	/* Outstanding synchronous mailbox command is guaranteed to be done,
8532 	 * successful or timeout, after timing-out the outstanding mailbox
8533 	 * command shall always be removed, so just unblock posting async
8534 	 * mailbox command and resume
8535 	 */
8536 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8537 	spin_unlock_irq(&phba->hbalock);
8538 
8539 	/* wake up worker thread to post asynchronous mailbox command */
8540 	lpfc_worker_wake_up(phba);
8541 }
8542 
8543 /**
8544  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
8545  * @phba: Pointer to HBA context object.
8546  * @mboxq: Pointer to mailbox object.
8547  *
8548  * The function waits for the bootstrap mailbox register ready bit from
8549  * port for twice the regular mailbox command timeout value.
8550  *
8551  *      0 - no timeout on waiting for bootstrap mailbox register ready.
8552  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
8553  **/
8554 static int
8555 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8556 {
8557 	uint32_t db_ready;
8558 	unsigned long timeout;
8559 	struct lpfc_register bmbx_reg;
8560 
8561 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
8562 				   * 1000) + jiffies;
8563 
8564 	do {
8565 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
8566 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
8567 		if (!db_ready)
8568 			mdelay(2);
8569 
8570 		if (time_after(jiffies, timeout))
8571 			return MBXERR_ERROR;
8572 	} while (!db_ready);
8573 
8574 	return 0;
8575 }
8576 
8577 /**
8578  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
8579  * @phba: Pointer to HBA context object.
8580  * @mboxq: Pointer to mailbox object.
8581  *
8582  * The function posts a mailbox to the port.  The mailbox is expected
8583  * to be comletely filled in and ready for the port to operate on it.
8584  * This routine executes a synchronous completion operation on the
8585  * mailbox by polling for its completion.
8586  *
8587  * The caller must not be holding any locks when calling this routine.
8588  *
8589  * Returns:
8590  *	MBX_SUCCESS - mailbox posted successfully
8591  *	Any of the MBX error values.
8592  **/
8593 static int
8594 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8595 {
8596 	int rc = MBX_SUCCESS;
8597 	unsigned long iflag;
8598 	uint32_t mcqe_status;
8599 	uint32_t mbx_cmnd;
8600 	struct lpfc_sli *psli = &phba->sli;
8601 	struct lpfc_mqe *mb = &mboxq->u.mqe;
8602 	struct lpfc_bmbx_create *mbox_rgn;
8603 	struct dma_address *dma_address;
8604 
8605 	/*
8606 	 * Only one mailbox can be active to the bootstrap mailbox region
8607 	 * at a time and there is no queueing provided.
8608 	 */
8609 	spin_lock_irqsave(&phba->hbalock, iflag);
8610 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8611 		spin_unlock_irqrestore(&phba->hbalock, iflag);
8612 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8613 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
8614 				"cannot issue Data: x%x x%x\n",
8615 				mboxq->vport ? mboxq->vport->vpi : 0,
8616 				mboxq->u.mb.mbxCommand,
8617 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8618 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8619 				psli->sli_flag, MBX_POLL);
8620 		return MBXERR_ERROR;
8621 	}
8622 	/* The server grabs the token and owns it until release */
8623 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8624 	phba->sli.mbox_active = mboxq;
8625 	spin_unlock_irqrestore(&phba->hbalock, iflag);
8626 
8627 	/* wait for bootstrap mbox register for readyness */
8628 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8629 	if (rc)
8630 		goto exit;
8631 	/*
8632 	 * Initialize the bootstrap memory region to avoid stale data areas
8633 	 * in the mailbox post.  Then copy the caller's mailbox contents to
8634 	 * the bmbx mailbox region.
8635 	 */
8636 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
8637 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
8638 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
8639 			       sizeof(struct lpfc_mqe));
8640 
8641 	/* Post the high mailbox dma address to the port and wait for ready. */
8642 	dma_address = &phba->sli4_hba.bmbx.dma_address;
8643 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
8644 
8645 	/* wait for bootstrap mbox register for hi-address write done */
8646 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8647 	if (rc)
8648 		goto exit;
8649 
8650 	/* Post the low mailbox dma address to the port. */
8651 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
8652 
8653 	/* wait for bootstrap mbox register for low address write done */
8654 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8655 	if (rc)
8656 		goto exit;
8657 
8658 	/*
8659 	 * Read the CQ to ensure the mailbox has completed.
8660 	 * If so, update the mailbox status so that the upper layers
8661 	 * can complete the request normally.
8662 	 */
8663 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
8664 			       sizeof(struct lpfc_mqe));
8665 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
8666 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
8667 			       sizeof(struct lpfc_mcqe));
8668 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
8669 	/*
8670 	 * When the CQE status indicates a failure and the mailbox status
8671 	 * indicates success then copy the CQE status into the mailbox status
8672 	 * (and prefix it with x4000).
8673 	 */
8674 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
8675 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
8676 			bf_set(lpfc_mqe_status, mb,
8677 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
8678 		rc = MBXERR_ERROR;
8679 	} else
8680 		lpfc_sli4_swap_str(phba, mboxq);
8681 
8682 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8683 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
8684 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
8685 			" x%x x%x CQ: x%x x%x x%x x%x\n",
8686 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
8687 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8688 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8689 			bf_get(lpfc_mqe_status, mb),
8690 			mb->un.mb_words[0], mb->un.mb_words[1],
8691 			mb->un.mb_words[2], mb->un.mb_words[3],
8692 			mb->un.mb_words[4], mb->un.mb_words[5],
8693 			mb->un.mb_words[6], mb->un.mb_words[7],
8694 			mb->un.mb_words[8], mb->un.mb_words[9],
8695 			mb->un.mb_words[10], mb->un.mb_words[11],
8696 			mb->un.mb_words[12], mboxq->mcqe.word0,
8697 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
8698 			mboxq->mcqe.trailer);
8699 exit:
8700 	/* We are holding the token, no needed for lock when release */
8701 	spin_lock_irqsave(&phba->hbalock, iflag);
8702 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8703 	phba->sli.mbox_active = NULL;
8704 	spin_unlock_irqrestore(&phba->hbalock, iflag);
8705 	return rc;
8706 }
8707 
8708 /**
8709  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
8710  * @phba: Pointer to HBA context object.
8711  * @pmbox: Pointer to mailbox object.
8712  * @flag: Flag indicating how the mailbox need to be processed.
8713  *
8714  * This function is called by discovery code and HBA management code to submit
8715  * a mailbox command to firmware with SLI-4 interface spec.
8716  *
8717  * Return codes the caller owns the mailbox command after the return of the
8718  * function.
8719  **/
8720 static int
8721 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
8722 		       uint32_t flag)
8723 {
8724 	struct lpfc_sli *psli = &phba->sli;
8725 	unsigned long iflags;
8726 	int rc;
8727 
8728 	/* dump from issue mailbox command if setup */
8729 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
8730 
8731 	rc = lpfc_mbox_dev_check(phba);
8732 	if (unlikely(rc)) {
8733 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8734 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
8735 				"cannot issue Data: x%x x%x\n",
8736 				mboxq->vport ? mboxq->vport->vpi : 0,
8737 				mboxq->u.mb.mbxCommand,
8738 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8739 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8740 				psli->sli_flag, flag);
8741 		goto out_not_finished;
8742 	}
8743 
8744 	/* Detect polling mode and jump to a handler */
8745 	if (!phba->sli4_hba.intr_enable) {
8746 		if (flag == MBX_POLL)
8747 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
8748 		else
8749 			rc = -EIO;
8750 		if (rc != MBX_SUCCESS)
8751 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8752 					"(%d):2541 Mailbox command x%x "
8753 					"(x%x/x%x) failure: "
8754 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
8755 					"Data: x%x x%x\n,",
8756 					mboxq->vport ? mboxq->vport->vpi : 0,
8757 					mboxq->u.mb.mbxCommand,
8758 					lpfc_sli_config_mbox_subsys_get(phba,
8759 									mboxq),
8760 					lpfc_sli_config_mbox_opcode_get(phba,
8761 									mboxq),
8762 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
8763 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
8764 					bf_get(lpfc_mcqe_ext_status,
8765 					       &mboxq->mcqe),
8766 					psli->sli_flag, flag);
8767 		return rc;
8768 	} else if (flag == MBX_POLL) {
8769 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8770 				"(%d):2542 Try to issue mailbox command "
8771 				"x%x (x%x/x%x) synchronously ahead of async "
8772 				"mailbox command queue: x%x x%x\n",
8773 				mboxq->vport ? mboxq->vport->vpi : 0,
8774 				mboxq->u.mb.mbxCommand,
8775 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8776 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8777 				psli->sli_flag, flag);
8778 		/* Try to block the asynchronous mailbox posting */
8779 		rc = lpfc_sli4_async_mbox_block(phba);
8780 		if (!rc) {
8781 			/* Successfully blocked, now issue sync mbox cmd */
8782 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
8783 			if (rc != MBX_SUCCESS)
8784 				lpfc_printf_log(phba, KERN_WARNING,
8785 					LOG_MBOX | LOG_SLI,
8786 					"(%d):2597 Sync Mailbox command "
8787 					"x%x (x%x/x%x) failure: "
8788 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
8789 					"Data: x%x x%x\n,",
8790 					mboxq->vport ? mboxq->vport->vpi : 0,
8791 					mboxq->u.mb.mbxCommand,
8792 					lpfc_sli_config_mbox_subsys_get(phba,
8793 									mboxq),
8794 					lpfc_sli_config_mbox_opcode_get(phba,
8795 									mboxq),
8796 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
8797 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
8798 					bf_get(lpfc_mcqe_ext_status,
8799 					       &mboxq->mcqe),
8800 					psli->sli_flag, flag);
8801 			/* Unblock the async mailbox posting afterward */
8802 			lpfc_sli4_async_mbox_unblock(phba);
8803 		}
8804 		return rc;
8805 	}
8806 
8807 	/* Now, interrupt mode asynchronous mailbox command */
8808 	rc = lpfc_mbox_cmd_check(phba, mboxq);
8809 	if (rc) {
8810 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8811 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
8812 				"cannot issue Data: x%x x%x\n",
8813 				mboxq->vport ? mboxq->vport->vpi : 0,
8814 				mboxq->u.mb.mbxCommand,
8815 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8816 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8817 				psli->sli_flag, flag);
8818 		goto out_not_finished;
8819 	}
8820 
8821 	/* Put the mailbox command to the driver internal FIFO */
8822 	psli->slistat.mbox_busy++;
8823 	spin_lock_irqsave(&phba->hbalock, iflags);
8824 	lpfc_mbox_put(phba, mboxq);
8825 	spin_unlock_irqrestore(&phba->hbalock, iflags);
8826 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8827 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
8828 			"x%x (x%x/x%x) x%x x%x x%x\n",
8829 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
8830 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8831 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8832 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8833 			phba->pport->port_state,
8834 			psli->sli_flag, MBX_NOWAIT);
8835 	/* Wake up worker thread to transport mailbox command from head */
8836 	lpfc_worker_wake_up(phba);
8837 
8838 	return MBX_BUSY;
8839 
8840 out_not_finished:
8841 	return MBX_NOT_FINISHED;
8842 }
8843 
8844 /**
8845  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
8846  * @phba: Pointer to HBA context object.
8847  *
8848  * This function is called by worker thread to send a mailbox command to
8849  * SLI4 HBA firmware.
8850  *
8851  **/
8852 int
8853 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
8854 {
8855 	struct lpfc_sli *psli = &phba->sli;
8856 	LPFC_MBOXQ_t *mboxq;
8857 	int rc = MBX_SUCCESS;
8858 	unsigned long iflags;
8859 	struct lpfc_mqe *mqe;
8860 	uint32_t mbx_cmnd;
8861 
8862 	/* Check interrupt mode before post async mailbox command */
8863 	if (unlikely(!phba->sli4_hba.intr_enable))
8864 		return MBX_NOT_FINISHED;
8865 
8866 	/* Check for mailbox command service token */
8867 	spin_lock_irqsave(&phba->hbalock, iflags);
8868 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8869 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8870 		return MBX_NOT_FINISHED;
8871 	}
8872 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8873 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8874 		return MBX_NOT_FINISHED;
8875 	}
8876 	if (unlikely(phba->sli.mbox_active)) {
8877 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8878 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8879 				"0384 There is pending active mailbox cmd\n");
8880 		return MBX_NOT_FINISHED;
8881 	}
8882 	/* Take the mailbox command service token */
8883 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8884 
8885 	/* Get the next mailbox command from head of queue */
8886 	mboxq = lpfc_mbox_get(phba);
8887 
8888 	/* If no more mailbox command waiting for post, we're done */
8889 	if (!mboxq) {
8890 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8891 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8892 		return MBX_SUCCESS;
8893 	}
8894 	phba->sli.mbox_active = mboxq;
8895 	spin_unlock_irqrestore(&phba->hbalock, iflags);
8896 
8897 	/* Check device readiness for posting mailbox command */
8898 	rc = lpfc_mbox_dev_check(phba);
8899 	if (unlikely(rc))
8900 		/* Driver clean routine will clean up pending mailbox */
8901 		goto out_not_finished;
8902 
8903 	/* Prepare the mbox command to be posted */
8904 	mqe = &mboxq->u.mqe;
8905 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
8906 
8907 	/* Start timer for the mbox_tmo and log some mailbox post messages */
8908 	mod_timer(&psli->mbox_tmo, (jiffies +
8909 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
8910 
8911 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8912 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
8913 			"x%x x%x\n",
8914 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
8915 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8916 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8917 			phba->pport->port_state, psli->sli_flag);
8918 
8919 	if (mbx_cmnd != MBX_HEARTBEAT) {
8920 		if (mboxq->vport) {
8921 			lpfc_debugfs_disc_trc(mboxq->vport,
8922 				LPFC_DISC_TRC_MBOX_VPORT,
8923 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
8924 				mbx_cmnd, mqe->un.mb_words[0],
8925 				mqe->un.mb_words[1]);
8926 		} else {
8927 			lpfc_debugfs_disc_trc(phba->pport,
8928 				LPFC_DISC_TRC_MBOX,
8929 				"MBOX Send: cmd:x%x mb:x%x x%x",
8930 				mbx_cmnd, mqe->un.mb_words[0],
8931 				mqe->un.mb_words[1]);
8932 		}
8933 	}
8934 	psli->slistat.mbox_cmd++;
8935 
8936 	/* Post the mailbox command to the port */
8937 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
8938 	if (rc != MBX_SUCCESS) {
8939 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8940 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
8941 				"cannot issue Data: x%x x%x\n",
8942 				mboxq->vport ? mboxq->vport->vpi : 0,
8943 				mboxq->u.mb.mbxCommand,
8944 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8945 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8946 				psli->sli_flag, MBX_NOWAIT);
8947 		goto out_not_finished;
8948 	}
8949 
8950 	return rc;
8951 
8952 out_not_finished:
8953 	spin_lock_irqsave(&phba->hbalock, iflags);
8954 	if (phba->sli.mbox_active) {
8955 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
8956 		__lpfc_mbox_cmpl_put(phba, mboxq);
8957 		/* Release the token */
8958 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8959 		phba->sli.mbox_active = NULL;
8960 	}
8961 	spin_unlock_irqrestore(&phba->hbalock, iflags);
8962 
8963 	return MBX_NOT_FINISHED;
8964 }
8965 
8966 /**
8967  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
8968  * @phba: Pointer to HBA context object.
8969  * @pmbox: Pointer to mailbox object.
8970  * @flag: Flag indicating how the mailbox need to be processed.
8971  *
8972  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
8973  * the API jump table function pointer from the lpfc_hba struct.
8974  *
8975  * Return codes the caller owns the mailbox command after the return of the
8976  * function.
8977  **/
8978 int
8979 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
8980 {
8981 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
8982 }
8983 
8984 /**
8985  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
8986  * @phba: The hba struct for which this call is being executed.
8987  * @dev_grp: The HBA PCI-Device group number.
8988  *
8989  * This routine sets up the mbox interface API function jump table in @phba
8990  * struct.
8991  * Returns: 0 - success, -ENODEV - failure.
8992  **/
8993 int
8994 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8995 {
8996 
8997 	switch (dev_grp) {
8998 	case LPFC_PCI_DEV_LP:
8999 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
9000 		phba->lpfc_sli_handle_slow_ring_event =
9001 				lpfc_sli_handle_slow_ring_event_s3;
9002 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
9003 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
9004 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
9005 		break;
9006 	case LPFC_PCI_DEV_OC:
9007 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
9008 		phba->lpfc_sli_handle_slow_ring_event =
9009 				lpfc_sli_handle_slow_ring_event_s4;
9010 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
9011 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
9012 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
9013 		break;
9014 	default:
9015 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9016 				"1420 Invalid HBA PCI-device group: 0x%x\n",
9017 				dev_grp);
9018 		return -ENODEV;
9019 		break;
9020 	}
9021 	return 0;
9022 }
9023 
9024 /**
9025  * __lpfc_sli_ringtx_put - Add an iocb to the txq
9026  * @phba: Pointer to HBA context object.
9027  * @pring: Pointer to driver SLI ring object.
9028  * @piocb: Pointer to address of newly added command iocb.
9029  *
9030  * This function is called with hbalock held for SLI3 ports or
9031  * the ring lock held for SLI4 ports to add a command
9032  * iocb to the txq when SLI layer cannot submit the command iocb
9033  * to the ring.
9034  **/
9035 void
9036 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9037 		    struct lpfc_iocbq *piocb)
9038 {
9039 	if (phba->sli_rev == LPFC_SLI_REV4)
9040 		lockdep_assert_held(&pring->ring_lock);
9041 	else
9042 		lockdep_assert_held(&phba->hbalock);
9043 	/* Insert the caller's iocb in the txq tail for later processing. */
9044 	list_add_tail(&piocb->list, &pring->txq);
9045 }
9046 
9047 /**
9048  * lpfc_sli_next_iocb - Get the next iocb in the txq
9049  * @phba: Pointer to HBA context object.
9050  * @pring: Pointer to driver SLI ring object.
9051  * @piocb: Pointer to address of newly added command iocb.
9052  *
9053  * This function is called with hbalock held before a new
9054  * iocb is submitted to the firmware. This function checks
9055  * txq to flush the iocbs in txq to Firmware before
9056  * submitting new iocbs to the Firmware.
9057  * If there are iocbs in the txq which need to be submitted
9058  * to firmware, lpfc_sli_next_iocb returns the first element
9059  * of the txq after dequeuing it from txq.
9060  * If there is no iocb in the txq then the function will return
9061  * *piocb and *piocb is set to NULL. Caller needs to check
9062  * *piocb to find if there are more commands in the txq.
9063  **/
9064 static struct lpfc_iocbq *
9065 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9066 		   struct lpfc_iocbq **piocb)
9067 {
9068 	struct lpfc_iocbq * nextiocb;
9069 
9070 	lockdep_assert_held(&phba->hbalock);
9071 
9072 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
9073 	if (!nextiocb) {
9074 		nextiocb = *piocb;
9075 		*piocb = NULL;
9076 	}
9077 
9078 	return nextiocb;
9079 }
9080 
9081 /**
9082  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
9083  * @phba: Pointer to HBA context object.
9084  * @ring_number: SLI ring number to issue iocb on.
9085  * @piocb: Pointer to command iocb.
9086  * @flag: Flag indicating if this command can be put into txq.
9087  *
9088  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
9089  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
9090  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
9091  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
9092  * this function allows only iocbs for posting buffers. This function finds
9093  * next available slot in the command ring and posts the command to the
9094  * available slot and writes the port attention register to request HBA start
9095  * processing new iocb. If there is no slot available in the ring and
9096  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
9097  * the function returns IOCB_BUSY.
9098  *
9099  * This function is called with hbalock held. The function will return success
9100  * after it successfully submit the iocb to firmware or after adding to the
9101  * txq.
9102  **/
9103 static int
9104 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
9105 		    struct lpfc_iocbq *piocb, uint32_t flag)
9106 {
9107 	struct lpfc_iocbq *nextiocb;
9108 	IOCB_t *iocb;
9109 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
9110 
9111 	lockdep_assert_held(&phba->hbalock);
9112 
9113 	if (piocb->iocb_cmpl && (!piocb->vport) &&
9114 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
9115 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
9116 		lpfc_printf_log(phba, KERN_ERR,
9117 				LOG_SLI | LOG_VPORT,
9118 				"1807 IOCB x%x failed. No vport\n",
9119 				piocb->iocb.ulpCommand);
9120 		dump_stack();
9121 		return IOCB_ERROR;
9122 	}
9123 
9124 
9125 	/* If the PCI channel is in offline state, do not post iocbs. */
9126 	if (unlikely(pci_channel_offline(phba->pcidev)))
9127 		return IOCB_ERROR;
9128 
9129 	/* If HBA has a deferred error attention, fail the iocb. */
9130 	if (unlikely(phba->hba_flag & DEFER_ERATT))
9131 		return IOCB_ERROR;
9132 
9133 	/*
9134 	 * We should never get an IOCB if we are in a < LINK_DOWN state
9135 	 */
9136 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
9137 		return IOCB_ERROR;
9138 
9139 	/*
9140 	 * Check to see if we are blocking IOCB processing because of a
9141 	 * outstanding event.
9142 	 */
9143 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
9144 		goto iocb_busy;
9145 
9146 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
9147 		/*
9148 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
9149 		 * can be issued if the link is not up.
9150 		 */
9151 		switch (piocb->iocb.ulpCommand) {
9152 		case CMD_GEN_REQUEST64_CR:
9153 		case CMD_GEN_REQUEST64_CX:
9154 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
9155 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
9156 					FC_RCTL_DD_UNSOL_CMD) ||
9157 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
9158 					MENLO_TRANSPORT_TYPE))
9159 
9160 				goto iocb_busy;
9161 			break;
9162 		case CMD_QUE_RING_BUF_CN:
9163 		case CMD_QUE_RING_BUF64_CN:
9164 			/*
9165 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
9166 			 * completion, iocb_cmpl MUST be 0.
9167 			 */
9168 			if (piocb->iocb_cmpl)
9169 				piocb->iocb_cmpl = NULL;
9170 			/*FALLTHROUGH*/
9171 		case CMD_CREATE_XRI_CR:
9172 		case CMD_CLOSE_XRI_CN:
9173 		case CMD_CLOSE_XRI_CX:
9174 			break;
9175 		default:
9176 			goto iocb_busy;
9177 		}
9178 
9179 	/*
9180 	 * For FCP commands, we must be in a state where we can process link
9181 	 * attention events.
9182 	 */
9183 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
9184 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
9185 		goto iocb_busy;
9186 	}
9187 
9188 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
9189 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
9190 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
9191 
9192 	if (iocb)
9193 		lpfc_sli_update_ring(phba, pring);
9194 	else
9195 		lpfc_sli_update_full_ring(phba, pring);
9196 
9197 	if (!piocb)
9198 		return IOCB_SUCCESS;
9199 
9200 	goto out_busy;
9201 
9202  iocb_busy:
9203 	pring->stats.iocb_cmd_delay++;
9204 
9205  out_busy:
9206 
9207 	if (!(flag & SLI_IOCB_RET_IOCB)) {
9208 		__lpfc_sli_ringtx_put(phba, pring, piocb);
9209 		return IOCB_SUCCESS;
9210 	}
9211 
9212 	return IOCB_BUSY;
9213 }
9214 
9215 /**
9216  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
9217  * @phba: Pointer to HBA context object.
9218  * @piocb: Pointer to command iocb.
9219  * @sglq: Pointer to the scatter gather queue object.
9220  *
9221  * This routine converts the bpl or bde that is in the IOCB
9222  * to a sgl list for the sli4 hardware. The physical address
9223  * of the bpl/bde is converted back to a virtual address.
9224  * If the IOCB contains a BPL then the list of BDE's is
9225  * converted to sli4_sge's. If the IOCB contains a single
9226  * BDE then it is converted to a single sli_sge.
9227  * The IOCB is still in cpu endianess so the contents of
9228  * the bpl can be used without byte swapping.
9229  *
9230  * Returns valid XRI = Success, NO_XRI = Failure.
9231 **/
9232 static uint16_t
9233 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
9234 		struct lpfc_sglq *sglq)
9235 {
9236 	uint16_t xritag = NO_XRI;
9237 	struct ulp_bde64 *bpl = NULL;
9238 	struct ulp_bde64 bde;
9239 	struct sli4_sge *sgl  = NULL;
9240 	struct lpfc_dmabuf *dmabuf;
9241 	IOCB_t *icmd;
9242 	int numBdes = 0;
9243 	int i = 0;
9244 	uint32_t offset = 0; /* accumulated offset in the sg request list */
9245 	int inbound = 0; /* number of sg reply entries inbound from firmware */
9246 
9247 	if (!piocbq || !sglq)
9248 		return xritag;
9249 
9250 	sgl  = (struct sli4_sge *)sglq->sgl;
9251 	icmd = &piocbq->iocb;
9252 	if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
9253 		return sglq->sli4_xritag;
9254 	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9255 		numBdes = icmd->un.genreq64.bdl.bdeSize /
9256 				sizeof(struct ulp_bde64);
9257 		/* The addrHigh and addrLow fields within the IOCB
9258 		 * have not been byteswapped yet so there is no
9259 		 * need to swap them back.
9260 		 */
9261 		if (piocbq->context3)
9262 			dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
9263 		else
9264 			return xritag;
9265 
9266 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
9267 		if (!bpl)
9268 			return xritag;
9269 
9270 		for (i = 0; i < numBdes; i++) {
9271 			/* Should already be byte swapped. */
9272 			sgl->addr_hi = bpl->addrHigh;
9273 			sgl->addr_lo = bpl->addrLow;
9274 
9275 			sgl->word2 = le32_to_cpu(sgl->word2);
9276 			if ((i+1) == numBdes)
9277 				bf_set(lpfc_sli4_sge_last, sgl, 1);
9278 			else
9279 				bf_set(lpfc_sli4_sge_last, sgl, 0);
9280 			/* swap the size field back to the cpu so we
9281 			 * can assign it to the sgl.
9282 			 */
9283 			bde.tus.w = le32_to_cpu(bpl->tus.w);
9284 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
9285 			/* The offsets in the sgl need to be accumulated
9286 			 * separately for the request and reply lists.
9287 			 * The request is always first, the reply follows.
9288 			 */
9289 			if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
9290 				/* add up the reply sg entries */
9291 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
9292 					inbound++;
9293 				/* first inbound? reset the offset */
9294 				if (inbound == 1)
9295 					offset = 0;
9296 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
9297 				bf_set(lpfc_sli4_sge_type, sgl,
9298 					LPFC_SGE_TYPE_DATA);
9299 				offset += bde.tus.f.bdeSize;
9300 			}
9301 			sgl->word2 = cpu_to_le32(sgl->word2);
9302 			bpl++;
9303 			sgl++;
9304 		}
9305 	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
9306 			/* The addrHigh and addrLow fields of the BDE have not
9307 			 * been byteswapped yet so they need to be swapped
9308 			 * before putting them in the sgl.
9309 			 */
9310 			sgl->addr_hi =
9311 				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
9312 			sgl->addr_lo =
9313 				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
9314 			sgl->word2 = le32_to_cpu(sgl->word2);
9315 			bf_set(lpfc_sli4_sge_last, sgl, 1);
9316 			sgl->word2 = cpu_to_le32(sgl->word2);
9317 			sgl->sge_len =
9318 				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
9319 	}
9320 	return sglq->sli4_xritag;
9321 }
9322 
9323 /**
9324  * lpfc_sli_iocb2wqe - Convert the IOCB to a work queue entry.
9325  * @phba: Pointer to HBA context object.
9326  * @piocb: Pointer to command iocb.
9327  * @wqe: Pointer to the work queue entry.
9328  *
9329  * This routine converts the iocb command to its Work Queue Entry
9330  * equivalent. The wqe pointer should not have any fields set when
9331  * this routine is called because it will memcpy over them.
9332  * This routine does not set the CQ_ID or the WQEC bits in the
9333  * wqe.
9334  *
9335  * Returns: 0 = Success, IOCB_ERROR = Failure.
9336  **/
9337 static int
9338 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
9339 		union lpfc_wqe128 *wqe)
9340 {
9341 	uint32_t xmit_len = 0, total_len = 0;
9342 	uint8_t ct = 0;
9343 	uint32_t fip;
9344 	uint32_t abort_tag;
9345 	uint8_t command_type = ELS_COMMAND_NON_FIP;
9346 	uint8_t cmnd;
9347 	uint16_t xritag;
9348 	uint16_t abrt_iotag;
9349 	struct lpfc_iocbq *abrtiocbq;
9350 	struct ulp_bde64 *bpl = NULL;
9351 	uint32_t els_id = LPFC_ELS_ID_DEFAULT;
9352 	int numBdes, i;
9353 	struct ulp_bde64 bde;
9354 	struct lpfc_nodelist *ndlp;
9355 	uint32_t *pcmd;
9356 	uint32_t if_type;
9357 
9358 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
9359 	/* The fcp commands will set command type */
9360 	if (iocbq->iocb_flag &  LPFC_IO_FCP)
9361 		command_type = FCP_COMMAND;
9362 	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
9363 		command_type = ELS_COMMAND_FIP;
9364 	else
9365 		command_type = ELS_COMMAND_NON_FIP;
9366 
9367 	if (phba->fcp_embed_io)
9368 		memset(wqe, 0, sizeof(union lpfc_wqe128));
9369 	/* Some of the fields are in the right position already */
9370 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
9371 	/* The ct field has moved so reset */
9372 	wqe->generic.wqe_com.word7 = 0;
9373 	wqe->generic.wqe_com.word10 = 0;
9374 
9375 	abort_tag = (uint32_t) iocbq->iotag;
9376 	xritag = iocbq->sli4_xritag;
9377 	/* words0-2 bpl convert bde */
9378 	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9379 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
9380 				sizeof(struct ulp_bde64);
9381 		bpl  = (struct ulp_bde64 *)
9382 			((struct lpfc_dmabuf *)iocbq->context3)->virt;
9383 		if (!bpl)
9384 			return IOCB_ERROR;
9385 
9386 		/* Should already be byte swapped. */
9387 		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
9388 		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
9389 		/* swap the size field back to the cpu so we
9390 		 * can assign it to the sgl.
9391 		 */
9392 		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
9393 		xmit_len = wqe->generic.bde.tus.f.bdeSize;
9394 		total_len = 0;
9395 		for (i = 0; i < numBdes; i++) {
9396 			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
9397 			total_len += bde.tus.f.bdeSize;
9398 		}
9399 	} else
9400 		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
9401 
9402 	iocbq->iocb.ulpIoTag = iocbq->iotag;
9403 	cmnd = iocbq->iocb.ulpCommand;
9404 
9405 	switch (iocbq->iocb.ulpCommand) {
9406 	case CMD_ELS_REQUEST64_CR:
9407 		if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
9408 			ndlp = iocbq->context_un.ndlp;
9409 		else
9410 			ndlp = (struct lpfc_nodelist *)iocbq->context1;
9411 		if (!iocbq->iocb.ulpLe) {
9412 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9413 				"2007 Only Limited Edition cmd Format"
9414 				" supported 0x%x\n",
9415 				iocbq->iocb.ulpCommand);
9416 			return IOCB_ERROR;
9417 		}
9418 
9419 		wqe->els_req.payload_len = xmit_len;
9420 		/* Els_reguest64 has a TMO */
9421 		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
9422 			iocbq->iocb.ulpTimeout);
9423 		/* Need a VF for word 4 set the vf bit*/
9424 		bf_set(els_req64_vf, &wqe->els_req, 0);
9425 		/* And a VFID for word 12 */
9426 		bf_set(els_req64_vfid, &wqe->els_req, 0);
9427 		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
9428 		bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9429 		       iocbq->iocb.ulpContext);
9430 		bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
9431 		bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
9432 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
9433 		if (command_type == ELS_COMMAND_FIP)
9434 			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
9435 					>> LPFC_FIP_ELS_ID_SHIFT);
9436 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9437 					iocbq->context2)->virt);
9438 		if_type = bf_get(lpfc_sli_intf_if_type,
9439 					&phba->sli4_hba.sli_intf);
9440 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9441 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
9442 				*pcmd == ELS_CMD_SCR ||
9443 				*pcmd == ELS_CMD_RDF ||
9444 				*pcmd == ELS_CMD_RSCN_XMT ||
9445 				*pcmd == ELS_CMD_FDISC ||
9446 				*pcmd == ELS_CMD_LOGO ||
9447 				*pcmd == ELS_CMD_PLOGI)) {
9448 				bf_set(els_req64_sp, &wqe->els_req, 1);
9449 				bf_set(els_req64_sid, &wqe->els_req,
9450 					iocbq->vport->fc_myDID);
9451 				if ((*pcmd == ELS_CMD_FLOGI) &&
9452 					!(phba->fc_topology ==
9453 						LPFC_TOPOLOGY_LOOP))
9454 					bf_set(els_req64_sid, &wqe->els_req, 0);
9455 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
9456 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9457 					phba->vpi_ids[iocbq->vport->vpi]);
9458 			} else if (pcmd && iocbq->context1) {
9459 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
9460 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9461 					phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9462 			}
9463 		}
9464 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
9465 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9466 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
9467 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
9468 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
9469 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
9470 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
9471 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
9472 		wqe->els_req.max_response_payload_len = total_len - xmit_len;
9473 		break;
9474 	case CMD_XMIT_SEQUENCE64_CX:
9475 		bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
9476 		       iocbq->iocb.un.ulpWord[3]);
9477 		bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
9478 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
9479 		/* The entire sequence is transmitted for this IOCB */
9480 		xmit_len = total_len;
9481 		cmnd = CMD_XMIT_SEQUENCE64_CR;
9482 		if (phba->link_flag & LS_LOOPBACK_MODE)
9483 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
9484 		/* fall through */
9485 	case CMD_XMIT_SEQUENCE64_CR:
9486 		/* word3 iocb=io_tag32 wqe=reserved */
9487 		wqe->xmit_sequence.rsvd3 = 0;
9488 		/* word4 relative_offset memcpy */
9489 		/* word5 r_ctl/df_ctl memcpy */
9490 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
9491 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
9492 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
9493 		       LPFC_WQE_IOD_WRITE);
9494 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
9495 		       LPFC_WQE_LENLOC_WORD12);
9496 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
9497 		wqe->xmit_sequence.xmit_len = xmit_len;
9498 		command_type = OTHER_COMMAND;
9499 		break;
9500 	case CMD_XMIT_BCAST64_CN:
9501 		/* word3 iocb=iotag32 wqe=seq_payload_len */
9502 		wqe->xmit_bcast64.seq_payload_len = xmit_len;
9503 		/* word4 iocb=rsvd wqe=rsvd */
9504 		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
9505 		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
9506 		bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
9507 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9508 		bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
9509 		bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
9510 		bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
9511 		       LPFC_WQE_LENLOC_WORD3);
9512 		bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
9513 		break;
9514 	case CMD_FCP_IWRITE64_CR:
9515 		command_type = FCP_COMMAND_DATA_OUT;
9516 		/* word3 iocb=iotag wqe=payload_offset_len */
9517 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9518 		bf_set(payload_offset_len, &wqe->fcp_iwrite,
9519 		       xmit_len + sizeof(struct fcp_rsp));
9520 		bf_set(cmd_buff_len, &wqe->fcp_iwrite,
9521 		       0);
9522 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9523 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9524 		bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
9525 		       iocbq->iocb.ulpFCP2Rcvy);
9526 		bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
9527 		/* Always open the exchange */
9528 		bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
9529 		bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
9530 		       LPFC_WQE_LENLOC_WORD4);
9531 		bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
9532 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
9533 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9534 			bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
9535 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
9536 			if (iocbq->priority) {
9537 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9538 				       (iocbq->priority << 1));
9539 			} else {
9540 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9541 				       (phba->cfg_XLanePriority << 1));
9542 			}
9543 		}
9544 		/* Note, word 10 is already initialized to 0 */
9545 
9546 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9547 		if (phba->cfg_enable_pbde)
9548 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 1);
9549 		else
9550 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
9551 
9552 		if (phba->fcp_embed_io) {
9553 			struct lpfc_io_buf *lpfc_cmd;
9554 			struct sli4_sge *sgl;
9555 			struct fcp_cmnd *fcp_cmnd;
9556 			uint32_t *ptr;
9557 
9558 			/* 128 byte wqe support here */
9559 
9560 			lpfc_cmd = iocbq->context1;
9561 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9562 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9563 
9564 			/* Word 0-2 - FCP_CMND */
9565 			wqe->generic.bde.tus.f.bdeFlags =
9566 				BUFF_TYPE_BDE_IMMED;
9567 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9568 			wqe->generic.bde.addrHigh = 0;
9569 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9570 
9571 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
9572 			bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
9573 
9574 			/* Word 22-29  FCP CMND Payload */
9575 			ptr = &wqe->words[22];
9576 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9577 		}
9578 		break;
9579 	case CMD_FCP_IREAD64_CR:
9580 		/* word3 iocb=iotag wqe=payload_offset_len */
9581 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9582 		bf_set(payload_offset_len, &wqe->fcp_iread,
9583 		       xmit_len + sizeof(struct fcp_rsp));
9584 		bf_set(cmd_buff_len, &wqe->fcp_iread,
9585 		       0);
9586 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9587 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9588 		bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
9589 		       iocbq->iocb.ulpFCP2Rcvy);
9590 		bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
9591 		/* Always open the exchange */
9592 		bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
9593 		bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
9594 		       LPFC_WQE_LENLOC_WORD4);
9595 		bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
9596 		bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
9597 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9598 			bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
9599 			bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
9600 			if (iocbq->priority) {
9601 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9602 				       (iocbq->priority << 1));
9603 			} else {
9604 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9605 				       (phba->cfg_XLanePriority << 1));
9606 			}
9607 		}
9608 		/* Note, word 10 is already initialized to 0 */
9609 
9610 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9611 		if (phba->cfg_enable_pbde)
9612 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 1);
9613 		else
9614 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
9615 
9616 		if (phba->fcp_embed_io) {
9617 			struct lpfc_io_buf *lpfc_cmd;
9618 			struct sli4_sge *sgl;
9619 			struct fcp_cmnd *fcp_cmnd;
9620 			uint32_t *ptr;
9621 
9622 			/* 128 byte wqe support here */
9623 
9624 			lpfc_cmd = iocbq->context1;
9625 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9626 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9627 
9628 			/* Word 0-2 - FCP_CMND */
9629 			wqe->generic.bde.tus.f.bdeFlags =
9630 				BUFF_TYPE_BDE_IMMED;
9631 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9632 			wqe->generic.bde.addrHigh = 0;
9633 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9634 
9635 			bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
9636 			bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
9637 
9638 			/* Word 22-29  FCP CMND Payload */
9639 			ptr = &wqe->words[22];
9640 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9641 		}
9642 		break;
9643 	case CMD_FCP_ICMND64_CR:
9644 		/* word3 iocb=iotag wqe=payload_offset_len */
9645 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9646 		bf_set(payload_offset_len, &wqe->fcp_icmd,
9647 		       xmit_len + sizeof(struct fcp_rsp));
9648 		bf_set(cmd_buff_len, &wqe->fcp_icmd,
9649 		       0);
9650 		/* word3 iocb=IO_TAG wqe=reserved */
9651 		bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
9652 		/* Always open the exchange */
9653 		bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
9654 		bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
9655 		bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
9656 		bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
9657 		       LPFC_WQE_LENLOC_NONE);
9658 		bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
9659 		       iocbq->iocb.ulpFCP2Rcvy);
9660 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9661 			bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
9662 			bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
9663 			if (iocbq->priority) {
9664 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9665 				       (iocbq->priority << 1));
9666 			} else {
9667 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9668 				       (phba->cfg_XLanePriority << 1));
9669 			}
9670 		}
9671 		/* Note, word 10 is already initialized to 0 */
9672 
9673 		if (phba->fcp_embed_io) {
9674 			struct lpfc_io_buf *lpfc_cmd;
9675 			struct sli4_sge *sgl;
9676 			struct fcp_cmnd *fcp_cmnd;
9677 			uint32_t *ptr;
9678 
9679 			/* 128 byte wqe support here */
9680 
9681 			lpfc_cmd = iocbq->context1;
9682 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9683 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9684 
9685 			/* Word 0-2 - FCP_CMND */
9686 			wqe->generic.bde.tus.f.bdeFlags =
9687 				BUFF_TYPE_BDE_IMMED;
9688 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9689 			wqe->generic.bde.addrHigh = 0;
9690 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9691 
9692 			bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
9693 			bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
9694 
9695 			/* Word 22-29  FCP CMND Payload */
9696 			ptr = &wqe->words[22];
9697 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9698 		}
9699 		break;
9700 	case CMD_GEN_REQUEST64_CR:
9701 		/* For this command calculate the xmit length of the
9702 		 * request bde.
9703 		 */
9704 		xmit_len = 0;
9705 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
9706 			sizeof(struct ulp_bde64);
9707 		for (i = 0; i < numBdes; i++) {
9708 			bde.tus.w = le32_to_cpu(bpl[i].tus.w);
9709 			if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
9710 				break;
9711 			xmit_len += bde.tus.f.bdeSize;
9712 		}
9713 		/* word3 iocb=IO_TAG wqe=request_payload_len */
9714 		wqe->gen_req.request_payload_len = xmit_len;
9715 		/* word4 iocb=parameter wqe=relative_offset memcpy */
9716 		/* word5 [rctl, type, df_ctl, la] copied in memcpy */
9717 		/* word6 context tag copied in memcpy */
9718 		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
9719 			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
9720 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9721 				"2015 Invalid CT %x command 0x%x\n",
9722 				ct, iocbq->iocb.ulpCommand);
9723 			return IOCB_ERROR;
9724 		}
9725 		bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
9726 		bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
9727 		bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
9728 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
9729 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
9730 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
9731 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
9732 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
9733 		wqe->gen_req.max_response_payload_len = total_len - xmit_len;
9734 		command_type = OTHER_COMMAND;
9735 		break;
9736 	case CMD_XMIT_ELS_RSP64_CX:
9737 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
9738 		/* words0-2 BDE memcpy */
9739 		/* word3 iocb=iotag32 wqe=response_payload_len */
9740 		wqe->xmit_els_rsp.response_payload_len = xmit_len;
9741 		/* word4 */
9742 		wqe->xmit_els_rsp.word4 = 0;
9743 		/* word5 iocb=rsvd wge=did */
9744 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
9745 			 iocbq->iocb.un.xseq64.xmit_els_remoteID);
9746 
9747 		if_type = bf_get(lpfc_sli_intf_if_type,
9748 					&phba->sli4_hba.sli_intf);
9749 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9750 			if (iocbq->vport->fc_flag & FC_PT2PT) {
9751 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
9752 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
9753 					iocbq->vport->fc_myDID);
9754 				if (iocbq->vport->fc_myDID == Fabric_DID) {
9755 					bf_set(wqe_els_did,
9756 						&wqe->xmit_els_rsp.wqe_dest, 0);
9757 				}
9758 			}
9759 		}
9760 		bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
9761 		       ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9762 		bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
9763 		bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
9764 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
9765 		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
9766 			bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
9767 			       phba->vpi_ids[iocbq->vport->vpi]);
9768 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
9769 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
9770 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
9771 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
9772 		       LPFC_WQE_LENLOC_WORD3);
9773 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
9774 		bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
9775 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9776 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9777 					iocbq->context2)->virt);
9778 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
9779 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
9780 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
9781 					iocbq->vport->fc_myDID);
9782 				bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
9783 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
9784 					phba->vpi_ids[phba->pport->vpi]);
9785 		}
9786 		command_type = OTHER_COMMAND;
9787 		break;
9788 	case CMD_CLOSE_XRI_CN:
9789 	case CMD_ABORT_XRI_CN:
9790 	case CMD_ABORT_XRI_CX:
9791 		/* words 0-2 memcpy should be 0 rserved */
9792 		/* port will send abts */
9793 		abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
9794 		if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
9795 			abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
9796 			fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
9797 		} else
9798 			fip = 0;
9799 
9800 		if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
9801 			/*
9802 			 * The link is down, or the command was ELS_FIP
9803 			 * so the fw does not need to send abts
9804 			 * on the wire.
9805 			 */
9806 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
9807 		else
9808 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
9809 		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
9810 		/* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
9811 		wqe->abort_cmd.rsrvd5 = 0;
9812 		bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
9813 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9814 		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
9815 		/*
9816 		 * The abort handler will send us CMD_ABORT_XRI_CN or
9817 		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
9818 		 */
9819 		bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
9820 		bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
9821 		bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
9822 		       LPFC_WQE_LENLOC_NONE);
9823 		cmnd = CMD_ABORT_XRI_CX;
9824 		command_type = OTHER_COMMAND;
9825 		xritag = 0;
9826 		break;
9827 	case CMD_XMIT_BLS_RSP64_CX:
9828 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
9829 		/* As BLS ABTS RSP WQE is very different from other WQEs,
9830 		 * we re-construct this WQE here based on information in
9831 		 * iocbq from scratch.
9832 		 */
9833 		memset(wqe, 0, sizeof(*wqe));
9834 		/* OX_ID is invariable to who sent ABTS to CT exchange */
9835 		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
9836 		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
9837 		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
9838 		    LPFC_ABTS_UNSOL_INT) {
9839 			/* ABTS sent by initiator to CT exchange, the
9840 			 * RX_ID field will be filled with the newly
9841 			 * allocated responder XRI.
9842 			 */
9843 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
9844 			       iocbq->sli4_xritag);
9845 		} else {
9846 			/* ABTS sent by responder to CT exchange, the
9847 			 * RX_ID field will be filled with the responder
9848 			 * RX_ID from ABTS.
9849 			 */
9850 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
9851 			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
9852 		}
9853 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
9854 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
9855 
9856 		/* Use CT=VPI */
9857 		bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
9858 			ndlp->nlp_DID);
9859 		bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
9860 			iocbq->iocb.ulpContext);
9861 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
9862 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
9863 			phba->vpi_ids[phba->pport->vpi]);
9864 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
9865 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
9866 		       LPFC_WQE_LENLOC_NONE);
9867 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
9868 		command_type = OTHER_COMMAND;
9869 		if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
9870 			bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
9871 			       bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
9872 			bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
9873 			       bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
9874 			bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
9875 			       bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
9876 		}
9877 
9878 		break;
9879 	case CMD_SEND_FRAME:
9880 		bf_set(wqe_cmnd, &wqe->generic.wqe_com, CMD_SEND_FRAME);
9881 		bf_set(wqe_sof, &wqe->generic.wqe_com, 0x2E); /* SOF byte */
9882 		bf_set(wqe_eof, &wqe->generic.wqe_com, 0x41); /* EOF byte */
9883 		bf_set(wqe_lenloc, &wqe->generic.wqe_com, 1);
9884 		bf_set(wqe_xbl, &wqe->generic.wqe_com, 1);
9885 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
9886 		bf_set(wqe_xc, &wqe->generic.wqe_com, 1);
9887 		bf_set(wqe_cmd_type, &wqe->generic.wqe_com, 0xA);
9888 		bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
9889 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
9890 		bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
9891 		return 0;
9892 	case CMD_XRI_ABORTED_CX:
9893 	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
9894 	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
9895 	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
9896 	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
9897 	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
9898 	default:
9899 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9900 				"2014 Invalid command 0x%x\n",
9901 				iocbq->iocb.ulpCommand);
9902 		return IOCB_ERROR;
9903 		break;
9904 	}
9905 
9906 	if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
9907 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
9908 	else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
9909 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
9910 	else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
9911 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
9912 	iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
9913 			      LPFC_IO_DIF_INSERT);
9914 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
9915 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
9916 	wqe->generic.wqe_com.abort_tag = abort_tag;
9917 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
9918 	bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
9919 	bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
9920 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
9921 	return 0;
9922 }
9923 
9924 /**
9925  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
9926  * @phba: Pointer to HBA context object.
9927  * @ring_number: SLI ring number to issue iocb on.
9928  * @piocb: Pointer to command iocb.
9929  * @flag: Flag indicating if this command can be put into txq.
9930  *
9931  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
9932  * an iocb command to an HBA with SLI-4 interface spec.
9933  *
9934  * This function is called with ringlock held. The function will return success
9935  * after it successfully submit the iocb to firmware or after adding to the
9936  * txq.
9937  **/
9938 static int
9939 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
9940 			 struct lpfc_iocbq *piocb, uint32_t flag)
9941 {
9942 	struct lpfc_sglq *sglq;
9943 	union lpfc_wqe128 wqe;
9944 	struct lpfc_queue *wq;
9945 	struct lpfc_sli_ring *pring;
9946 
9947 	/* Get the WQ */
9948 	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
9949 	    (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
9950 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
9951 	} else {
9952 		wq = phba->sli4_hba.els_wq;
9953 	}
9954 
9955 	/* Get corresponding ring */
9956 	pring = wq->pring;
9957 
9958 	/*
9959 	 * The WQE can be either 64 or 128 bytes,
9960 	 */
9961 
9962 	lockdep_assert_held(&pring->ring_lock);
9963 
9964 	if (piocb->sli4_xritag == NO_XRI) {
9965 		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
9966 		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
9967 			sglq = NULL;
9968 		else {
9969 			if (!list_empty(&pring->txq)) {
9970 				if (!(flag & SLI_IOCB_RET_IOCB)) {
9971 					__lpfc_sli_ringtx_put(phba,
9972 						pring, piocb);
9973 					return IOCB_SUCCESS;
9974 				} else {
9975 					return IOCB_BUSY;
9976 				}
9977 			} else {
9978 				sglq = __lpfc_sli_get_els_sglq(phba, piocb);
9979 				if (!sglq) {
9980 					if (!(flag & SLI_IOCB_RET_IOCB)) {
9981 						__lpfc_sli_ringtx_put(phba,
9982 								pring,
9983 								piocb);
9984 						return IOCB_SUCCESS;
9985 					} else
9986 						return IOCB_BUSY;
9987 				}
9988 			}
9989 		}
9990 	} else if (piocb->iocb_flag &  LPFC_IO_FCP)
9991 		/* These IO's already have an XRI and a mapped sgl. */
9992 		sglq = NULL;
9993 	else {
9994 		/*
9995 		 * This is a continuation of a commandi,(CX) so this
9996 		 * sglq is on the active list
9997 		 */
9998 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
9999 		if (!sglq)
10000 			return IOCB_ERROR;
10001 	}
10002 
10003 	if (sglq) {
10004 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10005 		piocb->sli4_xritag = sglq->sli4_xritag;
10006 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
10007 			return IOCB_ERROR;
10008 	}
10009 
10010 	if (lpfc_sli4_iocb2wqe(phba, piocb, &wqe))
10011 		return IOCB_ERROR;
10012 
10013 	if (lpfc_sli4_wq_put(wq, &wqe))
10014 		return IOCB_ERROR;
10015 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10016 
10017 	return 0;
10018 }
10019 
10020 /**
10021  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10022  *
10023  * This routine wraps the actual lockless version for issusing IOCB function
10024  * pointer from the lpfc_hba struct.
10025  *
10026  * Return codes:
10027  * IOCB_ERROR - Error
10028  * IOCB_SUCCESS - Success
10029  * IOCB_BUSY - Busy
10030  **/
10031 int
10032 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10033 		struct lpfc_iocbq *piocb, uint32_t flag)
10034 {
10035 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10036 }
10037 
10038 /**
10039  * lpfc_sli_api_table_setup - Set up sli api function jump table
10040  * @phba: The hba struct for which this call is being executed.
10041  * @dev_grp: The HBA PCI-Device group number.
10042  *
10043  * This routine sets up the SLI interface API function jump table in @phba
10044  * struct.
10045  * Returns: 0 - success, -ENODEV - failure.
10046  **/
10047 int
10048 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10049 {
10050 
10051 	switch (dev_grp) {
10052 	case LPFC_PCI_DEV_LP:
10053 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
10054 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
10055 		break;
10056 	case LPFC_PCI_DEV_OC:
10057 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
10058 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
10059 		break;
10060 	default:
10061 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10062 				"1419 Invalid HBA PCI-device group: 0x%x\n",
10063 				dev_grp);
10064 		return -ENODEV;
10065 		break;
10066 	}
10067 	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
10068 	return 0;
10069 }
10070 
10071 /**
10072  * lpfc_sli4_calc_ring - Calculates which ring to use
10073  * @phba: Pointer to HBA context object.
10074  * @piocb: Pointer to command iocb.
10075  *
10076  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
10077  * hba_wqidx, thus we need to calculate the corresponding ring.
10078  * Since ABORTS must go on the same WQ of the command they are
10079  * aborting, we use command's hba_wqidx.
10080  */
10081 struct lpfc_sli_ring *
10082 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
10083 {
10084 	struct lpfc_io_buf *lpfc_cmd;
10085 
10086 	if (piocb->iocb_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
10087 		if (unlikely(!phba->sli4_hba.hdwq))
10088 			return NULL;
10089 		/*
10090 		 * for abort iocb hba_wqidx should already
10091 		 * be setup based on what work queue we used.
10092 		 */
10093 		if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
10094 			lpfc_cmd = (struct lpfc_io_buf *)piocb->context1;
10095 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
10096 		}
10097 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
10098 	} else {
10099 		if (unlikely(!phba->sli4_hba.els_wq))
10100 			return NULL;
10101 		piocb->hba_wqidx = 0;
10102 		return phba->sli4_hba.els_wq->pring;
10103 	}
10104 }
10105 
10106 /**
10107  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
10108  * @phba: Pointer to HBA context object.
10109  * @pring: Pointer to driver SLI ring object.
10110  * @piocb: Pointer to command iocb.
10111  * @flag: Flag indicating if this command can be put into txq.
10112  *
10113  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
10114  * function. This function gets the hbalock and calls
10115  * __lpfc_sli_issue_iocb function and will return the error returned
10116  * by __lpfc_sli_issue_iocb function. This wrapper is used by
10117  * functions which do not hold hbalock.
10118  **/
10119 int
10120 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10121 		    struct lpfc_iocbq *piocb, uint32_t flag)
10122 {
10123 	struct lpfc_sli_ring *pring;
10124 	struct lpfc_queue *eq;
10125 	unsigned long iflags;
10126 	int rc;
10127 
10128 	if (phba->sli_rev == LPFC_SLI_REV4) {
10129 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
10130 
10131 		pring = lpfc_sli4_calc_ring(phba, piocb);
10132 		if (unlikely(pring == NULL))
10133 			return IOCB_ERROR;
10134 
10135 		spin_lock_irqsave(&pring->ring_lock, iflags);
10136 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10137 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
10138 
10139 		lpfc_sli4_poll_eq(eq, LPFC_POLL_FASTPATH);
10140 	} else {
10141 		/* For now, SLI2/3 will still use hbalock */
10142 		spin_lock_irqsave(&phba->hbalock, iflags);
10143 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10144 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10145 	}
10146 	return rc;
10147 }
10148 
10149 /**
10150  * lpfc_extra_ring_setup - Extra ring setup function
10151  * @phba: Pointer to HBA context object.
10152  *
10153  * This function is called while driver attaches with the
10154  * HBA to setup the extra ring. The extra ring is used
10155  * only when driver needs to support target mode functionality
10156  * or IP over FC functionalities.
10157  *
10158  * This function is called with no lock held. SLI3 only.
10159  **/
10160 static int
10161 lpfc_extra_ring_setup( struct lpfc_hba *phba)
10162 {
10163 	struct lpfc_sli *psli;
10164 	struct lpfc_sli_ring *pring;
10165 
10166 	psli = &phba->sli;
10167 
10168 	/* Adjust cmd/rsp ring iocb entries more evenly */
10169 
10170 	/* Take some away from the FCP ring */
10171 	pring = &psli->sli3_ring[LPFC_FCP_RING];
10172 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10173 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10174 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10175 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10176 
10177 	/* and give them to the extra ring */
10178 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
10179 
10180 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10181 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10182 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10183 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10184 
10185 	/* Setup default profile for this ring */
10186 	pring->iotag_max = 4096;
10187 	pring->num_mask = 1;
10188 	pring->prt[0].profile = 0;      /* Mask 0 */
10189 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
10190 	pring->prt[0].type = phba->cfg_multi_ring_type;
10191 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
10192 	return 0;
10193 }
10194 
10195 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
10196  * @phba: Pointer to HBA context object.
10197  * @iocbq: Pointer to iocb object.
10198  *
10199  * The async_event handler calls this routine when it receives
10200  * an ASYNC_STATUS_CN event from the port.  The port generates
10201  * this event when an Abort Sequence request to an rport fails
10202  * twice in succession.  The abort could be originated by the
10203  * driver or by the port.  The ABTS could have been for an ELS
10204  * or FCP IO.  The port only generates this event when an ABTS
10205  * fails to complete after one retry.
10206  */
10207 static void
10208 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
10209 			  struct lpfc_iocbq *iocbq)
10210 {
10211 	struct lpfc_nodelist *ndlp = NULL;
10212 	uint16_t rpi = 0, vpi = 0;
10213 	struct lpfc_vport *vport = NULL;
10214 
10215 	/* The rpi in the ulpContext is vport-sensitive. */
10216 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
10217 	rpi = iocbq->iocb.ulpContext;
10218 
10219 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10220 			"3092 Port generated ABTS async event "
10221 			"on vpi %d rpi %d status 0x%x\n",
10222 			vpi, rpi, iocbq->iocb.ulpStatus);
10223 
10224 	vport = lpfc_find_vport_by_vpid(phba, vpi);
10225 	if (!vport)
10226 		goto err_exit;
10227 	ndlp = lpfc_findnode_rpi(vport, rpi);
10228 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp))
10229 		goto err_exit;
10230 
10231 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
10232 		lpfc_sli_abts_recover_port(vport, ndlp);
10233 	return;
10234 
10235  err_exit:
10236 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10237 			"3095 Event Context not found, no "
10238 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
10239 			iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
10240 			vpi, rpi);
10241 }
10242 
10243 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
10244  * @phba: pointer to HBA context object.
10245  * @ndlp: nodelist pointer for the impacted rport.
10246  * @axri: pointer to the wcqe containing the failed exchange.
10247  *
10248  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
10249  * port.  The port generates this event when an abort exchange request to an
10250  * rport fails twice in succession with no reply.  The abort could be originated
10251  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
10252  */
10253 void
10254 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
10255 			   struct lpfc_nodelist *ndlp,
10256 			   struct sli4_wcqe_xri_aborted *axri)
10257 {
10258 	struct lpfc_vport *vport;
10259 	uint32_t ext_status = 0;
10260 
10261 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
10262 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10263 				"3115 Node Context not found, driver "
10264 				"ignoring abts err event\n");
10265 		return;
10266 	}
10267 
10268 	vport = ndlp->vport;
10269 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10270 			"3116 Port generated FCP XRI ABORT event on "
10271 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
10272 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
10273 			bf_get(lpfc_wcqe_xa_xri, axri),
10274 			bf_get(lpfc_wcqe_xa_status, axri),
10275 			axri->parameter);
10276 
10277 	/*
10278 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
10279 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
10280 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
10281 	 */
10282 	ext_status = axri->parameter & IOERR_PARAM_MASK;
10283 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
10284 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
10285 		lpfc_sli_abts_recover_port(vport, ndlp);
10286 }
10287 
10288 /**
10289  * lpfc_sli_async_event_handler - ASYNC iocb handler function
10290  * @phba: Pointer to HBA context object.
10291  * @pring: Pointer to driver SLI ring object.
10292  * @iocbq: Pointer to iocb object.
10293  *
10294  * This function is called by the slow ring event handler
10295  * function when there is an ASYNC event iocb in the ring.
10296  * This function is called with no lock held.
10297  * Currently this function handles only temperature related
10298  * ASYNC events. The function decodes the temperature sensor
10299  * event message and posts events for the management applications.
10300  **/
10301 static void
10302 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
10303 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
10304 {
10305 	IOCB_t *icmd;
10306 	uint16_t evt_code;
10307 	struct temp_event temp_event_data;
10308 	struct Scsi_Host *shost;
10309 	uint32_t *iocb_w;
10310 
10311 	icmd = &iocbq->iocb;
10312 	evt_code = icmd->un.asyncstat.evt_code;
10313 
10314 	switch (evt_code) {
10315 	case ASYNC_TEMP_WARN:
10316 	case ASYNC_TEMP_SAFE:
10317 		temp_event_data.data = (uint32_t) icmd->ulpContext;
10318 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
10319 		if (evt_code == ASYNC_TEMP_WARN) {
10320 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
10321 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
10322 				"0347 Adapter is very hot, please take "
10323 				"corrective action. temperature : %d Celsius\n",
10324 				(uint32_t) icmd->ulpContext);
10325 		} else {
10326 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
10327 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
10328 				"0340 Adapter temperature is OK now. "
10329 				"temperature : %d Celsius\n",
10330 				(uint32_t) icmd->ulpContext);
10331 		}
10332 
10333 		/* Send temperature change event to applications */
10334 		shost = lpfc_shost_from_vport(phba->pport);
10335 		fc_host_post_vendor_event(shost, fc_get_event_number(),
10336 			sizeof(temp_event_data), (char *) &temp_event_data,
10337 			LPFC_NL_VENDOR_ID);
10338 		break;
10339 	case ASYNC_STATUS_CN:
10340 		lpfc_sli_abts_err_handler(phba, iocbq);
10341 		break;
10342 	default:
10343 		iocb_w = (uint32_t *) icmd;
10344 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10345 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
10346 			" evt_code 0x%x\n"
10347 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
10348 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
10349 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
10350 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
10351 			pring->ringno, icmd->un.asyncstat.evt_code,
10352 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
10353 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
10354 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
10355 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
10356 
10357 		break;
10358 	}
10359 }
10360 
10361 
10362 /**
10363  * lpfc_sli4_setup - SLI ring setup function
10364  * @phba: Pointer to HBA context object.
10365  *
10366  * lpfc_sli_setup sets up rings of the SLI interface with
10367  * number of iocbs per ring and iotags. This function is
10368  * called while driver attach to the HBA and before the
10369  * interrupts are enabled. So there is no need for locking.
10370  *
10371  * This function always returns 0.
10372  **/
10373 int
10374 lpfc_sli4_setup(struct lpfc_hba *phba)
10375 {
10376 	struct lpfc_sli_ring *pring;
10377 
10378 	pring = phba->sli4_hba.els_wq->pring;
10379 	pring->num_mask = LPFC_MAX_RING_MASK;
10380 	pring->prt[0].profile = 0;	/* Mask 0 */
10381 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10382 	pring->prt[0].type = FC_TYPE_ELS;
10383 	pring->prt[0].lpfc_sli_rcv_unsol_event =
10384 	    lpfc_els_unsol_event;
10385 	pring->prt[1].profile = 0;	/* Mask 1 */
10386 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
10387 	pring->prt[1].type = FC_TYPE_ELS;
10388 	pring->prt[1].lpfc_sli_rcv_unsol_event =
10389 	    lpfc_els_unsol_event;
10390 	pring->prt[2].profile = 0;	/* Mask 2 */
10391 	/* NameServer Inquiry */
10392 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10393 	/* NameServer */
10394 	pring->prt[2].type = FC_TYPE_CT;
10395 	pring->prt[2].lpfc_sli_rcv_unsol_event =
10396 	    lpfc_ct_unsol_event;
10397 	pring->prt[3].profile = 0;	/* Mask 3 */
10398 	/* NameServer response */
10399 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10400 	/* NameServer */
10401 	pring->prt[3].type = FC_TYPE_CT;
10402 	pring->prt[3].lpfc_sli_rcv_unsol_event =
10403 	    lpfc_ct_unsol_event;
10404 	return 0;
10405 }
10406 
10407 /**
10408  * lpfc_sli_setup - SLI ring setup function
10409  * @phba: Pointer to HBA context object.
10410  *
10411  * lpfc_sli_setup sets up rings of the SLI interface with
10412  * number of iocbs per ring and iotags. This function is
10413  * called while driver attach to the HBA and before the
10414  * interrupts are enabled. So there is no need for locking.
10415  *
10416  * This function always returns 0. SLI3 only.
10417  **/
10418 int
10419 lpfc_sli_setup(struct lpfc_hba *phba)
10420 {
10421 	int i, totiocbsize = 0;
10422 	struct lpfc_sli *psli = &phba->sli;
10423 	struct lpfc_sli_ring *pring;
10424 
10425 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
10426 	psli->sli_flag = 0;
10427 
10428 	psli->iocbq_lookup = NULL;
10429 	psli->iocbq_lookup_len = 0;
10430 	psli->last_iotag = 0;
10431 
10432 	for (i = 0; i < psli->num_rings; i++) {
10433 		pring = &psli->sli3_ring[i];
10434 		switch (i) {
10435 		case LPFC_FCP_RING:	/* ring 0 - FCP */
10436 			/* numCiocb and numRiocb are used in config_port */
10437 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
10438 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
10439 			pring->sli.sli3.numCiocb +=
10440 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10441 			pring->sli.sli3.numRiocb +=
10442 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10443 			pring->sli.sli3.numCiocb +=
10444 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10445 			pring->sli.sli3.numRiocb +=
10446 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10447 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10448 							SLI3_IOCB_CMD_SIZE :
10449 							SLI2_IOCB_CMD_SIZE;
10450 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10451 							SLI3_IOCB_RSP_SIZE :
10452 							SLI2_IOCB_RSP_SIZE;
10453 			pring->iotag_ctr = 0;
10454 			pring->iotag_max =
10455 			    (phba->cfg_hba_queue_depth * 2);
10456 			pring->fast_iotag = pring->iotag_max;
10457 			pring->num_mask = 0;
10458 			break;
10459 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
10460 			/* numCiocb and numRiocb are used in config_port */
10461 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
10462 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
10463 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10464 							SLI3_IOCB_CMD_SIZE :
10465 							SLI2_IOCB_CMD_SIZE;
10466 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10467 							SLI3_IOCB_RSP_SIZE :
10468 							SLI2_IOCB_RSP_SIZE;
10469 			pring->iotag_max = phba->cfg_hba_queue_depth;
10470 			pring->num_mask = 0;
10471 			break;
10472 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
10473 			/* numCiocb and numRiocb are used in config_port */
10474 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
10475 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
10476 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10477 							SLI3_IOCB_CMD_SIZE :
10478 							SLI2_IOCB_CMD_SIZE;
10479 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10480 							SLI3_IOCB_RSP_SIZE :
10481 							SLI2_IOCB_RSP_SIZE;
10482 			pring->fast_iotag = 0;
10483 			pring->iotag_ctr = 0;
10484 			pring->iotag_max = 4096;
10485 			pring->lpfc_sli_rcv_async_status =
10486 				lpfc_sli_async_event_handler;
10487 			pring->num_mask = LPFC_MAX_RING_MASK;
10488 			pring->prt[0].profile = 0;	/* Mask 0 */
10489 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10490 			pring->prt[0].type = FC_TYPE_ELS;
10491 			pring->prt[0].lpfc_sli_rcv_unsol_event =
10492 			    lpfc_els_unsol_event;
10493 			pring->prt[1].profile = 0;	/* Mask 1 */
10494 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
10495 			pring->prt[1].type = FC_TYPE_ELS;
10496 			pring->prt[1].lpfc_sli_rcv_unsol_event =
10497 			    lpfc_els_unsol_event;
10498 			pring->prt[2].profile = 0;	/* Mask 2 */
10499 			/* NameServer Inquiry */
10500 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10501 			/* NameServer */
10502 			pring->prt[2].type = FC_TYPE_CT;
10503 			pring->prt[2].lpfc_sli_rcv_unsol_event =
10504 			    lpfc_ct_unsol_event;
10505 			pring->prt[3].profile = 0;	/* Mask 3 */
10506 			/* NameServer response */
10507 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10508 			/* NameServer */
10509 			pring->prt[3].type = FC_TYPE_CT;
10510 			pring->prt[3].lpfc_sli_rcv_unsol_event =
10511 			    lpfc_ct_unsol_event;
10512 			break;
10513 		}
10514 		totiocbsize += (pring->sli.sli3.numCiocb *
10515 			pring->sli.sli3.sizeCiocb) +
10516 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
10517 	}
10518 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
10519 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
10520 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
10521 		       "SLI2 SLIM Data: x%x x%lx\n",
10522 		       phba->brd_no, totiocbsize,
10523 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
10524 	}
10525 	if (phba->cfg_multi_ring_support == 2)
10526 		lpfc_extra_ring_setup(phba);
10527 
10528 	return 0;
10529 }
10530 
10531 /**
10532  * lpfc_sli4_queue_init - Queue initialization function
10533  * @phba: Pointer to HBA context object.
10534  *
10535  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
10536  * ring. This function also initializes ring indices of each ring.
10537  * This function is called during the initialization of the SLI
10538  * interface of an HBA.
10539  * This function is called with no lock held and always returns
10540  * 1.
10541  **/
10542 void
10543 lpfc_sli4_queue_init(struct lpfc_hba *phba)
10544 {
10545 	struct lpfc_sli *psli;
10546 	struct lpfc_sli_ring *pring;
10547 	int i;
10548 
10549 	psli = &phba->sli;
10550 	spin_lock_irq(&phba->hbalock);
10551 	INIT_LIST_HEAD(&psli->mboxq);
10552 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
10553 	/* Initialize list headers for txq and txcmplq as double linked lists */
10554 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
10555 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
10556 		pring->flag = 0;
10557 		pring->ringno = LPFC_FCP_RING;
10558 		pring->txcmplq_cnt = 0;
10559 		INIT_LIST_HEAD(&pring->txq);
10560 		INIT_LIST_HEAD(&pring->txcmplq);
10561 		INIT_LIST_HEAD(&pring->iocb_continueq);
10562 		spin_lock_init(&pring->ring_lock);
10563 	}
10564 	pring = phba->sli4_hba.els_wq->pring;
10565 	pring->flag = 0;
10566 	pring->ringno = LPFC_ELS_RING;
10567 	pring->txcmplq_cnt = 0;
10568 	INIT_LIST_HEAD(&pring->txq);
10569 	INIT_LIST_HEAD(&pring->txcmplq);
10570 	INIT_LIST_HEAD(&pring->iocb_continueq);
10571 	spin_lock_init(&pring->ring_lock);
10572 
10573 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10574 		pring = phba->sli4_hba.nvmels_wq->pring;
10575 		pring->flag = 0;
10576 		pring->ringno = LPFC_ELS_RING;
10577 		pring->txcmplq_cnt = 0;
10578 		INIT_LIST_HEAD(&pring->txq);
10579 		INIT_LIST_HEAD(&pring->txcmplq);
10580 		INIT_LIST_HEAD(&pring->iocb_continueq);
10581 		spin_lock_init(&pring->ring_lock);
10582 	}
10583 
10584 	spin_unlock_irq(&phba->hbalock);
10585 }
10586 
10587 /**
10588  * lpfc_sli_queue_init - Queue initialization function
10589  * @phba: Pointer to HBA context object.
10590  *
10591  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
10592  * ring. This function also initializes ring indices of each ring.
10593  * This function is called during the initialization of the SLI
10594  * interface of an HBA.
10595  * This function is called with no lock held and always returns
10596  * 1.
10597  **/
10598 void
10599 lpfc_sli_queue_init(struct lpfc_hba *phba)
10600 {
10601 	struct lpfc_sli *psli;
10602 	struct lpfc_sli_ring *pring;
10603 	int i;
10604 
10605 	psli = &phba->sli;
10606 	spin_lock_irq(&phba->hbalock);
10607 	INIT_LIST_HEAD(&psli->mboxq);
10608 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
10609 	/* Initialize list headers for txq and txcmplq as double linked lists */
10610 	for (i = 0; i < psli->num_rings; i++) {
10611 		pring = &psli->sli3_ring[i];
10612 		pring->ringno = i;
10613 		pring->sli.sli3.next_cmdidx  = 0;
10614 		pring->sli.sli3.local_getidx = 0;
10615 		pring->sli.sli3.cmdidx = 0;
10616 		INIT_LIST_HEAD(&pring->iocb_continueq);
10617 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
10618 		INIT_LIST_HEAD(&pring->postbufq);
10619 		pring->flag = 0;
10620 		INIT_LIST_HEAD(&pring->txq);
10621 		INIT_LIST_HEAD(&pring->txcmplq);
10622 		spin_lock_init(&pring->ring_lock);
10623 	}
10624 	spin_unlock_irq(&phba->hbalock);
10625 }
10626 
10627 /**
10628  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
10629  * @phba: Pointer to HBA context object.
10630  *
10631  * This routine flushes the mailbox command subsystem. It will unconditionally
10632  * flush all the mailbox commands in the three possible stages in the mailbox
10633  * command sub-system: pending mailbox command queue; the outstanding mailbox
10634  * command; and completed mailbox command queue. It is caller's responsibility
10635  * to make sure that the driver is in the proper state to flush the mailbox
10636  * command sub-system. Namely, the posting of mailbox commands into the
10637  * pending mailbox command queue from the various clients must be stopped;
10638  * either the HBA is in a state that it will never works on the outstanding
10639  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
10640  * mailbox command has been completed.
10641  **/
10642 static void
10643 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
10644 {
10645 	LIST_HEAD(completions);
10646 	struct lpfc_sli *psli = &phba->sli;
10647 	LPFC_MBOXQ_t *pmb;
10648 	unsigned long iflag;
10649 
10650 	/* Disable softirqs, including timers from obtaining phba->hbalock */
10651 	local_bh_disable();
10652 
10653 	/* Flush all the mailbox commands in the mbox system */
10654 	spin_lock_irqsave(&phba->hbalock, iflag);
10655 
10656 	/* The pending mailbox command queue */
10657 	list_splice_init(&phba->sli.mboxq, &completions);
10658 	/* The outstanding active mailbox command */
10659 	if (psli->mbox_active) {
10660 		list_add_tail(&psli->mbox_active->list, &completions);
10661 		psli->mbox_active = NULL;
10662 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10663 	}
10664 	/* The completed mailbox command queue */
10665 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
10666 	spin_unlock_irqrestore(&phba->hbalock, iflag);
10667 
10668 	/* Enable softirqs again, done with phba->hbalock */
10669 	local_bh_enable();
10670 
10671 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
10672 	while (!list_empty(&completions)) {
10673 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
10674 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
10675 		if (pmb->mbox_cmpl)
10676 			pmb->mbox_cmpl(phba, pmb);
10677 	}
10678 }
10679 
10680 /**
10681  * lpfc_sli_host_down - Vport cleanup function
10682  * @vport: Pointer to virtual port object.
10683  *
10684  * lpfc_sli_host_down is called to clean up the resources
10685  * associated with a vport before destroying virtual
10686  * port data structures.
10687  * This function does following operations:
10688  * - Free discovery resources associated with this virtual
10689  *   port.
10690  * - Free iocbs associated with this virtual port in
10691  *   the txq.
10692  * - Send abort for all iocb commands associated with this
10693  *   vport in txcmplq.
10694  *
10695  * This function is called with no lock held and always returns 1.
10696  **/
10697 int
10698 lpfc_sli_host_down(struct lpfc_vport *vport)
10699 {
10700 	LIST_HEAD(completions);
10701 	struct lpfc_hba *phba = vport->phba;
10702 	struct lpfc_sli *psli = &phba->sli;
10703 	struct lpfc_queue *qp = NULL;
10704 	struct lpfc_sli_ring *pring;
10705 	struct lpfc_iocbq *iocb, *next_iocb;
10706 	int i;
10707 	unsigned long flags = 0;
10708 	uint16_t prev_pring_flag;
10709 
10710 	lpfc_cleanup_discovery_resources(vport);
10711 
10712 	spin_lock_irqsave(&phba->hbalock, flags);
10713 
10714 	/*
10715 	 * Error everything on the txq since these iocbs
10716 	 * have not been given to the FW yet.
10717 	 * Also issue ABTS for everything on the txcmplq
10718 	 */
10719 	if (phba->sli_rev != LPFC_SLI_REV4) {
10720 		for (i = 0; i < psli->num_rings; i++) {
10721 			pring = &psli->sli3_ring[i];
10722 			prev_pring_flag = pring->flag;
10723 			/* Only slow rings */
10724 			if (pring->ringno == LPFC_ELS_RING) {
10725 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10726 				/* Set the lpfc data pending flag */
10727 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10728 			}
10729 			list_for_each_entry_safe(iocb, next_iocb,
10730 						 &pring->txq, list) {
10731 				if (iocb->vport != vport)
10732 					continue;
10733 				list_move_tail(&iocb->list, &completions);
10734 			}
10735 			list_for_each_entry_safe(iocb, next_iocb,
10736 						 &pring->txcmplq, list) {
10737 				if (iocb->vport != vport)
10738 					continue;
10739 				lpfc_sli_issue_abort_iotag(phba, pring, iocb);
10740 			}
10741 			pring->flag = prev_pring_flag;
10742 		}
10743 	} else {
10744 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
10745 			pring = qp->pring;
10746 			if (!pring)
10747 				continue;
10748 			if (pring == phba->sli4_hba.els_wq->pring) {
10749 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10750 				/* Set the lpfc data pending flag */
10751 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10752 			}
10753 			prev_pring_flag = pring->flag;
10754 			spin_lock(&pring->ring_lock);
10755 			list_for_each_entry_safe(iocb, next_iocb,
10756 						 &pring->txq, list) {
10757 				if (iocb->vport != vport)
10758 					continue;
10759 				list_move_tail(&iocb->list, &completions);
10760 			}
10761 			spin_unlock(&pring->ring_lock);
10762 			list_for_each_entry_safe(iocb, next_iocb,
10763 						 &pring->txcmplq, list) {
10764 				if (iocb->vport != vport)
10765 					continue;
10766 				lpfc_sli_issue_abort_iotag(phba, pring, iocb);
10767 			}
10768 			pring->flag = prev_pring_flag;
10769 		}
10770 	}
10771 	spin_unlock_irqrestore(&phba->hbalock, flags);
10772 
10773 	/* Cancel all the IOCBs from the completions list */
10774 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
10775 			      IOERR_SLI_DOWN);
10776 	return 1;
10777 }
10778 
10779 /**
10780  * lpfc_sli_hba_down - Resource cleanup function for the HBA
10781  * @phba: Pointer to HBA context object.
10782  *
10783  * This function cleans up all iocb, buffers, mailbox commands
10784  * while shutting down the HBA. This function is called with no
10785  * lock held and always returns 1.
10786  * This function does the following to cleanup driver resources:
10787  * - Free discovery resources for each virtual port
10788  * - Cleanup any pending fabric iocbs
10789  * - Iterate through the iocb txq and free each entry
10790  *   in the list.
10791  * - Free up any buffer posted to the HBA
10792  * - Free mailbox commands in the mailbox queue.
10793  **/
10794 int
10795 lpfc_sli_hba_down(struct lpfc_hba *phba)
10796 {
10797 	LIST_HEAD(completions);
10798 	struct lpfc_sli *psli = &phba->sli;
10799 	struct lpfc_queue *qp = NULL;
10800 	struct lpfc_sli_ring *pring;
10801 	struct lpfc_dmabuf *buf_ptr;
10802 	unsigned long flags = 0;
10803 	int i;
10804 
10805 	/* Shutdown the mailbox command sub-system */
10806 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
10807 
10808 	lpfc_hba_down_prep(phba);
10809 
10810 	/* Disable softirqs, including timers from obtaining phba->hbalock */
10811 	local_bh_disable();
10812 
10813 	lpfc_fabric_abort_hba(phba);
10814 
10815 	spin_lock_irqsave(&phba->hbalock, flags);
10816 
10817 	/*
10818 	 * Error everything on the txq since these iocbs
10819 	 * have not been given to the FW yet.
10820 	 */
10821 	if (phba->sli_rev != LPFC_SLI_REV4) {
10822 		for (i = 0; i < psli->num_rings; i++) {
10823 			pring = &psli->sli3_ring[i];
10824 			/* Only slow rings */
10825 			if (pring->ringno == LPFC_ELS_RING) {
10826 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10827 				/* Set the lpfc data pending flag */
10828 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10829 			}
10830 			list_splice_init(&pring->txq, &completions);
10831 		}
10832 	} else {
10833 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
10834 			pring = qp->pring;
10835 			if (!pring)
10836 				continue;
10837 			spin_lock(&pring->ring_lock);
10838 			list_splice_init(&pring->txq, &completions);
10839 			spin_unlock(&pring->ring_lock);
10840 			if (pring == phba->sli4_hba.els_wq->pring) {
10841 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10842 				/* Set the lpfc data pending flag */
10843 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10844 			}
10845 		}
10846 	}
10847 	spin_unlock_irqrestore(&phba->hbalock, flags);
10848 
10849 	/* Cancel all the IOCBs from the completions list */
10850 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
10851 			      IOERR_SLI_DOWN);
10852 
10853 	spin_lock_irqsave(&phba->hbalock, flags);
10854 	list_splice_init(&phba->elsbuf, &completions);
10855 	phba->elsbuf_cnt = 0;
10856 	phba->elsbuf_prev_cnt = 0;
10857 	spin_unlock_irqrestore(&phba->hbalock, flags);
10858 
10859 	while (!list_empty(&completions)) {
10860 		list_remove_head(&completions, buf_ptr,
10861 			struct lpfc_dmabuf, list);
10862 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
10863 		kfree(buf_ptr);
10864 	}
10865 
10866 	/* Enable softirqs again, done with phba->hbalock */
10867 	local_bh_enable();
10868 
10869 	/* Return any active mbox cmds */
10870 	del_timer_sync(&psli->mbox_tmo);
10871 
10872 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
10873 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
10874 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
10875 
10876 	return 1;
10877 }
10878 
10879 /**
10880  * lpfc_sli_pcimem_bcopy - SLI memory copy function
10881  * @srcp: Source memory pointer.
10882  * @destp: Destination memory pointer.
10883  * @cnt: Number of words required to be copied.
10884  *
10885  * This function is used for copying data between driver memory
10886  * and the SLI memory. This function also changes the endianness
10887  * of each word if native endianness is different from SLI
10888  * endianness. This function can be called with or without
10889  * lock.
10890  **/
10891 void
10892 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
10893 {
10894 	uint32_t *src = srcp;
10895 	uint32_t *dest = destp;
10896 	uint32_t ldata;
10897 	int i;
10898 
10899 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
10900 		ldata = *src;
10901 		ldata = le32_to_cpu(ldata);
10902 		*dest = ldata;
10903 		src++;
10904 		dest++;
10905 	}
10906 }
10907 
10908 
10909 /**
10910  * lpfc_sli_bemem_bcopy - SLI memory copy function
10911  * @srcp: Source memory pointer.
10912  * @destp: Destination memory pointer.
10913  * @cnt: Number of words required to be copied.
10914  *
10915  * This function is used for copying data between a data structure
10916  * with big endian representation to local endianness.
10917  * This function can be called with or without lock.
10918  **/
10919 void
10920 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
10921 {
10922 	uint32_t *src = srcp;
10923 	uint32_t *dest = destp;
10924 	uint32_t ldata;
10925 	int i;
10926 
10927 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
10928 		ldata = *src;
10929 		ldata = be32_to_cpu(ldata);
10930 		*dest = ldata;
10931 		src++;
10932 		dest++;
10933 	}
10934 }
10935 
10936 /**
10937  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
10938  * @phba: Pointer to HBA context object.
10939  * @pring: Pointer to driver SLI ring object.
10940  * @mp: Pointer to driver buffer object.
10941  *
10942  * This function is called with no lock held.
10943  * It always return zero after adding the buffer to the postbufq
10944  * buffer list.
10945  **/
10946 int
10947 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10948 			 struct lpfc_dmabuf *mp)
10949 {
10950 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
10951 	   later */
10952 	spin_lock_irq(&phba->hbalock);
10953 	list_add_tail(&mp->list, &pring->postbufq);
10954 	pring->postbufq_cnt++;
10955 	spin_unlock_irq(&phba->hbalock);
10956 	return 0;
10957 }
10958 
10959 /**
10960  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
10961  * @phba: Pointer to HBA context object.
10962  *
10963  * When HBQ is enabled, buffers are searched based on tags. This function
10964  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
10965  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
10966  * does not conflict with tags of buffer posted for unsolicited events.
10967  * The function returns the allocated tag. The function is called with
10968  * no locks held.
10969  **/
10970 uint32_t
10971 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
10972 {
10973 	spin_lock_irq(&phba->hbalock);
10974 	phba->buffer_tag_count++;
10975 	/*
10976 	 * Always set the QUE_BUFTAG_BIT to distiguish between
10977 	 * a tag assigned by HBQ.
10978 	 */
10979 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
10980 	spin_unlock_irq(&phba->hbalock);
10981 	return phba->buffer_tag_count;
10982 }
10983 
10984 /**
10985  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
10986  * @phba: Pointer to HBA context object.
10987  * @pring: Pointer to driver SLI ring object.
10988  * @tag: Buffer tag.
10989  *
10990  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
10991  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
10992  * iocb is posted to the response ring with the tag of the buffer.
10993  * This function searches the pring->postbufq list using the tag
10994  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
10995  * iocb. If the buffer is found then lpfc_dmabuf object of the
10996  * buffer is returned to the caller else NULL is returned.
10997  * This function is called with no lock held.
10998  **/
10999 struct lpfc_dmabuf *
11000 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11001 			uint32_t tag)
11002 {
11003 	struct lpfc_dmabuf *mp, *next_mp;
11004 	struct list_head *slp = &pring->postbufq;
11005 
11006 	/* Search postbufq, from the beginning, looking for a match on tag */
11007 	spin_lock_irq(&phba->hbalock);
11008 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11009 		if (mp->buffer_tag == tag) {
11010 			list_del_init(&mp->list);
11011 			pring->postbufq_cnt--;
11012 			spin_unlock_irq(&phba->hbalock);
11013 			return mp;
11014 		}
11015 	}
11016 
11017 	spin_unlock_irq(&phba->hbalock);
11018 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11019 			"0402 Cannot find virtual addr for buffer tag on "
11020 			"ring %d Data x%lx x%px x%px x%x\n",
11021 			pring->ringno, (unsigned long) tag,
11022 			slp->next, slp->prev, pring->postbufq_cnt);
11023 
11024 	return NULL;
11025 }
11026 
11027 /**
11028  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
11029  * @phba: Pointer to HBA context object.
11030  * @pring: Pointer to driver SLI ring object.
11031  * @phys: DMA address of the buffer.
11032  *
11033  * This function searches the buffer list using the dma_address
11034  * of unsolicited event to find the driver's lpfc_dmabuf object
11035  * corresponding to the dma_address. The function returns the
11036  * lpfc_dmabuf object if a buffer is found else it returns NULL.
11037  * This function is called by the ct and els unsolicited event
11038  * handlers to get the buffer associated with the unsolicited
11039  * event.
11040  *
11041  * This function is called with no lock held.
11042  **/
11043 struct lpfc_dmabuf *
11044 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11045 			 dma_addr_t phys)
11046 {
11047 	struct lpfc_dmabuf *mp, *next_mp;
11048 	struct list_head *slp = &pring->postbufq;
11049 
11050 	/* Search postbufq, from the beginning, looking for a match on phys */
11051 	spin_lock_irq(&phba->hbalock);
11052 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11053 		if (mp->phys == phys) {
11054 			list_del_init(&mp->list);
11055 			pring->postbufq_cnt--;
11056 			spin_unlock_irq(&phba->hbalock);
11057 			return mp;
11058 		}
11059 	}
11060 
11061 	spin_unlock_irq(&phba->hbalock);
11062 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11063 			"0410 Cannot find virtual addr for mapped buf on "
11064 			"ring %d Data x%llx x%px x%px x%x\n",
11065 			pring->ringno, (unsigned long long)phys,
11066 			slp->next, slp->prev, pring->postbufq_cnt);
11067 	return NULL;
11068 }
11069 
11070 /**
11071  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
11072  * @phba: Pointer to HBA context object.
11073  * @cmdiocb: Pointer to driver command iocb object.
11074  * @rspiocb: Pointer to driver response iocb object.
11075  *
11076  * This function is the completion handler for the abort iocbs for
11077  * ELS commands. This function is called from the ELS ring event
11078  * handler with no lock held. This function frees memory resources
11079  * associated with the abort iocb.
11080  **/
11081 static void
11082 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11083 			struct lpfc_iocbq *rspiocb)
11084 {
11085 	IOCB_t *irsp = &rspiocb->iocb;
11086 	uint16_t abort_iotag, abort_context;
11087 	struct lpfc_iocbq *abort_iocb = NULL;
11088 
11089 	if (irsp->ulpStatus) {
11090 
11091 		/*
11092 		 * Assume that the port already completed and returned, or
11093 		 * will return the iocb. Just Log the message.
11094 		 */
11095 		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
11096 		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
11097 
11098 		spin_lock_irq(&phba->hbalock);
11099 		if (phba->sli_rev < LPFC_SLI_REV4) {
11100 			if (irsp->ulpCommand == CMD_ABORT_XRI_CX &&
11101 			    irsp->ulpStatus == IOSTAT_LOCAL_REJECT &&
11102 			    irsp->un.ulpWord[4] == IOERR_ABORT_REQUESTED) {
11103 				spin_unlock_irq(&phba->hbalock);
11104 				goto release_iocb;
11105 			}
11106 			if (abort_iotag != 0 &&
11107 				abort_iotag <= phba->sli.last_iotag)
11108 				abort_iocb =
11109 					phba->sli.iocbq_lookup[abort_iotag];
11110 		} else
11111 			/* For sli4 the abort_tag is the XRI,
11112 			 * so the abort routine puts the iotag  of the iocb
11113 			 * being aborted in the context field of the abort
11114 			 * IOCB.
11115 			 */
11116 			abort_iocb = phba->sli.iocbq_lookup[abort_context];
11117 
11118 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
11119 				"0327 Cannot abort els iocb x%px "
11120 				"with tag %x context %x, abort status %x, "
11121 				"abort code %x\n",
11122 				abort_iocb, abort_iotag, abort_context,
11123 				irsp->ulpStatus, irsp->un.ulpWord[4]);
11124 
11125 		spin_unlock_irq(&phba->hbalock);
11126 	}
11127 release_iocb:
11128 	lpfc_sli_release_iocbq(phba, cmdiocb);
11129 	return;
11130 }
11131 
11132 /**
11133  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
11134  * @phba: Pointer to HBA context object.
11135  * @cmdiocb: Pointer to driver command iocb object.
11136  * @rspiocb: Pointer to driver response iocb object.
11137  *
11138  * The function is called from SLI ring event handler with no
11139  * lock held. This function is the completion handler for ELS commands
11140  * which are aborted. The function frees memory resources used for
11141  * the aborted ELS commands.
11142  **/
11143 static void
11144 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11145 		     struct lpfc_iocbq *rspiocb)
11146 {
11147 	IOCB_t *irsp = &rspiocb->iocb;
11148 
11149 	/* ELS cmd tag <ulpIoTag> completes */
11150 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
11151 			"0139 Ignoring ELS cmd tag x%x completion Data: "
11152 			"x%x x%x x%x\n",
11153 			irsp->ulpIoTag, irsp->ulpStatus,
11154 			irsp->un.ulpWord[4], irsp->ulpTimeout);
11155 	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
11156 		lpfc_ct_free_iocb(phba, cmdiocb);
11157 	else
11158 		lpfc_els_free_iocb(phba, cmdiocb);
11159 	return;
11160 }
11161 
11162 /**
11163  * lpfc_sli_abort_iotag_issue - Issue abort for a command iocb
11164  * @phba: Pointer to HBA context object.
11165  * @pring: Pointer to driver SLI ring object.
11166  * @cmdiocb: Pointer to driver command iocb object.
11167  *
11168  * This function issues an abort iocb for the provided command iocb down to
11169  * the port. Other than the case the outstanding command iocb is an abort
11170  * request, this function issues abort out unconditionally. This function is
11171  * called with hbalock held. The function returns 0 when it fails due to
11172  * memory allocation failure or when the command iocb is an abort request.
11173  **/
11174 static int
11175 lpfc_sli_abort_iotag_issue(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11176 			   struct lpfc_iocbq *cmdiocb)
11177 {
11178 	struct lpfc_vport *vport = cmdiocb->vport;
11179 	struct lpfc_iocbq *abtsiocbp;
11180 	IOCB_t *icmd = NULL;
11181 	IOCB_t *iabt = NULL;
11182 	int retval;
11183 	unsigned long iflags;
11184 	struct lpfc_nodelist *ndlp;
11185 
11186 	lockdep_assert_held(&phba->hbalock);
11187 
11188 	/*
11189 	 * There are certain command types we don't want to abort.  And we
11190 	 * don't want to abort commands that are already in the process of
11191 	 * being aborted.
11192 	 */
11193 	icmd = &cmdiocb->iocb;
11194 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11195 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
11196 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
11197 		return 0;
11198 
11199 	/* issue ABTS for this IOCB based on iotag */
11200 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
11201 	if (abtsiocbp == NULL)
11202 		return 0;
11203 
11204 	/* This signals the response to set the correct status
11205 	 * before calling the completion handler
11206 	 */
11207 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
11208 
11209 	iabt = &abtsiocbp->iocb;
11210 	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
11211 	iabt->un.acxri.abortContextTag = icmd->ulpContext;
11212 	if (phba->sli_rev == LPFC_SLI_REV4) {
11213 		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
11214 		iabt->un.acxri.abortContextTag = cmdiocb->iotag;
11215 	} else {
11216 		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
11217 		if (pring->ringno == LPFC_ELS_RING) {
11218 			ndlp = (struct lpfc_nodelist *)(cmdiocb->context1);
11219 			iabt->un.acxri.abortContextTag = ndlp->nlp_rpi;
11220 		}
11221 	}
11222 	iabt->ulpLe = 1;
11223 	iabt->ulpClass = icmd->ulpClass;
11224 
11225 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11226 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
11227 	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
11228 		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
11229 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
11230 		abtsiocbp->iocb_flag |= LPFC_IO_FOF;
11231 
11232 	if (phba->link_state >= LPFC_LINK_UP)
11233 		iabt->ulpCommand = CMD_ABORT_XRI_CN;
11234 	else
11235 		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
11236 
11237 	abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
11238 	abtsiocbp->vport = vport;
11239 
11240 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
11241 			 "0339 Abort xri x%x, original iotag x%x, "
11242 			 "abort cmd iotag x%x\n",
11243 			 iabt->un.acxri.abortIoTag,
11244 			 iabt->un.acxri.abortContextTag,
11245 			 abtsiocbp->iotag);
11246 
11247 	if (phba->sli_rev == LPFC_SLI_REV4) {
11248 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
11249 		if (unlikely(pring == NULL))
11250 			return 0;
11251 		/* Note: both hbalock and ring_lock need to be set here */
11252 		spin_lock_irqsave(&pring->ring_lock, iflags);
11253 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11254 			abtsiocbp, 0);
11255 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11256 	} else {
11257 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11258 			abtsiocbp, 0);
11259 	}
11260 
11261 	if (retval)
11262 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
11263 
11264 	/*
11265 	 * Caller to this routine should check for IOCB_ERROR
11266 	 * and handle it properly.  This routine no longer removes
11267 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
11268 	 */
11269 	return retval;
11270 }
11271 
11272 /**
11273  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
11274  * @phba: Pointer to HBA context object.
11275  * @pring: Pointer to driver SLI ring object.
11276  * @cmdiocb: Pointer to driver command iocb object.
11277  *
11278  * This function issues an abort iocb for the provided command iocb. In case
11279  * of unloading, the abort iocb will not be issued to commands on the ELS
11280  * ring. Instead, the callback function shall be changed to those commands
11281  * so that nothing happens when them finishes. This function is called with
11282  * hbalock held. The function returns 0 when the command iocb is an abort
11283  * request.
11284  **/
11285 int
11286 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11287 			   struct lpfc_iocbq *cmdiocb)
11288 {
11289 	struct lpfc_vport *vport = cmdiocb->vport;
11290 	int retval = IOCB_ERROR;
11291 	IOCB_t *icmd = NULL;
11292 
11293 	lockdep_assert_held(&phba->hbalock);
11294 
11295 	/*
11296 	 * There are certain command types we don't want to abort.  And we
11297 	 * don't want to abort commands that are already in the process of
11298 	 * being aborted.
11299 	 */
11300 	icmd = &cmdiocb->iocb;
11301 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11302 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
11303 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
11304 		return 0;
11305 
11306 	if (!pring) {
11307 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11308 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11309 		else
11310 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11311 		goto abort_iotag_exit;
11312 	}
11313 
11314 	/*
11315 	 * If we're unloading, don't abort iocb on the ELS ring, but change
11316 	 * the callback so that nothing happens when it finishes.
11317 	 */
11318 	if ((vport->load_flag & FC_UNLOADING) &&
11319 	    (pring->ringno == LPFC_ELS_RING)) {
11320 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11321 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11322 		else
11323 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11324 		goto abort_iotag_exit;
11325 	}
11326 
11327 	/* Now, we try to issue the abort to the cmdiocb out */
11328 	retval = lpfc_sli_abort_iotag_issue(phba, pring, cmdiocb);
11329 
11330 abort_iotag_exit:
11331 	/*
11332 	 * Caller to this routine should check for IOCB_ERROR
11333 	 * and handle it properly.  This routine no longer removes
11334 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
11335 	 */
11336 	return retval;
11337 }
11338 
11339 /**
11340  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
11341  * @phba: pointer to lpfc HBA data structure.
11342  *
11343  * This routine will abort all pending and outstanding iocbs to an HBA.
11344  **/
11345 void
11346 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
11347 {
11348 	struct lpfc_sli *psli = &phba->sli;
11349 	struct lpfc_sli_ring *pring;
11350 	struct lpfc_queue *qp = NULL;
11351 	int i;
11352 
11353 	if (phba->sli_rev != LPFC_SLI_REV4) {
11354 		for (i = 0; i < psli->num_rings; i++) {
11355 			pring = &psli->sli3_ring[i];
11356 			lpfc_sli_abort_iocb_ring(phba, pring);
11357 		}
11358 		return;
11359 	}
11360 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11361 		pring = qp->pring;
11362 		if (!pring)
11363 			continue;
11364 		lpfc_sli_abort_iocb_ring(phba, pring);
11365 	}
11366 }
11367 
11368 /**
11369  * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
11370  * @iocbq: Pointer to driver iocb object.
11371  * @vport: Pointer to driver virtual port object.
11372  * @tgt_id: SCSI ID of the target.
11373  * @lun_id: LUN ID of the scsi device.
11374  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
11375  *
11376  * This function acts as an iocb filter for functions which abort or count
11377  * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
11378  * 0 if the filtering criteria is met for the given iocb and will return
11379  * 1 if the filtering criteria is not met.
11380  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
11381  * given iocb is for the SCSI device specified by vport, tgt_id and
11382  * lun_id parameter.
11383  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
11384  * given iocb is for the SCSI target specified by vport and tgt_id
11385  * parameters.
11386  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
11387  * given iocb is for the SCSI host associated with the given vport.
11388  * This function is called with no locks held.
11389  **/
11390 static int
11391 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
11392 			   uint16_t tgt_id, uint64_t lun_id,
11393 			   lpfc_ctx_cmd ctx_cmd)
11394 {
11395 	struct lpfc_io_buf *lpfc_cmd;
11396 	int rc = 1;
11397 
11398 	if (iocbq->vport != vport)
11399 		return rc;
11400 
11401 	if (!(iocbq->iocb_flag &  LPFC_IO_FCP) ||
11402 	    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ))
11403 		return rc;
11404 
11405 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
11406 
11407 	if (lpfc_cmd->pCmd == NULL)
11408 		return rc;
11409 
11410 	switch (ctx_cmd) {
11411 	case LPFC_CTX_LUN:
11412 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11413 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
11414 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
11415 			rc = 0;
11416 		break;
11417 	case LPFC_CTX_TGT:
11418 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11419 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
11420 			rc = 0;
11421 		break;
11422 	case LPFC_CTX_HOST:
11423 		rc = 0;
11424 		break;
11425 	default:
11426 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
11427 			__func__, ctx_cmd);
11428 		break;
11429 	}
11430 
11431 	return rc;
11432 }
11433 
11434 /**
11435  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
11436  * @vport: Pointer to virtual port.
11437  * @tgt_id: SCSI ID of the target.
11438  * @lun_id: LUN ID of the scsi device.
11439  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11440  *
11441  * This function returns number of FCP commands pending for the vport.
11442  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
11443  * commands pending on the vport associated with SCSI device specified
11444  * by tgt_id and lun_id parameters.
11445  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
11446  * commands pending on the vport associated with SCSI target specified
11447  * by tgt_id parameter.
11448  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
11449  * commands pending on the vport.
11450  * This function returns the number of iocbs which satisfy the filter.
11451  * This function is called without any lock held.
11452  **/
11453 int
11454 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
11455 		  lpfc_ctx_cmd ctx_cmd)
11456 {
11457 	struct lpfc_hba *phba = vport->phba;
11458 	struct lpfc_iocbq *iocbq;
11459 	int sum, i;
11460 
11461 	spin_lock_irq(&phba->hbalock);
11462 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
11463 		iocbq = phba->sli.iocbq_lookup[i];
11464 
11465 		if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
11466 						ctx_cmd) == 0)
11467 			sum++;
11468 	}
11469 	spin_unlock_irq(&phba->hbalock);
11470 
11471 	return sum;
11472 }
11473 
11474 /**
11475  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
11476  * @phba: Pointer to HBA context object
11477  * @cmdiocb: Pointer to command iocb object.
11478  * @rspiocb: Pointer to response iocb object.
11479  *
11480  * This function is called when an aborted FCP iocb completes. This
11481  * function is called by the ring event handler with no lock held.
11482  * This function frees the iocb.
11483  **/
11484 void
11485 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11486 			struct lpfc_iocbq *rspiocb)
11487 {
11488 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11489 			"3096 ABORT_XRI_CN completing on rpi x%x "
11490 			"original iotag x%x, abort cmd iotag x%x "
11491 			"status 0x%x, reason 0x%x\n",
11492 			cmdiocb->iocb.un.acxri.abortContextTag,
11493 			cmdiocb->iocb.un.acxri.abortIoTag,
11494 			cmdiocb->iotag, rspiocb->iocb.ulpStatus,
11495 			rspiocb->iocb.un.ulpWord[4]);
11496 	lpfc_sli_release_iocbq(phba, cmdiocb);
11497 	return;
11498 }
11499 
11500 /**
11501  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
11502  * @vport: Pointer to virtual port.
11503  * @pring: Pointer to driver SLI ring object.
11504  * @tgt_id: SCSI ID of the target.
11505  * @lun_id: LUN ID of the scsi device.
11506  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11507  *
11508  * This function sends an abort command for every SCSI command
11509  * associated with the given virtual port pending on the ring
11510  * filtered by lpfc_sli_validate_fcp_iocb function.
11511  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
11512  * FCP iocbs associated with lun specified by tgt_id and lun_id
11513  * parameters
11514  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
11515  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
11516  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
11517  * FCP iocbs associated with virtual port.
11518  * This function returns number of iocbs it failed to abort.
11519  * This function is called with no locks held.
11520  **/
11521 int
11522 lpfc_sli_abort_iocb(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
11523 		    uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd abort_cmd)
11524 {
11525 	struct lpfc_hba *phba = vport->phba;
11526 	struct lpfc_iocbq *iocbq;
11527 	struct lpfc_iocbq *abtsiocb;
11528 	struct lpfc_sli_ring *pring_s4;
11529 	IOCB_t *cmd = NULL;
11530 	int errcnt = 0, ret_val = 0;
11531 	int i;
11532 
11533 	/* all I/Os are in process of being flushed */
11534 	if (phba->hba_flag & HBA_IOQ_FLUSH)
11535 		return errcnt;
11536 
11537 	for (i = 1; i <= phba->sli.last_iotag; i++) {
11538 		iocbq = phba->sli.iocbq_lookup[i];
11539 
11540 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
11541 					       abort_cmd) != 0)
11542 			continue;
11543 
11544 		/*
11545 		 * If the iocbq is already being aborted, don't take a second
11546 		 * action, but do count it.
11547 		 */
11548 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
11549 			continue;
11550 
11551 		/* issue ABTS for this IOCB based on iotag */
11552 		abtsiocb = lpfc_sli_get_iocbq(phba);
11553 		if (abtsiocb == NULL) {
11554 			errcnt++;
11555 			continue;
11556 		}
11557 
11558 		/* indicate the IO is being aborted by the driver. */
11559 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
11560 
11561 		cmd = &iocbq->iocb;
11562 		abtsiocb->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
11563 		abtsiocb->iocb.un.acxri.abortContextTag = cmd->ulpContext;
11564 		if (phba->sli_rev == LPFC_SLI_REV4)
11565 			abtsiocb->iocb.un.acxri.abortIoTag = iocbq->sli4_xritag;
11566 		else
11567 			abtsiocb->iocb.un.acxri.abortIoTag = cmd->ulpIoTag;
11568 		abtsiocb->iocb.ulpLe = 1;
11569 		abtsiocb->iocb.ulpClass = cmd->ulpClass;
11570 		abtsiocb->vport = vport;
11571 
11572 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11573 		abtsiocb->hba_wqidx = iocbq->hba_wqidx;
11574 		if (iocbq->iocb_flag & LPFC_IO_FCP)
11575 			abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
11576 		if (iocbq->iocb_flag & LPFC_IO_FOF)
11577 			abtsiocb->iocb_flag |= LPFC_IO_FOF;
11578 
11579 		if (lpfc_is_link_up(phba))
11580 			abtsiocb->iocb.ulpCommand = CMD_ABORT_XRI_CN;
11581 		else
11582 			abtsiocb->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
11583 
11584 		/* Setup callback routine and issue the command. */
11585 		abtsiocb->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
11586 		if (phba->sli_rev == LPFC_SLI_REV4) {
11587 			pring_s4 = lpfc_sli4_calc_ring(phba, iocbq);
11588 			if (!pring_s4)
11589 				continue;
11590 			ret_val = lpfc_sli_issue_iocb(phba, pring_s4->ringno,
11591 						      abtsiocb, 0);
11592 		} else
11593 			ret_val = lpfc_sli_issue_iocb(phba, pring->ringno,
11594 						      abtsiocb, 0);
11595 		if (ret_val == IOCB_ERROR) {
11596 			lpfc_sli_release_iocbq(phba, abtsiocb);
11597 			errcnt++;
11598 			continue;
11599 		}
11600 	}
11601 
11602 	return errcnt;
11603 }
11604 
11605 /**
11606  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
11607  * @vport: Pointer to virtual port.
11608  * @pring: Pointer to driver SLI ring object.
11609  * @tgt_id: SCSI ID of the target.
11610  * @lun_id: LUN ID of the scsi device.
11611  * @taskmgmt_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11612  *
11613  * This function sends an abort command for every SCSI command
11614  * associated with the given virtual port pending on the ring
11615  * filtered by lpfc_sli_validate_fcp_iocb function.
11616  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
11617  * FCP iocbs associated with lun specified by tgt_id and lun_id
11618  * parameters
11619  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
11620  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
11621  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
11622  * FCP iocbs associated with virtual port.
11623  * This function returns number of iocbs it aborted .
11624  * This function is called with no locks held right after a taskmgmt
11625  * command is sent.
11626  **/
11627 int
11628 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
11629 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
11630 {
11631 	struct lpfc_hba *phba = vport->phba;
11632 	struct lpfc_io_buf *lpfc_cmd;
11633 	struct lpfc_iocbq *abtsiocbq;
11634 	struct lpfc_nodelist *ndlp;
11635 	struct lpfc_iocbq *iocbq;
11636 	IOCB_t *icmd;
11637 	int sum, i, ret_val;
11638 	unsigned long iflags;
11639 	struct lpfc_sli_ring *pring_s4 = NULL;
11640 
11641 	spin_lock_irqsave(&phba->hbalock, iflags);
11642 
11643 	/* all I/Os are in process of being flushed */
11644 	if (phba->hba_flag & HBA_IOQ_FLUSH) {
11645 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11646 		return 0;
11647 	}
11648 	sum = 0;
11649 
11650 	for (i = 1; i <= phba->sli.last_iotag; i++) {
11651 		iocbq = phba->sli.iocbq_lookup[i];
11652 
11653 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
11654 					       cmd) != 0)
11655 			continue;
11656 
11657 		/* Guard against IO completion being called at same time */
11658 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
11659 		spin_lock(&lpfc_cmd->buf_lock);
11660 
11661 		if (!lpfc_cmd->pCmd) {
11662 			spin_unlock(&lpfc_cmd->buf_lock);
11663 			continue;
11664 		}
11665 
11666 		if (phba->sli_rev == LPFC_SLI_REV4) {
11667 			pring_s4 =
11668 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
11669 			if (!pring_s4) {
11670 				spin_unlock(&lpfc_cmd->buf_lock);
11671 				continue;
11672 			}
11673 			/* Note: both hbalock and ring_lock must be set here */
11674 			spin_lock(&pring_s4->ring_lock);
11675 		}
11676 
11677 		/*
11678 		 * If the iocbq is already being aborted, don't take a second
11679 		 * action, but do count it.
11680 		 */
11681 		if ((iocbq->iocb_flag & LPFC_DRIVER_ABORTED) ||
11682 		    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ)) {
11683 			if (phba->sli_rev == LPFC_SLI_REV4)
11684 				spin_unlock(&pring_s4->ring_lock);
11685 			spin_unlock(&lpfc_cmd->buf_lock);
11686 			continue;
11687 		}
11688 
11689 		/* issue ABTS for this IOCB based on iotag */
11690 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
11691 		if (!abtsiocbq) {
11692 			if (phba->sli_rev == LPFC_SLI_REV4)
11693 				spin_unlock(&pring_s4->ring_lock);
11694 			spin_unlock(&lpfc_cmd->buf_lock);
11695 			continue;
11696 		}
11697 
11698 		icmd = &iocbq->iocb;
11699 		abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
11700 		abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
11701 		if (phba->sli_rev == LPFC_SLI_REV4)
11702 			abtsiocbq->iocb.un.acxri.abortIoTag =
11703 							 iocbq->sli4_xritag;
11704 		else
11705 			abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
11706 		abtsiocbq->iocb.ulpLe = 1;
11707 		abtsiocbq->iocb.ulpClass = icmd->ulpClass;
11708 		abtsiocbq->vport = vport;
11709 
11710 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11711 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
11712 		if (iocbq->iocb_flag & LPFC_IO_FCP)
11713 			abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
11714 		if (iocbq->iocb_flag & LPFC_IO_FOF)
11715 			abtsiocbq->iocb_flag |= LPFC_IO_FOF;
11716 
11717 		ndlp = lpfc_cmd->rdata->pnode;
11718 
11719 		if (lpfc_is_link_up(phba) &&
11720 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
11721 			abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
11722 		else
11723 			abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
11724 
11725 		/* Setup callback routine and issue the command. */
11726 		abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
11727 
11728 		/*
11729 		 * Indicate the IO is being aborted by the driver and set
11730 		 * the caller's flag into the aborted IO.
11731 		 */
11732 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
11733 
11734 		if (phba->sli_rev == LPFC_SLI_REV4) {
11735 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
11736 							abtsiocbq, 0);
11737 			spin_unlock(&pring_s4->ring_lock);
11738 		} else {
11739 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
11740 							abtsiocbq, 0);
11741 		}
11742 
11743 		spin_unlock(&lpfc_cmd->buf_lock);
11744 
11745 		if (ret_val == IOCB_ERROR)
11746 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
11747 		else
11748 			sum++;
11749 	}
11750 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11751 	return sum;
11752 }
11753 
11754 /**
11755  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
11756  * @phba: Pointer to HBA context object.
11757  * @cmdiocbq: Pointer to command iocb.
11758  * @rspiocbq: Pointer to response iocb.
11759  *
11760  * This function is the completion handler for iocbs issued using
11761  * lpfc_sli_issue_iocb_wait function. This function is called by the
11762  * ring event handler function without any lock held. This function
11763  * can be called from both worker thread context and interrupt
11764  * context. This function also can be called from other thread which
11765  * cleans up the SLI layer objects.
11766  * This function copy the contents of the response iocb to the
11767  * response iocb memory object provided by the caller of
11768  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
11769  * sleeps for the iocb completion.
11770  **/
11771 static void
11772 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
11773 			struct lpfc_iocbq *cmdiocbq,
11774 			struct lpfc_iocbq *rspiocbq)
11775 {
11776 	wait_queue_head_t *pdone_q;
11777 	unsigned long iflags;
11778 	struct lpfc_io_buf *lpfc_cmd;
11779 
11780 	spin_lock_irqsave(&phba->hbalock, iflags);
11781 	if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
11782 
11783 		/*
11784 		 * A time out has occurred for the iocb.  If a time out
11785 		 * completion handler has been supplied, call it.  Otherwise,
11786 		 * just free the iocbq.
11787 		 */
11788 
11789 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11790 		cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
11791 		cmdiocbq->wait_iocb_cmpl = NULL;
11792 		if (cmdiocbq->iocb_cmpl)
11793 			(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
11794 		else
11795 			lpfc_sli_release_iocbq(phba, cmdiocbq);
11796 		return;
11797 	}
11798 
11799 	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
11800 	if (cmdiocbq->context2 && rspiocbq)
11801 		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
11802 		       &rspiocbq->iocb, sizeof(IOCB_t));
11803 
11804 	/* Set the exchange busy flag for task management commands */
11805 	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
11806 		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
11807 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
11808 			cur_iocbq);
11809 		if (rspiocbq && (rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY))
11810 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
11811 		else
11812 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
11813 	}
11814 
11815 	pdone_q = cmdiocbq->context_un.wait_queue;
11816 	if (pdone_q)
11817 		wake_up(pdone_q);
11818 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11819 	return;
11820 }
11821 
11822 /**
11823  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
11824  * @phba: Pointer to HBA context object..
11825  * @piocbq: Pointer to command iocb.
11826  * @flag: Flag to test.
11827  *
11828  * This routine grabs the hbalock and then test the iocb_flag to
11829  * see if the passed in flag is set.
11830  * Returns:
11831  * 1 if flag is set.
11832  * 0 if flag is not set.
11833  **/
11834 static int
11835 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
11836 		 struct lpfc_iocbq *piocbq, uint32_t flag)
11837 {
11838 	unsigned long iflags;
11839 	int ret;
11840 
11841 	spin_lock_irqsave(&phba->hbalock, iflags);
11842 	ret = piocbq->iocb_flag & flag;
11843 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11844 	return ret;
11845 
11846 }
11847 
11848 /**
11849  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
11850  * @phba: Pointer to HBA context object..
11851  * @pring: Pointer to sli ring.
11852  * @piocb: Pointer to command iocb.
11853  * @prspiocbq: Pointer to response iocb.
11854  * @timeout: Timeout in number of seconds.
11855  *
11856  * This function issues the iocb to firmware and waits for the
11857  * iocb to complete. The iocb_cmpl field of the shall be used
11858  * to handle iocbs which time out. If the field is NULL, the
11859  * function shall free the iocbq structure.  If more clean up is
11860  * needed, the caller is expected to provide a completion function
11861  * that will provide the needed clean up.  If the iocb command is
11862  * not completed within timeout seconds, the function will either
11863  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
11864  * completion function set in the iocb_cmpl field and then return
11865  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
11866  * resources if this function returns IOCB_TIMEDOUT.
11867  * The function waits for the iocb completion using an
11868  * non-interruptible wait.
11869  * This function will sleep while waiting for iocb completion.
11870  * So, this function should not be called from any context which
11871  * does not allow sleeping. Due to the same reason, this function
11872  * cannot be called with interrupt disabled.
11873  * This function assumes that the iocb completions occur while
11874  * this function sleep. So, this function cannot be called from
11875  * the thread which process iocb completion for this ring.
11876  * This function clears the iocb_flag of the iocb object before
11877  * issuing the iocb and the iocb completion handler sets this
11878  * flag and wakes this thread when the iocb completes.
11879  * The contents of the response iocb will be copied to prspiocbq
11880  * by the completion handler when the command completes.
11881  * This function returns IOCB_SUCCESS when success.
11882  * This function is called with no lock held.
11883  **/
11884 int
11885 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
11886 			 uint32_t ring_number,
11887 			 struct lpfc_iocbq *piocb,
11888 			 struct lpfc_iocbq *prspiocbq,
11889 			 uint32_t timeout)
11890 {
11891 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
11892 	long timeleft, timeout_req = 0;
11893 	int retval = IOCB_SUCCESS;
11894 	uint32_t creg_val;
11895 	struct lpfc_iocbq *iocb;
11896 	int txq_cnt = 0;
11897 	int txcmplq_cnt = 0;
11898 	struct lpfc_sli_ring *pring;
11899 	unsigned long iflags;
11900 	bool iocb_completed = true;
11901 
11902 	if (phba->sli_rev >= LPFC_SLI_REV4)
11903 		pring = lpfc_sli4_calc_ring(phba, piocb);
11904 	else
11905 		pring = &phba->sli.sli3_ring[ring_number];
11906 	/*
11907 	 * If the caller has provided a response iocbq buffer, then context2
11908 	 * is NULL or its an error.
11909 	 */
11910 	if (prspiocbq) {
11911 		if (piocb->context2)
11912 			return IOCB_ERROR;
11913 		piocb->context2 = prspiocbq;
11914 	}
11915 
11916 	piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
11917 	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
11918 	piocb->context_un.wait_queue = &done_q;
11919 	piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
11920 
11921 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
11922 		if (lpfc_readl(phba->HCregaddr, &creg_val))
11923 			return IOCB_ERROR;
11924 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
11925 		writel(creg_val, phba->HCregaddr);
11926 		readl(phba->HCregaddr); /* flush */
11927 	}
11928 
11929 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
11930 				     SLI_IOCB_RET_IOCB);
11931 	if (retval == IOCB_SUCCESS) {
11932 		timeout_req = msecs_to_jiffies(timeout * 1000);
11933 		timeleft = wait_event_timeout(done_q,
11934 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
11935 				timeout_req);
11936 		spin_lock_irqsave(&phba->hbalock, iflags);
11937 		if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
11938 
11939 			/*
11940 			 * IOCB timed out.  Inform the wake iocb wait
11941 			 * completion function and set local status
11942 			 */
11943 
11944 			iocb_completed = false;
11945 			piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
11946 		}
11947 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11948 		if (iocb_completed) {
11949 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11950 					"0331 IOCB wake signaled\n");
11951 			/* Note: we are not indicating if the IOCB has a success
11952 			 * status or not - that's for the caller to check.
11953 			 * IOCB_SUCCESS means just that the command was sent and
11954 			 * completed. Not that it completed successfully.
11955 			 * */
11956 		} else if (timeleft == 0) {
11957 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11958 					"0338 IOCB wait timeout error - no "
11959 					"wake response Data x%x\n", timeout);
11960 			retval = IOCB_TIMEDOUT;
11961 		} else {
11962 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11963 					"0330 IOCB wake NOT set, "
11964 					"Data x%x x%lx\n",
11965 					timeout, (timeleft / jiffies));
11966 			retval = IOCB_TIMEDOUT;
11967 		}
11968 	} else if (retval == IOCB_BUSY) {
11969 		if (phba->cfg_log_verbose & LOG_SLI) {
11970 			list_for_each_entry(iocb, &pring->txq, list) {
11971 				txq_cnt++;
11972 			}
11973 			list_for_each_entry(iocb, &pring->txcmplq, list) {
11974 				txcmplq_cnt++;
11975 			}
11976 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11977 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
11978 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
11979 		}
11980 		return retval;
11981 	} else {
11982 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11983 				"0332 IOCB wait issue failed, Data x%x\n",
11984 				retval);
11985 		retval = IOCB_ERROR;
11986 	}
11987 
11988 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
11989 		if (lpfc_readl(phba->HCregaddr, &creg_val))
11990 			return IOCB_ERROR;
11991 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
11992 		writel(creg_val, phba->HCregaddr);
11993 		readl(phba->HCregaddr); /* flush */
11994 	}
11995 
11996 	if (prspiocbq)
11997 		piocb->context2 = NULL;
11998 
11999 	piocb->context_un.wait_queue = NULL;
12000 	piocb->iocb_cmpl = NULL;
12001 	return retval;
12002 }
12003 
12004 /**
12005  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
12006  * @phba: Pointer to HBA context object.
12007  * @pmboxq: Pointer to driver mailbox object.
12008  * @timeout: Timeout in number of seconds.
12009  *
12010  * This function issues the mailbox to firmware and waits for the
12011  * mailbox command to complete. If the mailbox command is not
12012  * completed within timeout seconds, it returns MBX_TIMEOUT.
12013  * The function waits for the mailbox completion using an
12014  * interruptible wait. If the thread is woken up due to a
12015  * signal, MBX_TIMEOUT error is returned to the caller. Caller
12016  * should not free the mailbox resources, if this function returns
12017  * MBX_TIMEOUT.
12018  * This function will sleep while waiting for mailbox completion.
12019  * So, this function should not be called from any context which
12020  * does not allow sleeping. Due to the same reason, this function
12021  * cannot be called with interrupt disabled.
12022  * This function assumes that the mailbox completion occurs while
12023  * this function sleep. So, this function cannot be called from
12024  * the worker thread which processes mailbox completion.
12025  * This function is called in the context of HBA management
12026  * applications.
12027  * This function returns MBX_SUCCESS when successful.
12028  * This function is called with no lock held.
12029  **/
12030 int
12031 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
12032 			 uint32_t timeout)
12033 {
12034 	struct completion mbox_done;
12035 	int retval;
12036 	unsigned long flag;
12037 
12038 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
12039 	/* setup wake call as IOCB callback */
12040 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
12041 
12042 	/* setup context3 field to pass wait_queue pointer to wake function  */
12043 	init_completion(&mbox_done);
12044 	pmboxq->context3 = &mbox_done;
12045 	/* now issue the command */
12046 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
12047 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
12048 		wait_for_completion_timeout(&mbox_done,
12049 					    msecs_to_jiffies(timeout * 1000));
12050 
12051 		spin_lock_irqsave(&phba->hbalock, flag);
12052 		pmboxq->context3 = NULL;
12053 		/*
12054 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
12055 		 * else do not free the resources.
12056 		 */
12057 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
12058 			retval = MBX_SUCCESS;
12059 		} else {
12060 			retval = MBX_TIMEOUT;
12061 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
12062 		}
12063 		spin_unlock_irqrestore(&phba->hbalock, flag);
12064 	}
12065 	return retval;
12066 }
12067 
12068 /**
12069  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
12070  * @phba: Pointer to HBA context.
12071  *
12072  * This function is called to shutdown the driver's mailbox sub-system.
12073  * It first marks the mailbox sub-system is in a block state to prevent
12074  * the asynchronous mailbox command from issued off the pending mailbox
12075  * command queue. If the mailbox command sub-system shutdown is due to
12076  * HBA error conditions such as EEH or ERATT, this routine shall invoke
12077  * the mailbox sub-system flush routine to forcefully bring down the
12078  * mailbox sub-system. Otherwise, if it is due to normal condition (such
12079  * as with offline or HBA function reset), this routine will wait for the
12080  * outstanding mailbox command to complete before invoking the mailbox
12081  * sub-system flush routine to gracefully bring down mailbox sub-system.
12082  **/
12083 void
12084 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
12085 {
12086 	struct lpfc_sli *psli = &phba->sli;
12087 	unsigned long timeout;
12088 
12089 	if (mbx_action == LPFC_MBX_NO_WAIT) {
12090 		/* delay 100ms for port state */
12091 		msleep(100);
12092 		lpfc_sli_mbox_sys_flush(phba);
12093 		return;
12094 	}
12095 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
12096 
12097 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12098 	local_bh_disable();
12099 
12100 	spin_lock_irq(&phba->hbalock);
12101 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
12102 
12103 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
12104 		/* Determine how long we might wait for the active mailbox
12105 		 * command to be gracefully completed by firmware.
12106 		 */
12107 		if (phba->sli.mbox_active)
12108 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
12109 						phba->sli.mbox_active) *
12110 						1000) + jiffies;
12111 		spin_unlock_irq(&phba->hbalock);
12112 
12113 		/* Enable softirqs again, done with phba->hbalock */
12114 		local_bh_enable();
12115 
12116 		while (phba->sli.mbox_active) {
12117 			/* Check active mailbox complete status every 2ms */
12118 			msleep(2);
12119 			if (time_after(jiffies, timeout))
12120 				/* Timeout, let the mailbox flush routine to
12121 				 * forcefully release active mailbox command
12122 				 */
12123 				break;
12124 		}
12125 	} else {
12126 		spin_unlock_irq(&phba->hbalock);
12127 
12128 		/* Enable softirqs again, done with phba->hbalock */
12129 		local_bh_enable();
12130 	}
12131 
12132 	lpfc_sli_mbox_sys_flush(phba);
12133 }
12134 
12135 /**
12136  * lpfc_sli_eratt_read - read sli-3 error attention events
12137  * @phba: Pointer to HBA context.
12138  *
12139  * This function is called to read the SLI3 device error attention registers
12140  * for possible error attention events. The caller must hold the hostlock
12141  * with spin_lock_irq().
12142  *
12143  * This function returns 1 when there is Error Attention in the Host Attention
12144  * Register and returns 0 otherwise.
12145  **/
12146 static int
12147 lpfc_sli_eratt_read(struct lpfc_hba *phba)
12148 {
12149 	uint32_t ha_copy;
12150 
12151 	/* Read chip Host Attention (HA) register */
12152 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
12153 		goto unplug_err;
12154 
12155 	if (ha_copy & HA_ERATT) {
12156 		/* Read host status register to retrieve error event */
12157 		if (lpfc_sli_read_hs(phba))
12158 			goto unplug_err;
12159 
12160 		/* Check if there is a deferred error condition is active */
12161 		if ((HS_FFER1 & phba->work_hs) &&
12162 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12163 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
12164 			phba->hba_flag |= DEFER_ERATT;
12165 			/* Clear all interrupt enable conditions */
12166 			writel(0, phba->HCregaddr);
12167 			readl(phba->HCregaddr);
12168 		}
12169 
12170 		/* Set the driver HA work bitmap */
12171 		phba->work_ha |= HA_ERATT;
12172 		/* Indicate polling handles this ERATT */
12173 		phba->hba_flag |= HBA_ERATT_HANDLED;
12174 		return 1;
12175 	}
12176 	return 0;
12177 
12178 unplug_err:
12179 	/* Set the driver HS work bitmap */
12180 	phba->work_hs |= UNPLUG_ERR;
12181 	/* Set the driver HA work bitmap */
12182 	phba->work_ha |= HA_ERATT;
12183 	/* Indicate polling handles this ERATT */
12184 	phba->hba_flag |= HBA_ERATT_HANDLED;
12185 	return 1;
12186 }
12187 
12188 /**
12189  * lpfc_sli4_eratt_read - read sli-4 error attention events
12190  * @phba: Pointer to HBA context.
12191  *
12192  * This function is called to read the SLI4 device error attention registers
12193  * for possible error attention events. The caller must hold the hostlock
12194  * with spin_lock_irq().
12195  *
12196  * This function returns 1 when there is Error Attention in the Host Attention
12197  * Register and returns 0 otherwise.
12198  **/
12199 static int
12200 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
12201 {
12202 	uint32_t uerr_sta_hi, uerr_sta_lo;
12203 	uint32_t if_type, portsmphr;
12204 	struct lpfc_register portstat_reg;
12205 
12206 	/*
12207 	 * For now, use the SLI4 device internal unrecoverable error
12208 	 * registers for error attention. This can be changed later.
12209 	 */
12210 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12211 	switch (if_type) {
12212 	case LPFC_SLI_INTF_IF_TYPE_0:
12213 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
12214 			&uerr_sta_lo) ||
12215 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
12216 			&uerr_sta_hi)) {
12217 			phba->work_hs |= UNPLUG_ERR;
12218 			phba->work_ha |= HA_ERATT;
12219 			phba->hba_flag |= HBA_ERATT_HANDLED;
12220 			return 1;
12221 		}
12222 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
12223 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
12224 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12225 					"1423 HBA Unrecoverable error: "
12226 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
12227 					"ue_mask_lo_reg=0x%x, "
12228 					"ue_mask_hi_reg=0x%x\n",
12229 					uerr_sta_lo, uerr_sta_hi,
12230 					phba->sli4_hba.ue_mask_lo,
12231 					phba->sli4_hba.ue_mask_hi);
12232 			phba->work_status[0] = uerr_sta_lo;
12233 			phba->work_status[1] = uerr_sta_hi;
12234 			phba->work_ha |= HA_ERATT;
12235 			phba->hba_flag |= HBA_ERATT_HANDLED;
12236 			return 1;
12237 		}
12238 		break;
12239 	case LPFC_SLI_INTF_IF_TYPE_2:
12240 	case LPFC_SLI_INTF_IF_TYPE_6:
12241 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
12242 			&portstat_reg.word0) ||
12243 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
12244 			&portsmphr)){
12245 			phba->work_hs |= UNPLUG_ERR;
12246 			phba->work_ha |= HA_ERATT;
12247 			phba->hba_flag |= HBA_ERATT_HANDLED;
12248 			return 1;
12249 		}
12250 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
12251 			phba->work_status[0] =
12252 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
12253 			phba->work_status[1] =
12254 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
12255 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12256 					"2885 Port Status Event: "
12257 					"port status reg 0x%x, "
12258 					"port smphr reg 0x%x, "
12259 					"error 1=0x%x, error 2=0x%x\n",
12260 					portstat_reg.word0,
12261 					portsmphr,
12262 					phba->work_status[0],
12263 					phba->work_status[1]);
12264 			phba->work_ha |= HA_ERATT;
12265 			phba->hba_flag |= HBA_ERATT_HANDLED;
12266 			return 1;
12267 		}
12268 		break;
12269 	case LPFC_SLI_INTF_IF_TYPE_1:
12270 	default:
12271 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12272 				"2886 HBA Error Attention on unsupported "
12273 				"if type %d.", if_type);
12274 		return 1;
12275 	}
12276 
12277 	return 0;
12278 }
12279 
12280 /**
12281  * lpfc_sli_check_eratt - check error attention events
12282  * @phba: Pointer to HBA context.
12283  *
12284  * This function is called from timer soft interrupt context to check HBA's
12285  * error attention register bit for error attention events.
12286  *
12287  * This function returns 1 when there is Error Attention in the Host Attention
12288  * Register and returns 0 otherwise.
12289  **/
12290 int
12291 lpfc_sli_check_eratt(struct lpfc_hba *phba)
12292 {
12293 	uint32_t ha_copy;
12294 
12295 	/* If somebody is waiting to handle an eratt, don't process it
12296 	 * here. The brdkill function will do this.
12297 	 */
12298 	if (phba->link_flag & LS_IGNORE_ERATT)
12299 		return 0;
12300 
12301 	/* Check if interrupt handler handles this ERATT */
12302 	spin_lock_irq(&phba->hbalock);
12303 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
12304 		/* Interrupt handler has handled ERATT */
12305 		spin_unlock_irq(&phba->hbalock);
12306 		return 0;
12307 	}
12308 
12309 	/*
12310 	 * If there is deferred error attention, do not check for error
12311 	 * attention
12312 	 */
12313 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12314 		spin_unlock_irq(&phba->hbalock);
12315 		return 0;
12316 	}
12317 
12318 	/* If PCI channel is offline, don't process it */
12319 	if (unlikely(pci_channel_offline(phba->pcidev))) {
12320 		spin_unlock_irq(&phba->hbalock);
12321 		return 0;
12322 	}
12323 
12324 	switch (phba->sli_rev) {
12325 	case LPFC_SLI_REV2:
12326 	case LPFC_SLI_REV3:
12327 		/* Read chip Host Attention (HA) register */
12328 		ha_copy = lpfc_sli_eratt_read(phba);
12329 		break;
12330 	case LPFC_SLI_REV4:
12331 		/* Read device Uncoverable Error (UERR) registers */
12332 		ha_copy = lpfc_sli4_eratt_read(phba);
12333 		break;
12334 	default:
12335 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12336 				"0299 Invalid SLI revision (%d)\n",
12337 				phba->sli_rev);
12338 		ha_copy = 0;
12339 		break;
12340 	}
12341 	spin_unlock_irq(&phba->hbalock);
12342 
12343 	return ha_copy;
12344 }
12345 
12346 /**
12347  * lpfc_intr_state_check - Check device state for interrupt handling
12348  * @phba: Pointer to HBA context.
12349  *
12350  * This inline routine checks whether a device or its PCI slot is in a state
12351  * that the interrupt should be handled.
12352  *
12353  * This function returns 0 if the device or the PCI slot is in a state that
12354  * interrupt should be handled, otherwise -EIO.
12355  */
12356 static inline int
12357 lpfc_intr_state_check(struct lpfc_hba *phba)
12358 {
12359 	/* If the pci channel is offline, ignore all the interrupts */
12360 	if (unlikely(pci_channel_offline(phba->pcidev)))
12361 		return -EIO;
12362 
12363 	/* Update device level interrupt statistics */
12364 	phba->sli.slistat.sli_intr++;
12365 
12366 	/* Ignore all interrupts during initialization. */
12367 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
12368 		return -EIO;
12369 
12370 	return 0;
12371 }
12372 
12373 /**
12374  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
12375  * @irq: Interrupt number.
12376  * @dev_id: The device context pointer.
12377  *
12378  * This function is directly called from the PCI layer as an interrupt
12379  * service routine when device with SLI-3 interface spec is enabled with
12380  * MSI-X multi-message interrupt mode and there are slow-path events in
12381  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
12382  * interrupt mode, this function is called as part of the device-level
12383  * interrupt handler. When the PCI slot is in error recovery or the HBA
12384  * is undergoing initialization, the interrupt handler will not process
12385  * the interrupt. The link attention and ELS ring attention events are
12386  * handled by the worker thread. The interrupt handler signals the worker
12387  * thread and returns for these events. This function is called without
12388  * any lock held. It gets the hbalock to access and update SLI data
12389  * structures.
12390  *
12391  * This function returns IRQ_HANDLED when interrupt is handled else it
12392  * returns IRQ_NONE.
12393  **/
12394 irqreturn_t
12395 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
12396 {
12397 	struct lpfc_hba  *phba;
12398 	uint32_t ha_copy, hc_copy;
12399 	uint32_t work_ha_copy;
12400 	unsigned long status;
12401 	unsigned long iflag;
12402 	uint32_t control;
12403 
12404 	MAILBOX_t *mbox, *pmbox;
12405 	struct lpfc_vport *vport;
12406 	struct lpfc_nodelist *ndlp;
12407 	struct lpfc_dmabuf *mp;
12408 	LPFC_MBOXQ_t *pmb;
12409 	int rc;
12410 
12411 	/*
12412 	 * Get the driver's phba structure from the dev_id and
12413 	 * assume the HBA is not interrupting.
12414 	 */
12415 	phba = (struct lpfc_hba *)dev_id;
12416 
12417 	if (unlikely(!phba))
12418 		return IRQ_NONE;
12419 
12420 	/*
12421 	 * Stuff needs to be attented to when this function is invoked as an
12422 	 * individual interrupt handler in MSI-X multi-message interrupt mode
12423 	 */
12424 	if (phba->intr_type == MSIX) {
12425 		/* Check device state for handling interrupt */
12426 		if (lpfc_intr_state_check(phba))
12427 			return IRQ_NONE;
12428 		/* Need to read HA REG for slow-path events */
12429 		spin_lock_irqsave(&phba->hbalock, iflag);
12430 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
12431 			goto unplug_error;
12432 		/* If somebody is waiting to handle an eratt don't process it
12433 		 * here. The brdkill function will do this.
12434 		 */
12435 		if (phba->link_flag & LS_IGNORE_ERATT)
12436 			ha_copy &= ~HA_ERATT;
12437 		/* Check the need for handling ERATT in interrupt handler */
12438 		if (ha_copy & HA_ERATT) {
12439 			if (phba->hba_flag & HBA_ERATT_HANDLED)
12440 				/* ERATT polling has handled ERATT */
12441 				ha_copy &= ~HA_ERATT;
12442 			else
12443 				/* Indicate interrupt handler handles ERATT */
12444 				phba->hba_flag |= HBA_ERATT_HANDLED;
12445 		}
12446 
12447 		/*
12448 		 * If there is deferred error attention, do not check for any
12449 		 * interrupt.
12450 		 */
12451 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12452 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12453 			return IRQ_NONE;
12454 		}
12455 
12456 		/* Clear up only attention source related to slow-path */
12457 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
12458 			goto unplug_error;
12459 
12460 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
12461 			HC_LAINT_ENA | HC_ERINT_ENA),
12462 			phba->HCregaddr);
12463 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
12464 			phba->HAregaddr);
12465 		writel(hc_copy, phba->HCregaddr);
12466 		readl(phba->HAregaddr); /* flush */
12467 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12468 	} else
12469 		ha_copy = phba->ha_copy;
12470 
12471 	work_ha_copy = ha_copy & phba->work_ha_mask;
12472 
12473 	if (work_ha_copy) {
12474 		if (work_ha_copy & HA_LATT) {
12475 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
12476 				/*
12477 				 * Turn off Link Attention interrupts
12478 				 * until CLEAR_LA done
12479 				 */
12480 				spin_lock_irqsave(&phba->hbalock, iflag);
12481 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
12482 				if (lpfc_readl(phba->HCregaddr, &control))
12483 					goto unplug_error;
12484 				control &= ~HC_LAINT_ENA;
12485 				writel(control, phba->HCregaddr);
12486 				readl(phba->HCregaddr); /* flush */
12487 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12488 			}
12489 			else
12490 				work_ha_copy &= ~HA_LATT;
12491 		}
12492 
12493 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
12494 			/*
12495 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
12496 			 * the only slow ring.
12497 			 */
12498 			status = (work_ha_copy &
12499 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
12500 			status >>= (4*LPFC_ELS_RING);
12501 			if (status & HA_RXMASK) {
12502 				spin_lock_irqsave(&phba->hbalock, iflag);
12503 				if (lpfc_readl(phba->HCregaddr, &control))
12504 					goto unplug_error;
12505 
12506 				lpfc_debugfs_slow_ring_trc(phba,
12507 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
12508 				control, status,
12509 				(uint32_t)phba->sli.slistat.sli_intr);
12510 
12511 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
12512 					lpfc_debugfs_slow_ring_trc(phba,
12513 						"ISR Disable ring:"
12514 						"pwork:x%x hawork:x%x wait:x%x",
12515 						phba->work_ha, work_ha_copy,
12516 						(uint32_t)((unsigned long)
12517 						&phba->work_waitq));
12518 
12519 					control &=
12520 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
12521 					writel(control, phba->HCregaddr);
12522 					readl(phba->HCregaddr); /* flush */
12523 				}
12524 				else {
12525 					lpfc_debugfs_slow_ring_trc(phba,
12526 						"ISR slow ring:   pwork:"
12527 						"x%x hawork:x%x wait:x%x",
12528 						phba->work_ha, work_ha_copy,
12529 						(uint32_t)((unsigned long)
12530 						&phba->work_waitq));
12531 				}
12532 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12533 			}
12534 		}
12535 		spin_lock_irqsave(&phba->hbalock, iflag);
12536 		if (work_ha_copy & HA_ERATT) {
12537 			if (lpfc_sli_read_hs(phba))
12538 				goto unplug_error;
12539 			/*
12540 			 * Check if there is a deferred error condition
12541 			 * is active
12542 			 */
12543 			if ((HS_FFER1 & phba->work_hs) &&
12544 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12545 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
12546 				  phba->work_hs)) {
12547 				phba->hba_flag |= DEFER_ERATT;
12548 				/* Clear all interrupt enable conditions */
12549 				writel(0, phba->HCregaddr);
12550 				readl(phba->HCregaddr);
12551 			}
12552 		}
12553 
12554 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
12555 			pmb = phba->sli.mbox_active;
12556 			pmbox = &pmb->u.mb;
12557 			mbox = phba->mbox;
12558 			vport = pmb->vport;
12559 
12560 			/* First check out the status word */
12561 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
12562 			if (pmbox->mbxOwner != OWN_HOST) {
12563 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12564 				/*
12565 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
12566 				 * mbxStatus <status>
12567 				 */
12568 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
12569 						LOG_SLI,
12570 						"(%d):0304 Stray Mailbox "
12571 						"Interrupt mbxCommand x%x "
12572 						"mbxStatus x%x\n",
12573 						(vport ? vport->vpi : 0),
12574 						pmbox->mbxCommand,
12575 						pmbox->mbxStatus);
12576 				/* clear mailbox attention bit */
12577 				work_ha_copy &= ~HA_MBATT;
12578 			} else {
12579 				phba->sli.mbox_active = NULL;
12580 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12581 				phba->last_completion_time = jiffies;
12582 				del_timer(&phba->sli.mbox_tmo);
12583 				if (pmb->mbox_cmpl) {
12584 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
12585 							MAILBOX_CMD_SIZE);
12586 					if (pmb->out_ext_byte_len &&
12587 						pmb->ctx_buf)
12588 						lpfc_sli_pcimem_bcopy(
12589 						phba->mbox_ext,
12590 						pmb->ctx_buf,
12591 						pmb->out_ext_byte_len);
12592 				}
12593 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
12594 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
12595 
12596 					lpfc_debugfs_disc_trc(vport,
12597 						LPFC_DISC_TRC_MBOX_VPORT,
12598 						"MBOX dflt rpi: : "
12599 						"status:x%x rpi:x%x",
12600 						(uint32_t)pmbox->mbxStatus,
12601 						pmbox->un.varWords[0], 0);
12602 
12603 					if (!pmbox->mbxStatus) {
12604 						mp = (struct lpfc_dmabuf *)
12605 							(pmb->ctx_buf);
12606 						ndlp = (struct lpfc_nodelist *)
12607 							pmb->ctx_ndlp;
12608 
12609 						/* Reg_LOGIN of dflt RPI was
12610 						 * successful. new lets get
12611 						 * rid of the RPI using the
12612 						 * same mbox buffer.
12613 						 */
12614 						lpfc_unreg_login(phba,
12615 							vport->vpi,
12616 							pmbox->un.varWords[0],
12617 							pmb);
12618 						pmb->mbox_cmpl =
12619 							lpfc_mbx_cmpl_dflt_rpi;
12620 						pmb->ctx_buf = mp;
12621 						pmb->ctx_ndlp = ndlp;
12622 						pmb->vport = vport;
12623 						rc = lpfc_sli_issue_mbox(phba,
12624 								pmb,
12625 								MBX_NOWAIT);
12626 						if (rc != MBX_BUSY)
12627 							lpfc_printf_log(phba,
12628 							KERN_ERR,
12629 							LOG_MBOX | LOG_SLI,
12630 							"0350 rc should have"
12631 							"been MBX_BUSY\n");
12632 						if (rc != MBX_NOT_FINISHED)
12633 							goto send_current_mbox;
12634 					}
12635 				}
12636 				spin_lock_irqsave(
12637 						&phba->pport->work_port_lock,
12638 						iflag);
12639 				phba->pport->work_port_events &=
12640 					~WORKER_MBOX_TMO;
12641 				spin_unlock_irqrestore(
12642 						&phba->pport->work_port_lock,
12643 						iflag);
12644 				lpfc_mbox_cmpl_put(phba, pmb);
12645 			}
12646 		} else
12647 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12648 
12649 		if ((work_ha_copy & HA_MBATT) &&
12650 		    (phba->sli.mbox_active == NULL)) {
12651 send_current_mbox:
12652 			/* Process next mailbox command if there is one */
12653 			do {
12654 				rc = lpfc_sli_issue_mbox(phba, NULL,
12655 							 MBX_NOWAIT);
12656 			} while (rc == MBX_NOT_FINISHED);
12657 			if (rc != MBX_SUCCESS)
12658 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
12659 						LOG_SLI, "0349 rc should be "
12660 						"MBX_SUCCESS\n");
12661 		}
12662 
12663 		spin_lock_irqsave(&phba->hbalock, iflag);
12664 		phba->work_ha |= work_ha_copy;
12665 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12666 		lpfc_worker_wake_up(phba);
12667 	}
12668 	return IRQ_HANDLED;
12669 unplug_error:
12670 	spin_unlock_irqrestore(&phba->hbalock, iflag);
12671 	return IRQ_HANDLED;
12672 
12673 } /* lpfc_sli_sp_intr_handler */
12674 
12675 /**
12676  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
12677  * @irq: Interrupt number.
12678  * @dev_id: The device context pointer.
12679  *
12680  * This function is directly called from the PCI layer as an interrupt
12681  * service routine when device with SLI-3 interface spec is enabled with
12682  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
12683  * ring event in the HBA. However, when the device is enabled with either
12684  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
12685  * device-level interrupt handler. When the PCI slot is in error recovery
12686  * or the HBA is undergoing initialization, the interrupt handler will not
12687  * process the interrupt. The SCSI FCP fast-path ring event are handled in
12688  * the intrrupt context. This function is called without any lock held.
12689  * It gets the hbalock to access and update SLI data structures.
12690  *
12691  * This function returns IRQ_HANDLED when interrupt is handled else it
12692  * returns IRQ_NONE.
12693  **/
12694 irqreturn_t
12695 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
12696 {
12697 	struct lpfc_hba  *phba;
12698 	uint32_t ha_copy;
12699 	unsigned long status;
12700 	unsigned long iflag;
12701 	struct lpfc_sli_ring *pring;
12702 
12703 	/* Get the driver's phba structure from the dev_id and
12704 	 * assume the HBA is not interrupting.
12705 	 */
12706 	phba = (struct lpfc_hba *) dev_id;
12707 
12708 	if (unlikely(!phba))
12709 		return IRQ_NONE;
12710 
12711 	/*
12712 	 * Stuff needs to be attented to when this function is invoked as an
12713 	 * individual interrupt handler in MSI-X multi-message interrupt mode
12714 	 */
12715 	if (phba->intr_type == MSIX) {
12716 		/* Check device state for handling interrupt */
12717 		if (lpfc_intr_state_check(phba))
12718 			return IRQ_NONE;
12719 		/* Need to read HA REG for FCP ring and other ring events */
12720 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
12721 			return IRQ_HANDLED;
12722 		/* Clear up only attention source related to fast-path */
12723 		spin_lock_irqsave(&phba->hbalock, iflag);
12724 		/*
12725 		 * If there is deferred error attention, do not check for
12726 		 * any interrupt.
12727 		 */
12728 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12729 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12730 			return IRQ_NONE;
12731 		}
12732 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
12733 			phba->HAregaddr);
12734 		readl(phba->HAregaddr); /* flush */
12735 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12736 	} else
12737 		ha_copy = phba->ha_copy;
12738 
12739 	/*
12740 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
12741 	 */
12742 	ha_copy &= ~(phba->work_ha_mask);
12743 
12744 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
12745 	status >>= (4*LPFC_FCP_RING);
12746 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12747 	if (status & HA_RXMASK)
12748 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
12749 
12750 	if (phba->cfg_multi_ring_support == 2) {
12751 		/*
12752 		 * Process all events on extra ring. Take the optimized path
12753 		 * for extra ring IO.
12754 		 */
12755 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
12756 		status >>= (4*LPFC_EXTRA_RING);
12757 		if (status & HA_RXMASK) {
12758 			lpfc_sli_handle_fast_ring_event(phba,
12759 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
12760 					status);
12761 		}
12762 	}
12763 	return IRQ_HANDLED;
12764 }  /* lpfc_sli_fp_intr_handler */
12765 
12766 /**
12767  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
12768  * @irq: Interrupt number.
12769  * @dev_id: The device context pointer.
12770  *
12771  * This function is the HBA device-level interrupt handler to device with
12772  * SLI-3 interface spec, called from the PCI layer when either MSI or
12773  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
12774  * requires driver attention. This function invokes the slow-path interrupt
12775  * attention handling function and fast-path interrupt attention handling
12776  * function in turn to process the relevant HBA attention events. This
12777  * function is called without any lock held. It gets the hbalock to access
12778  * and update SLI data structures.
12779  *
12780  * This function returns IRQ_HANDLED when interrupt is handled, else it
12781  * returns IRQ_NONE.
12782  **/
12783 irqreturn_t
12784 lpfc_sli_intr_handler(int irq, void *dev_id)
12785 {
12786 	struct lpfc_hba  *phba;
12787 	irqreturn_t sp_irq_rc, fp_irq_rc;
12788 	unsigned long status1, status2;
12789 	uint32_t hc_copy;
12790 
12791 	/*
12792 	 * Get the driver's phba structure from the dev_id and
12793 	 * assume the HBA is not interrupting.
12794 	 */
12795 	phba = (struct lpfc_hba *) dev_id;
12796 
12797 	if (unlikely(!phba))
12798 		return IRQ_NONE;
12799 
12800 	/* Check device state for handling interrupt */
12801 	if (lpfc_intr_state_check(phba))
12802 		return IRQ_NONE;
12803 
12804 	spin_lock(&phba->hbalock);
12805 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
12806 		spin_unlock(&phba->hbalock);
12807 		return IRQ_HANDLED;
12808 	}
12809 
12810 	if (unlikely(!phba->ha_copy)) {
12811 		spin_unlock(&phba->hbalock);
12812 		return IRQ_NONE;
12813 	} else if (phba->ha_copy & HA_ERATT) {
12814 		if (phba->hba_flag & HBA_ERATT_HANDLED)
12815 			/* ERATT polling has handled ERATT */
12816 			phba->ha_copy &= ~HA_ERATT;
12817 		else
12818 			/* Indicate interrupt handler handles ERATT */
12819 			phba->hba_flag |= HBA_ERATT_HANDLED;
12820 	}
12821 
12822 	/*
12823 	 * If there is deferred error attention, do not check for any interrupt.
12824 	 */
12825 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12826 		spin_unlock(&phba->hbalock);
12827 		return IRQ_NONE;
12828 	}
12829 
12830 	/* Clear attention sources except link and error attentions */
12831 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
12832 		spin_unlock(&phba->hbalock);
12833 		return IRQ_HANDLED;
12834 	}
12835 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
12836 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
12837 		phba->HCregaddr);
12838 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
12839 	writel(hc_copy, phba->HCregaddr);
12840 	readl(phba->HAregaddr); /* flush */
12841 	spin_unlock(&phba->hbalock);
12842 
12843 	/*
12844 	 * Invokes slow-path host attention interrupt handling as appropriate.
12845 	 */
12846 
12847 	/* status of events with mailbox and link attention */
12848 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
12849 
12850 	/* status of events with ELS ring */
12851 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
12852 	status2 >>= (4*LPFC_ELS_RING);
12853 
12854 	if (status1 || (status2 & HA_RXMASK))
12855 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
12856 	else
12857 		sp_irq_rc = IRQ_NONE;
12858 
12859 	/*
12860 	 * Invoke fast-path host attention interrupt handling as appropriate.
12861 	 */
12862 
12863 	/* status of events with FCP ring */
12864 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
12865 	status1 >>= (4*LPFC_FCP_RING);
12866 
12867 	/* status of events with extra ring */
12868 	if (phba->cfg_multi_ring_support == 2) {
12869 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
12870 		status2 >>= (4*LPFC_EXTRA_RING);
12871 	} else
12872 		status2 = 0;
12873 
12874 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
12875 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
12876 	else
12877 		fp_irq_rc = IRQ_NONE;
12878 
12879 	/* Return device-level interrupt handling status */
12880 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
12881 }  /* lpfc_sli_intr_handler */
12882 
12883 /**
12884  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
12885  * @phba: pointer to lpfc hba data structure.
12886  *
12887  * This routine is invoked by the worker thread to process all the pending
12888  * SLI4 els abort xri events.
12889  **/
12890 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
12891 {
12892 	struct lpfc_cq_event *cq_event;
12893 
12894 	/* First, declare the els xri abort event has been handled */
12895 	spin_lock_irq(&phba->hbalock);
12896 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
12897 	spin_unlock_irq(&phba->hbalock);
12898 	/* Now, handle all the els xri abort events */
12899 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
12900 		/* Get the first event from the head of the event queue */
12901 		spin_lock_irq(&phba->hbalock);
12902 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
12903 				 cq_event, struct lpfc_cq_event, list);
12904 		spin_unlock_irq(&phba->hbalock);
12905 		/* Notify aborted XRI for ELS work queue */
12906 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
12907 		/* Free the event processed back to the free pool */
12908 		lpfc_sli4_cq_event_release(phba, cq_event);
12909 	}
12910 }
12911 
12912 /**
12913  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
12914  * @phba: pointer to lpfc hba data structure
12915  * @pIocbIn: pointer to the rspiocbq
12916  * @pIocbOut: pointer to the cmdiocbq
12917  * @wcqe: pointer to the complete wcqe
12918  *
12919  * This routine transfers the fields of a command iocbq to a response iocbq
12920  * by copying all the IOCB fields from command iocbq and transferring the
12921  * completion status information from the complete wcqe.
12922  **/
12923 static void
12924 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
12925 			      struct lpfc_iocbq *pIocbIn,
12926 			      struct lpfc_iocbq *pIocbOut,
12927 			      struct lpfc_wcqe_complete *wcqe)
12928 {
12929 	int numBdes, i;
12930 	unsigned long iflags;
12931 	uint32_t status, max_response;
12932 	struct lpfc_dmabuf *dmabuf;
12933 	struct ulp_bde64 *bpl, bde;
12934 	size_t offset = offsetof(struct lpfc_iocbq, iocb);
12935 
12936 	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
12937 	       sizeof(struct lpfc_iocbq) - offset);
12938 	/* Map WCQE parameters into irspiocb parameters */
12939 	status = bf_get(lpfc_wcqe_c_status, wcqe);
12940 	pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
12941 	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
12942 		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
12943 			pIocbIn->iocb.un.fcpi.fcpi_parm =
12944 					pIocbOut->iocb.un.fcpi.fcpi_parm -
12945 					wcqe->total_data_placed;
12946 		else
12947 			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
12948 	else {
12949 		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
12950 		switch (pIocbOut->iocb.ulpCommand) {
12951 		case CMD_ELS_REQUEST64_CR:
12952 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
12953 			bpl  = (struct ulp_bde64 *)dmabuf->virt;
12954 			bde.tus.w = le32_to_cpu(bpl[1].tus.w);
12955 			max_response = bde.tus.f.bdeSize;
12956 			break;
12957 		case CMD_GEN_REQUEST64_CR:
12958 			max_response = 0;
12959 			if (!pIocbOut->context3)
12960 				break;
12961 			numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
12962 					sizeof(struct ulp_bde64);
12963 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
12964 			bpl = (struct ulp_bde64 *)dmabuf->virt;
12965 			for (i = 0; i < numBdes; i++) {
12966 				bde.tus.w = le32_to_cpu(bpl[i].tus.w);
12967 				if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
12968 					max_response += bde.tus.f.bdeSize;
12969 			}
12970 			break;
12971 		default:
12972 			max_response = wcqe->total_data_placed;
12973 			break;
12974 		}
12975 		if (max_response < wcqe->total_data_placed)
12976 			pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
12977 		else
12978 			pIocbIn->iocb.un.genreq64.bdl.bdeSize =
12979 				wcqe->total_data_placed;
12980 	}
12981 
12982 	/* Convert BG errors for completion status */
12983 	if (status == CQE_STATUS_DI_ERROR) {
12984 		pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
12985 
12986 		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
12987 			pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
12988 		else
12989 			pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
12990 
12991 		pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
12992 		if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
12993 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
12994 				BGS_GUARD_ERR_MASK;
12995 		if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
12996 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
12997 				BGS_APPTAG_ERR_MASK;
12998 		if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
12999 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13000 				BGS_REFTAG_ERR_MASK;
13001 
13002 		/* Check to see if there was any good data before the error */
13003 		if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
13004 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13005 				BGS_HI_WATER_MARK_PRESENT_MASK;
13006 			pIocbIn->iocb.unsli3.sli3_bg.bghm =
13007 				wcqe->total_data_placed;
13008 		}
13009 
13010 		/*
13011 		* Set ALL the error bits to indicate we don't know what
13012 		* type of error it is.
13013 		*/
13014 		if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
13015 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13016 				(BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
13017 				BGS_GUARD_ERR_MASK);
13018 	}
13019 
13020 	/* Pick up HBA exchange busy condition */
13021 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
13022 		spin_lock_irqsave(&phba->hbalock, iflags);
13023 		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
13024 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13025 	}
13026 }
13027 
13028 /**
13029  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
13030  * @phba: Pointer to HBA context object.
13031  * @wcqe: Pointer to work-queue completion queue entry.
13032  *
13033  * This routine handles an ELS work-queue completion event and construct
13034  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
13035  * discovery engine to handle.
13036  *
13037  * Return: Pointer to the receive IOCBQ, NULL otherwise.
13038  **/
13039 static struct lpfc_iocbq *
13040 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
13041 			       struct lpfc_iocbq *irspiocbq)
13042 {
13043 	struct lpfc_sli_ring *pring;
13044 	struct lpfc_iocbq *cmdiocbq;
13045 	struct lpfc_wcqe_complete *wcqe;
13046 	unsigned long iflags;
13047 
13048 	pring = lpfc_phba_elsring(phba);
13049 	if (unlikely(!pring))
13050 		return NULL;
13051 
13052 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
13053 	pring->stats.iocb_event++;
13054 	/* Look up the ELS command IOCB and create pseudo response IOCB */
13055 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
13056 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13057 	if (unlikely(!cmdiocbq)) {
13058 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13059 				"0386 ELS complete with no corresponding "
13060 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
13061 				wcqe->word0, wcqe->total_data_placed,
13062 				wcqe->parameter, wcqe->word3);
13063 		lpfc_sli_release_iocbq(phba, irspiocbq);
13064 		return NULL;
13065 	}
13066 
13067 	spin_lock_irqsave(&pring->ring_lock, iflags);
13068 	/* Put the iocb back on the txcmplq */
13069 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
13070 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
13071 
13072 	/* Fake the irspiocbq and copy necessary response information */
13073 	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
13074 
13075 	return irspiocbq;
13076 }
13077 
13078 inline struct lpfc_cq_event *
13079 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
13080 {
13081 	struct lpfc_cq_event *cq_event;
13082 
13083 	/* Allocate a new internal CQ_EVENT entry */
13084 	cq_event = lpfc_sli4_cq_event_alloc(phba);
13085 	if (!cq_event) {
13086 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13087 				"0602 Failed to alloc CQ_EVENT entry\n");
13088 		return NULL;
13089 	}
13090 
13091 	/* Move the CQE into the event */
13092 	memcpy(&cq_event->cqe, entry, size);
13093 	return cq_event;
13094 }
13095 
13096 /**
13097  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
13098  * @phba: Pointer to HBA context object.
13099  * @cqe: Pointer to mailbox completion queue entry.
13100  *
13101  * This routine process a mailbox completion queue entry with asynchronous
13102  * event.
13103  *
13104  * Return: true if work posted to worker thread, otherwise false.
13105  **/
13106 static bool
13107 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13108 {
13109 	struct lpfc_cq_event *cq_event;
13110 	unsigned long iflags;
13111 
13112 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13113 			"0392 Async Event: word0:x%x, word1:x%x, "
13114 			"word2:x%x, word3:x%x\n", mcqe->word0,
13115 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
13116 
13117 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
13118 	if (!cq_event)
13119 		return false;
13120 	spin_lock_irqsave(&phba->hbalock, iflags);
13121 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
13122 	/* Set the async event flag */
13123 	phba->hba_flag |= ASYNC_EVENT;
13124 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13125 
13126 	return true;
13127 }
13128 
13129 /**
13130  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
13131  * @phba: Pointer to HBA context object.
13132  * @cqe: Pointer to mailbox completion queue entry.
13133  *
13134  * This routine process a mailbox completion queue entry with mailbox
13135  * completion event.
13136  *
13137  * Return: true if work posted to worker thread, otherwise false.
13138  **/
13139 static bool
13140 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13141 {
13142 	uint32_t mcqe_status;
13143 	MAILBOX_t *mbox, *pmbox;
13144 	struct lpfc_mqe *mqe;
13145 	struct lpfc_vport *vport;
13146 	struct lpfc_nodelist *ndlp;
13147 	struct lpfc_dmabuf *mp;
13148 	unsigned long iflags;
13149 	LPFC_MBOXQ_t *pmb;
13150 	bool workposted = false;
13151 	int rc;
13152 
13153 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
13154 	if (!bf_get(lpfc_trailer_completed, mcqe))
13155 		goto out_no_mqe_complete;
13156 
13157 	/* Get the reference to the active mbox command */
13158 	spin_lock_irqsave(&phba->hbalock, iflags);
13159 	pmb = phba->sli.mbox_active;
13160 	if (unlikely(!pmb)) {
13161 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
13162 				"1832 No pending MBOX command to handle\n");
13163 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13164 		goto out_no_mqe_complete;
13165 	}
13166 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13167 	mqe = &pmb->u.mqe;
13168 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
13169 	mbox = phba->mbox;
13170 	vport = pmb->vport;
13171 
13172 	/* Reset heartbeat timer */
13173 	phba->last_completion_time = jiffies;
13174 	del_timer(&phba->sli.mbox_tmo);
13175 
13176 	/* Move mbox data to caller's mailbox region, do endian swapping */
13177 	if (pmb->mbox_cmpl && mbox)
13178 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
13179 
13180 	/*
13181 	 * For mcqe errors, conditionally move a modified error code to
13182 	 * the mbox so that the error will not be missed.
13183 	 */
13184 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
13185 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
13186 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
13187 			bf_set(lpfc_mqe_status, mqe,
13188 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
13189 	}
13190 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13191 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13192 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
13193 				      "MBOX dflt rpi: status:x%x rpi:x%x",
13194 				      mcqe_status,
13195 				      pmbox->un.varWords[0], 0);
13196 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
13197 			mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
13198 			ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
13199 			/* Reg_LOGIN of dflt RPI was successful. Now lets get
13200 			 * RID of the PPI using the same mbox buffer.
13201 			 */
13202 			lpfc_unreg_login(phba, vport->vpi,
13203 					 pmbox->un.varWords[0], pmb);
13204 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
13205 			pmb->ctx_buf = mp;
13206 			pmb->ctx_ndlp = ndlp;
13207 			pmb->vport = vport;
13208 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
13209 			if (rc != MBX_BUSY)
13210 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
13211 						LOG_SLI, "0385 rc should "
13212 						"have been MBX_BUSY\n");
13213 			if (rc != MBX_NOT_FINISHED)
13214 				goto send_current_mbox;
13215 		}
13216 	}
13217 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
13218 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
13219 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
13220 
13221 	/* There is mailbox completion work to do */
13222 	spin_lock_irqsave(&phba->hbalock, iflags);
13223 	__lpfc_mbox_cmpl_put(phba, pmb);
13224 	phba->work_ha |= HA_MBATT;
13225 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13226 	workposted = true;
13227 
13228 send_current_mbox:
13229 	spin_lock_irqsave(&phba->hbalock, iflags);
13230 	/* Release the mailbox command posting token */
13231 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13232 	/* Setting active mailbox pointer need to be in sync to flag clear */
13233 	phba->sli.mbox_active = NULL;
13234 	if (bf_get(lpfc_trailer_consumed, mcqe))
13235 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13236 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13237 	/* Wake up worker thread to post the next pending mailbox command */
13238 	lpfc_worker_wake_up(phba);
13239 	return workposted;
13240 
13241 out_no_mqe_complete:
13242 	spin_lock_irqsave(&phba->hbalock, iflags);
13243 	if (bf_get(lpfc_trailer_consumed, mcqe))
13244 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13245 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13246 	return false;
13247 }
13248 
13249 /**
13250  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
13251  * @phba: Pointer to HBA context object.
13252  * @cqe: Pointer to mailbox completion queue entry.
13253  *
13254  * This routine process a mailbox completion queue entry, it invokes the
13255  * proper mailbox complete handling or asynchronous event handling routine
13256  * according to the MCQE's async bit.
13257  *
13258  * Return: true if work posted to worker thread, otherwise false.
13259  **/
13260 static bool
13261 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13262 			 struct lpfc_cqe *cqe)
13263 {
13264 	struct lpfc_mcqe mcqe;
13265 	bool workposted;
13266 
13267 	cq->CQ_mbox++;
13268 
13269 	/* Copy the mailbox MCQE and convert endian order as needed */
13270 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
13271 
13272 	/* Invoke the proper event handling routine */
13273 	if (!bf_get(lpfc_trailer_async, &mcqe))
13274 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
13275 	else
13276 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
13277 	return workposted;
13278 }
13279 
13280 /**
13281  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
13282  * @phba: Pointer to HBA context object.
13283  * @cq: Pointer to associated CQ
13284  * @wcqe: Pointer to work-queue completion queue entry.
13285  *
13286  * This routine handles an ELS work-queue completion event.
13287  *
13288  * Return: true if work posted to worker thread, otherwise false.
13289  **/
13290 static bool
13291 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13292 			     struct lpfc_wcqe_complete *wcqe)
13293 {
13294 	struct lpfc_iocbq *irspiocbq;
13295 	unsigned long iflags;
13296 	struct lpfc_sli_ring *pring = cq->pring;
13297 	int txq_cnt = 0;
13298 	int txcmplq_cnt = 0;
13299 
13300 	/* Check for response status */
13301 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
13302 		/* Log the error status */
13303 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13304 				"0357 ELS CQE error: status=x%x: "
13305 				"CQE: %08x %08x %08x %08x\n",
13306 				bf_get(lpfc_wcqe_c_status, wcqe),
13307 				wcqe->word0, wcqe->total_data_placed,
13308 				wcqe->parameter, wcqe->word3);
13309 	}
13310 
13311 	/* Get an irspiocbq for later ELS response processing use */
13312 	irspiocbq = lpfc_sli_get_iocbq(phba);
13313 	if (!irspiocbq) {
13314 		if (!list_empty(&pring->txq))
13315 			txq_cnt++;
13316 		if (!list_empty(&pring->txcmplq))
13317 			txcmplq_cnt++;
13318 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13319 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
13320 			"els_txcmplq_cnt=%d\n",
13321 			txq_cnt, phba->iocb_cnt,
13322 			txcmplq_cnt);
13323 		return false;
13324 	}
13325 
13326 	/* Save off the slow-path queue event for work thread to process */
13327 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
13328 	spin_lock_irqsave(&phba->hbalock, iflags);
13329 	list_add_tail(&irspiocbq->cq_event.list,
13330 		      &phba->sli4_hba.sp_queue_event);
13331 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
13332 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13333 
13334 	return true;
13335 }
13336 
13337 /**
13338  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
13339  * @phba: Pointer to HBA context object.
13340  * @wcqe: Pointer to work-queue completion queue entry.
13341  *
13342  * This routine handles slow-path WQ entry consumed event by invoking the
13343  * proper WQ release routine to the slow-path WQ.
13344  **/
13345 static void
13346 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
13347 			     struct lpfc_wcqe_release *wcqe)
13348 {
13349 	/* sanity check on queue memory */
13350 	if (unlikely(!phba->sli4_hba.els_wq))
13351 		return;
13352 	/* Check for the slow-path ELS work queue */
13353 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
13354 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
13355 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
13356 	else
13357 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13358 				"2579 Slow-path wqe consume event carries "
13359 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
13360 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
13361 				phba->sli4_hba.els_wq->queue_id);
13362 }
13363 
13364 /**
13365  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
13366  * @phba: Pointer to HBA context object.
13367  * @cq: Pointer to a WQ completion queue.
13368  * @wcqe: Pointer to work-queue completion queue entry.
13369  *
13370  * This routine handles an XRI abort event.
13371  *
13372  * Return: true if work posted to worker thread, otherwise false.
13373  **/
13374 static bool
13375 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
13376 				   struct lpfc_queue *cq,
13377 				   struct sli4_wcqe_xri_aborted *wcqe)
13378 {
13379 	bool workposted = false;
13380 	struct lpfc_cq_event *cq_event;
13381 	unsigned long iflags;
13382 
13383 	switch (cq->subtype) {
13384 	case LPFC_IO:
13385 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
13386 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13387 			/* Notify aborted XRI for NVME work queue */
13388 			if (phba->nvmet_support)
13389 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
13390 		}
13391 		workposted = false;
13392 		break;
13393 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
13394 	case LPFC_ELS:
13395 		cq_event = lpfc_cq_event_setup(
13396 			phba, wcqe, sizeof(struct sli4_wcqe_xri_aborted));
13397 		if (!cq_event)
13398 			return false;
13399 		cq_event->hdwq = cq->hdwq;
13400 		spin_lock_irqsave(&phba->hbalock, iflags);
13401 		list_add_tail(&cq_event->list,
13402 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
13403 		/* Set the els xri abort event flag */
13404 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
13405 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13406 		workposted = true;
13407 		break;
13408 	default:
13409 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13410 				"0603 Invalid CQ subtype %d: "
13411 				"%08x %08x %08x %08x\n",
13412 				cq->subtype, wcqe->word0, wcqe->parameter,
13413 				wcqe->word2, wcqe->word3);
13414 		workposted = false;
13415 		break;
13416 	}
13417 	return workposted;
13418 }
13419 
13420 #define FC_RCTL_MDS_DIAGS	0xF4
13421 
13422 /**
13423  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
13424  * @phba: Pointer to HBA context object.
13425  * @rcqe: Pointer to receive-queue completion queue entry.
13426  *
13427  * This routine process a receive-queue completion queue entry.
13428  *
13429  * Return: true if work posted to worker thread, otherwise false.
13430  **/
13431 static bool
13432 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
13433 {
13434 	bool workposted = false;
13435 	struct fc_frame_header *fc_hdr;
13436 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
13437 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
13438 	struct lpfc_nvmet_tgtport *tgtp;
13439 	struct hbq_dmabuf *dma_buf;
13440 	uint32_t status, rq_id;
13441 	unsigned long iflags;
13442 
13443 	/* sanity check on queue memory */
13444 	if (unlikely(!hrq) || unlikely(!drq))
13445 		return workposted;
13446 
13447 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
13448 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
13449 	else
13450 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
13451 	if (rq_id != hrq->queue_id)
13452 		goto out;
13453 
13454 	status = bf_get(lpfc_rcqe_status, rcqe);
13455 	switch (status) {
13456 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
13457 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13458 				"2537 Receive Frame Truncated!!\n");
13459 		/* fall through */
13460 	case FC_STATUS_RQ_SUCCESS:
13461 		spin_lock_irqsave(&phba->hbalock, iflags);
13462 		lpfc_sli4_rq_release(hrq, drq);
13463 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
13464 		if (!dma_buf) {
13465 			hrq->RQ_no_buf_found++;
13466 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13467 			goto out;
13468 		}
13469 		hrq->RQ_rcv_buf++;
13470 		hrq->RQ_buf_posted--;
13471 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
13472 
13473 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
13474 
13475 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
13476 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
13477 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13478 			/* Handle MDS Loopback frames */
13479 			lpfc_sli4_handle_mds_loopback(phba->pport, dma_buf);
13480 			break;
13481 		}
13482 
13483 		/* save off the frame for the work thread to process */
13484 		list_add_tail(&dma_buf->cq_event.list,
13485 			      &phba->sli4_hba.sp_queue_event);
13486 		/* Frame received */
13487 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
13488 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13489 		workposted = true;
13490 		break;
13491 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
13492 		if (phba->nvmet_support) {
13493 			tgtp = phba->targetport->private;
13494 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_NVME,
13495 					"6402 RQE Error x%x, posted %d err_cnt "
13496 					"%d: %x %x %x\n",
13497 					status, hrq->RQ_buf_posted,
13498 					hrq->RQ_no_posted_buf,
13499 					atomic_read(&tgtp->rcv_fcp_cmd_in),
13500 					atomic_read(&tgtp->rcv_fcp_cmd_out),
13501 					atomic_read(&tgtp->xmt_fcp_release));
13502 		}
13503 		/* fallthrough */
13504 
13505 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
13506 		hrq->RQ_no_posted_buf++;
13507 		/* Post more buffers if possible */
13508 		spin_lock_irqsave(&phba->hbalock, iflags);
13509 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
13510 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13511 		workposted = true;
13512 		break;
13513 	}
13514 out:
13515 	return workposted;
13516 }
13517 
13518 /**
13519  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
13520  * @phba: Pointer to HBA context object.
13521  * @cq: Pointer to the completion queue.
13522  * @cqe: Pointer to a completion queue entry.
13523  *
13524  * This routine process a slow-path work-queue or receive queue completion queue
13525  * entry.
13526  *
13527  * Return: true if work posted to worker thread, otherwise false.
13528  **/
13529 static bool
13530 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13531 			 struct lpfc_cqe *cqe)
13532 {
13533 	struct lpfc_cqe cqevt;
13534 	bool workposted = false;
13535 
13536 	/* Copy the work queue CQE and convert endian order if needed */
13537 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
13538 
13539 	/* Check and process for different type of WCQE and dispatch */
13540 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
13541 	case CQE_CODE_COMPL_WQE:
13542 		/* Process the WQ/RQ complete event */
13543 		phba->last_completion_time = jiffies;
13544 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
13545 				(struct lpfc_wcqe_complete *)&cqevt);
13546 		break;
13547 	case CQE_CODE_RELEASE_WQE:
13548 		/* Process the WQ release event */
13549 		lpfc_sli4_sp_handle_rel_wcqe(phba,
13550 				(struct lpfc_wcqe_release *)&cqevt);
13551 		break;
13552 	case CQE_CODE_XRI_ABORTED:
13553 		/* Process the WQ XRI abort event */
13554 		phba->last_completion_time = jiffies;
13555 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
13556 				(struct sli4_wcqe_xri_aborted *)&cqevt);
13557 		break;
13558 	case CQE_CODE_RECEIVE:
13559 	case CQE_CODE_RECEIVE_V1:
13560 		/* Process the RQ event */
13561 		phba->last_completion_time = jiffies;
13562 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
13563 				(struct lpfc_rcqe *)&cqevt);
13564 		break;
13565 	default:
13566 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13567 				"0388 Not a valid WCQE code: x%x\n",
13568 				bf_get(lpfc_cqe_code, &cqevt));
13569 		break;
13570 	}
13571 	return workposted;
13572 }
13573 
13574 /**
13575  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
13576  * @phba: Pointer to HBA context object.
13577  * @eqe: Pointer to fast-path event queue entry.
13578  *
13579  * This routine process a event queue entry from the slow-path event queue.
13580  * It will check the MajorCode and MinorCode to determine this is for a
13581  * completion event on a completion queue, if not, an error shall be logged
13582  * and just return. Otherwise, it will get to the corresponding completion
13583  * queue and process all the entries on that completion queue, rearm the
13584  * completion queue, and then return.
13585  *
13586  **/
13587 static void
13588 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
13589 	struct lpfc_queue *speq)
13590 {
13591 	struct lpfc_queue *cq = NULL, *childq;
13592 	uint16_t cqid;
13593 
13594 	/* Get the reference to the corresponding CQ */
13595 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
13596 
13597 	list_for_each_entry(childq, &speq->child_list, list) {
13598 		if (childq->queue_id == cqid) {
13599 			cq = childq;
13600 			break;
13601 		}
13602 	}
13603 	if (unlikely(!cq)) {
13604 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
13605 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13606 					"0365 Slow-path CQ identifier "
13607 					"(%d) does not exist\n", cqid);
13608 		return;
13609 	}
13610 
13611 	/* Save EQ associated with this CQ */
13612 	cq->assoc_qp = speq;
13613 
13614 	if (!queue_work_on(cq->chann, phba->wq, &cq->spwork))
13615 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13616 				"0390 Cannot schedule soft IRQ "
13617 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
13618 				cqid, cq->queue_id, raw_smp_processor_id());
13619 }
13620 
13621 /**
13622  * __lpfc_sli4_process_cq - Process elements of a CQ
13623  * @phba: Pointer to HBA context object.
13624  * @cq: Pointer to CQ to be processed
13625  * @handler: Routine to process each cqe
13626  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
13627  *
13628  * This routine processes completion queue entries in a CQ. While a valid
13629  * queue element is found, the handler is called. During processing checks
13630  * are made for periodic doorbell writes to let the hardware know of
13631  * element consumption.
13632  *
13633  * If the max limit on cqes to process is hit, or there are no more valid
13634  * entries, the loop stops. If we processed a sufficient number of elements,
13635  * meaning there is sufficient load, rather than rearming and generating
13636  * another interrupt, a cq rescheduling delay will be set. A delay of 0
13637  * indicates no rescheduling.
13638  *
13639  * Returns True if work scheduled, False otherwise.
13640  **/
13641 static bool
13642 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
13643 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
13644 			struct lpfc_cqe *), unsigned long *delay)
13645 {
13646 	struct lpfc_cqe *cqe;
13647 	bool workposted = false;
13648 	int count = 0, consumed = 0;
13649 	bool arm = true;
13650 
13651 	/* default - no reschedule */
13652 	*delay = 0;
13653 
13654 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
13655 		goto rearm_and_exit;
13656 
13657 	/* Process all the entries to the CQ */
13658 	cq->q_flag = 0;
13659 	cqe = lpfc_sli4_cq_get(cq);
13660 	while (cqe) {
13661 		workposted |= handler(phba, cq, cqe);
13662 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
13663 
13664 		consumed++;
13665 		if (!(++count % cq->max_proc_limit))
13666 			break;
13667 
13668 		if (!(count % cq->notify_interval)) {
13669 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
13670 						LPFC_QUEUE_NOARM);
13671 			consumed = 0;
13672 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
13673 		}
13674 
13675 		if (count == LPFC_NVMET_CQ_NOTIFY)
13676 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
13677 
13678 		cqe = lpfc_sli4_cq_get(cq);
13679 	}
13680 	if (count >= phba->cfg_cq_poll_threshold) {
13681 		*delay = 1;
13682 		arm = false;
13683 	}
13684 
13685 	/* Track the max number of CQEs processed in 1 EQ */
13686 	if (count > cq->CQ_max_cqe)
13687 		cq->CQ_max_cqe = count;
13688 
13689 	cq->assoc_qp->EQ_cqe_cnt += count;
13690 
13691 	/* Catch the no cq entry condition */
13692 	if (unlikely(count == 0))
13693 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13694 				"0369 No entry from completion queue "
13695 				"qid=%d\n", cq->queue_id);
13696 
13697 	cq->queue_claimed = 0;
13698 
13699 rearm_and_exit:
13700 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
13701 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
13702 
13703 	return workposted;
13704 }
13705 
13706 /**
13707  * lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
13708  * @cq: pointer to CQ to process
13709  *
13710  * This routine calls the cq processing routine with a handler specific
13711  * to the type of queue bound to it.
13712  *
13713  * The CQ routine returns two values: the first is the calling status,
13714  * which indicates whether work was queued to the  background discovery
13715  * thread. If true, the routine should wakeup the discovery thread;
13716  * the second is the delay parameter. If non-zero, rather than rearming
13717  * the CQ and yet another interrupt, the CQ handler should be queued so
13718  * that it is processed in a subsequent polling action. The value of
13719  * the delay indicates when to reschedule it.
13720  **/
13721 static void
13722 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
13723 {
13724 	struct lpfc_hba *phba = cq->phba;
13725 	unsigned long delay;
13726 	bool workposted = false;
13727 
13728 	/* Process and rearm the CQ */
13729 	switch (cq->type) {
13730 	case LPFC_MCQ:
13731 		workposted |= __lpfc_sli4_process_cq(phba, cq,
13732 						lpfc_sli4_sp_handle_mcqe,
13733 						&delay);
13734 		break;
13735 	case LPFC_WCQ:
13736 		if (cq->subtype == LPFC_IO)
13737 			workposted |= __lpfc_sli4_process_cq(phba, cq,
13738 						lpfc_sli4_fp_handle_cqe,
13739 						&delay);
13740 		else
13741 			workposted |= __lpfc_sli4_process_cq(phba, cq,
13742 						lpfc_sli4_sp_handle_cqe,
13743 						&delay);
13744 		break;
13745 	default:
13746 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13747 				"0370 Invalid completion queue type (%d)\n",
13748 				cq->type);
13749 		return;
13750 	}
13751 
13752 	if (delay) {
13753 		if (!queue_delayed_work_on(cq->chann, phba->wq,
13754 					   &cq->sched_spwork, delay))
13755 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13756 				"0394 Cannot schedule soft IRQ "
13757 				"for cqid=%d on CPU %d\n",
13758 				cq->queue_id, cq->chann);
13759 	}
13760 
13761 	/* wake up worker thread if there are works to be done */
13762 	if (workposted)
13763 		lpfc_worker_wake_up(phba);
13764 }
13765 
13766 /**
13767  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
13768  *   interrupt
13769  * @work: pointer to work element
13770  *
13771  * translates from the work handler and calls the slow-path handler.
13772  **/
13773 static void
13774 lpfc_sli4_sp_process_cq(struct work_struct *work)
13775 {
13776 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
13777 
13778 	__lpfc_sli4_sp_process_cq(cq);
13779 }
13780 
13781 /**
13782  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
13783  * @work: pointer to work element
13784  *
13785  * translates from the work handler and calls the slow-path handler.
13786  **/
13787 static void
13788 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
13789 {
13790 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
13791 					struct lpfc_queue, sched_spwork);
13792 
13793 	__lpfc_sli4_sp_process_cq(cq);
13794 }
13795 
13796 /**
13797  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
13798  * @phba: Pointer to HBA context object.
13799  * @cq: Pointer to associated CQ
13800  * @wcqe: Pointer to work-queue completion queue entry.
13801  *
13802  * This routine process a fast-path work queue completion entry from fast-path
13803  * event queue for FCP command response completion.
13804  **/
13805 static void
13806 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13807 			     struct lpfc_wcqe_complete *wcqe)
13808 {
13809 	struct lpfc_sli_ring *pring = cq->pring;
13810 	struct lpfc_iocbq *cmdiocbq;
13811 	struct lpfc_iocbq irspiocbq;
13812 	unsigned long iflags;
13813 
13814 	/* Check for response status */
13815 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
13816 		/* If resource errors reported from HBA, reduce queue
13817 		 * depth of the SCSI device.
13818 		 */
13819 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
13820 		     IOSTAT_LOCAL_REJECT)) &&
13821 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
13822 		     IOERR_NO_RESOURCES))
13823 			phba->lpfc_rampdown_queue_depth(phba);
13824 
13825 		/* Log the error status */
13826 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13827 				"0373 FCP CQE error: status=x%x: "
13828 				"CQE: %08x %08x %08x %08x\n",
13829 				bf_get(lpfc_wcqe_c_status, wcqe),
13830 				wcqe->word0, wcqe->total_data_placed,
13831 				wcqe->parameter, wcqe->word3);
13832 	}
13833 
13834 	/* Look up the FCP command IOCB and create pseudo response IOCB */
13835 	spin_lock_irqsave(&pring->ring_lock, iflags);
13836 	pring->stats.iocb_event++;
13837 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
13838 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
13839 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13840 	if (unlikely(!cmdiocbq)) {
13841 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13842 				"0374 FCP complete with no corresponding "
13843 				"cmdiocb: iotag (%d)\n",
13844 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13845 		return;
13846 	}
13847 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
13848 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
13849 #endif
13850 	if (cmdiocbq->iocb_cmpl == NULL) {
13851 		if (cmdiocbq->wqe_cmpl) {
13852 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
13853 				spin_lock_irqsave(&phba->hbalock, iflags);
13854 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
13855 				spin_unlock_irqrestore(&phba->hbalock, iflags);
13856 			}
13857 
13858 			/* Pass the cmd_iocb and the wcqe to the upper layer */
13859 			(cmdiocbq->wqe_cmpl)(phba, cmdiocbq, wcqe);
13860 			return;
13861 		}
13862 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13863 				"0375 FCP cmdiocb not callback function "
13864 				"iotag: (%d)\n",
13865 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13866 		return;
13867 	}
13868 
13869 	/* Fake the irspiocb and copy necessary response information */
13870 	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
13871 
13872 	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
13873 		spin_lock_irqsave(&phba->hbalock, iflags);
13874 		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
13875 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13876 	}
13877 
13878 	/* Pass the cmd_iocb and the rsp state to the upper layer */
13879 	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
13880 }
13881 
13882 /**
13883  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
13884  * @phba: Pointer to HBA context object.
13885  * @cq: Pointer to completion queue.
13886  * @wcqe: Pointer to work-queue completion queue entry.
13887  *
13888  * This routine handles an fast-path WQ entry consumed event by invoking the
13889  * proper WQ release routine to the slow-path WQ.
13890  **/
13891 static void
13892 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13893 			     struct lpfc_wcqe_release *wcqe)
13894 {
13895 	struct lpfc_queue *childwq;
13896 	bool wqid_matched = false;
13897 	uint16_t hba_wqid;
13898 
13899 	/* Check for fast-path FCP work queue release */
13900 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
13901 	list_for_each_entry(childwq, &cq->child_list, list) {
13902 		if (childwq->queue_id == hba_wqid) {
13903 			lpfc_sli4_wq_release(childwq,
13904 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
13905 			if (childwq->q_flag & HBA_NVMET_WQFULL)
13906 				lpfc_nvmet_wqfull_process(phba, childwq);
13907 			wqid_matched = true;
13908 			break;
13909 		}
13910 	}
13911 	/* Report warning log message if no match found */
13912 	if (wqid_matched != true)
13913 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13914 				"2580 Fast-path wqe consume event carries "
13915 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
13916 }
13917 
13918 /**
13919  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
13920  * @phba: Pointer to HBA context object.
13921  * @rcqe: Pointer to receive-queue completion queue entry.
13922  *
13923  * This routine process a receive-queue completion queue entry.
13924  *
13925  * Return: true if work posted to worker thread, otherwise false.
13926  **/
13927 static bool
13928 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13929 			    struct lpfc_rcqe *rcqe)
13930 {
13931 	bool workposted = false;
13932 	struct lpfc_queue *hrq;
13933 	struct lpfc_queue *drq;
13934 	struct rqb_dmabuf *dma_buf;
13935 	struct fc_frame_header *fc_hdr;
13936 	struct lpfc_nvmet_tgtport *tgtp;
13937 	uint32_t status, rq_id;
13938 	unsigned long iflags;
13939 	uint32_t fctl, idx;
13940 
13941 	if ((phba->nvmet_support == 0) ||
13942 	    (phba->sli4_hba.nvmet_cqset == NULL))
13943 		return workposted;
13944 
13945 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
13946 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
13947 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
13948 
13949 	/* sanity check on queue memory */
13950 	if (unlikely(!hrq) || unlikely(!drq))
13951 		return workposted;
13952 
13953 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
13954 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
13955 	else
13956 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
13957 
13958 	if ((phba->nvmet_support == 0) ||
13959 	    (rq_id != hrq->queue_id))
13960 		return workposted;
13961 
13962 	status = bf_get(lpfc_rcqe_status, rcqe);
13963 	switch (status) {
13964 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
13965 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13966 				"6126 Receive Frame Truncated!!\n");
13967 		/* fall through */
13968 	case FC_STATUS_RQ_SUCCESS:
13969 		spin_lock_irqsave(&phba->hbalock, iflags);
13970 		lpfc_sli4_rq_release(hrq, drq);
13971 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
13972 		if (!dma_buf) {
13973 			hrq->RQ_no_buf_found++;
13974 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13975 			goto out;
13976 		}
13977 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13978 		hrq->RQ_rcv_buf++;
13979 		hrq->RQ_buf_posted--;
13980 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
13981 
13982 		/* Just some basic sanity checks on FCP Command frame */
13983 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
13984 		fc_hdr->fh_f_ctl[1] << 8 |
13985 		fc_hdr->fh_f_ctl[2]);
13986 		if (((fctl &
13987 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
13988 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
13989 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
13990 			goto drop;
13991 
13992 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
13993 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
13994 			lpfc_nvmet_unsol_fcp_event(
13995 				phba, idx, dma_buf, cq->isr_timestamp,
13996 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
13997 			return false;
13998 		}
13999 drop:
14000 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
14001 		break;
14002 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14003 		if (phba->nvmet_support) {
14004 			tgtp = phba->targetport->private;
14005 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_NVME,
14006 					"6401 RQE Error x%x, posted %d err_cnt "
14007 					"%d: %x %x %x\n",
14008 					status, hrq->RQ_buf_posted,
14009 					hrq->RQ_no_posted_buf,
14010 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14011 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14012 					atomic_read(&tgtp->xmt_fcp_release));
14013 		}
14014 		/* fallthrough */
14015 
14016 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14017 		hrq->RQ_no_posted_buf++;
14018 		/* Post more buffers if possible */
14019 		break;
14020 	}
14021 out:
14022 	return workposted;
14023 }
14024 
14025 /**
14026  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
14027  * @phba: adapter with cq
14028  * @cq: Pointer to the completion queue.
14029  * @eqe: Pointer to fast-path completion queue entry.
14030  *
14031  * This routine process a fast-path work queue completion entry from fast-path
14032  * event queue for FCP command response completion.
14033  *
14034  * Return: true if work posted to worker thread, otherwise false.
14035  **/
14036 static bool
14037 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14038 			 struct lpfc_cqe *cqe)
14039 {
14040 	struct lpfc_wcqe_release wcqe;
14041 	bool workposted = false;
14042 
14043 	/* Copy the work queue CQE and convert endian order if needed */
14044 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
14045 
14046 	/* Check and process for different type of WCQE and dispatch */
14047 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
14048 	case CQE_CODE_COMPL_WQE:
14049 	case CQE_CODE_NVME_ERSP:
14050 		cq->CQ_wq++;
14051 		/* Process the WQ complete event */
14052 		phba->last_completion_time = jiffies;
14053 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
14054 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
14055 				(struct lpfc_wcqe_complete *)&wcqe);
14056 		break;
14057 	case CQE_CODE_RELEASE_WQE:
14058 		cq->CQ_release_wqe++;
14059 		/* Process the WQ release event */
14060 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
14061 				(struct lpfc_wcqe_release *)&wcqe);
14062 		break;
14063 	case CQE_CODE_XRI_ABORTED:
14064 		cq->CQ_xri_aborted++;
14065 		/* Process the WQ XRI abort event */
14066 		phba->last_completion_time = jiffies;
14067 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14068 				(struct sli4_wcqe_xri_aborted *)&wcqe);
14069 		break;
14070 	case CQE_CODE_RECEIVE_V1:
14071 	case CQE_CODE_RECEIVE:
14072 		phba->last_completion_time = jiffies;
14073 		if (cq->subtype == LPFC_NVMET) {
14074 			workposted = lpfc_sli4_nvmet_handle_rcqe(
14075 				phba, cq, (struct lpfc_rcqe *)&wcqe);
14076 		}
14077 		break;
14078 	default:
14079 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14080 				"0144 Not a valid CQE code: x%x\n",
14081 				bf_get(lpfc_wcqe_c_code, &wcqe));
14082 		break;
14083 	}
14084 	return workposted;
14085 }
14086 
14087 /**
14088  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
14089  * @phba: Pointer to HBA context object.
14090  * @eqe: Pointer to fast-path event queue entry.
14091  *
14092  * This routine process a event queue entry from the fast-path event queue.
14093  * It will check the MajorCode and MinorCode to determine this is for a
14094  * completion event on a completion queue, if not, an error shall be logged
14095  * and just return. Otherwise, it will get to the corresponding completion
14096  * queue and process all the entries on the completion queue, rearm the
14097  * completion queue, and then return.
14098  **/
14099 static void
14100 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
14101 			 struct lpfc_eqe *eqe)
14102 {
14103 	struct lpfc_queue *cq = NULL;
14104 	uint32_t qidx = eq->hdwq;
14105 	uint16_t cqid, id;
14106 
14107 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
14108 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14109 				"0366 Not a valid completion "
14110 				"event: majorcode=x%x, minorcode=x%x\n",
14111 				bf_get_le32(lpfc_eqe_major_code, eqe),
14112 				bf_get_le32(lpfc_eqe_minor_code, eqe));
14113 		return;
14114 	}
14115 
14116 	/* Get the reference to the corresponding CQ */
14117 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14118 
14119 	/* Use the fast lookup method first */
14120 	if (cqid <= phba->sli4_hba.cq_max) {
14121 		cq = phba->sli4_hba.cq_lookup[cqid];
14122 		if (cq)
14123 			goto  work_cq;
14124 	}
14125 
14126 	/* Next check for NVMET completion */
14127 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
14128 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
14129 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
14130 			/* Process NVMET unsol rcv */
14131 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
14132 			goto  process_cq;
14133 		}
14134 	}
14135 
14136 	if (phba->sli4_hba.nvmels_cq &&
14137 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
14138 		/* Process NVME unsol rcv */
14139 		cq = phba->sli4_hba.nvmels_cq;
14140 	}
14141 
14142 	/* Otherwise this is a Slow path event */
14143 	if (cq == NULL) {
14144 		lpfc_sli4_sp_handle_eqe(phba, eqe,
14145 					phba->sli4_hba.hdwq[qidx].hba_eq);
14146 		return;
14147 	}
14148 
14149 process_cq:
14150 	if (unlikely(cqid != cq->queue_id)) {
14151 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14152 				"0368 Miss-matched fast-path completion "
14153 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
14154 				cqid, cq->queue_id);
14155 		return;
14156 	}
14157 
14158 work_cq:
14159 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
14160 	if (phba->ktime_on)
14161 		cq->isr_timestamp = ktime_get_ns();
14162 	else
14163 		cq->isr_timestamp = 0;
14164 #endif
14165 	if (!queue_work_on(cq->chann, phba->wq, &cq->irqwork))
14166 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14167 				"0363 Cannot schedule soft IRQ "
14168 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14169 				cqid, cq->queue_id, raw_smp_processor_id());
14170 }
14171 
14172 /**
14173  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
14174  * @cq: Pointer to CQ to be processed
14175  *
14176  * This routine calls the cq processing routine with the handler for
14177  * fast path CQEs.
14178  *
14179  * The CQ routine returns two values: the first is the calling status,
14180  * which indicates whether work was queued to the  background discovery
14181  * thread. If true, the routine should wakeup the discovery thread;
14182  * the second is the delay parameter. If non-zero, rather than rearming
14183  * the CQ and yet another interrupt, the CQ handler should be queued so
14184  * that it is processed in a subsequent polling action. The value of
14185  * the delay indicates when to reschedule it.
14186  **/
14187 static void
14188 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq)
14189 {
14190 	struct lpfc_hba *phba = cq->phba;
14191 	unsigned long delay;
14192 	bool workposted = false;
14193 
14194 	/* process and rearm the CQ */
14195 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
14196 					     &delay);
14197 
14198 	if (delay) {
14199 		if (!queue_delayed_work_on(cq->chann, phba->wq,
14200 					   &cq->sched_irqwork, delay))
14201 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14202 				"0367 Cannot schedule soft IRQ "
14203 				"for cqid=%d on CPU %d\n",
14204 				cq->queue_id, cq->chann);
14205 	}
14206 
14207 	/* wake up worker thread if there are works to be done */
14208 	if (workposted)
14209 		lpfc_worker_wake_up(phba);
14210 }
14211 
14212 /**
14213  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
14214  *   interrupt
14215  * @work: pointer to work element
14216  *
14217  * translates from the work handler and calls the fast-path handler.
14218  **/
14219 static void
14220 lpfc_sli4_hba_process_cq(struct work_struct *work)
14221 {
14222 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
14223 
14224 	__lpfc_sli4_hba_process_cq(cq);
14225 }
14226 
14227 /**
14228  * lpfc_sli4_hba_process_cq - fast-path work handler when started by timer
14229  * @work: pointer to work element
14230  *
14231  * translates from the work handler and calls the fast-path handler.
14232  **/
14233 static void
14234 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
14235 {
14236 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
14237 					struct lpfc_queue, sched_irqwork);
14238 
14239 	__lpfc_sli4_hba_process_cq(cq);
14240 }
14241 
14242 /**
14243  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
14244  * @irq: Interrupt number.
14245  * @dev_id: The device context pointer.
14246  *
14247  * This function is directly called from the PCI layer as an interrupt
14248  * service routine when device with SLI-4 interface spec is enabled with
14249  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
14250  * ring event in the HBA. However, when the device is enabled with either
14251  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
14252  * device-level interrupt handler. When the PCI slot is in error recovery
14253  * or the HBA is undergoing initialization, the interrupt handler will not
14254  * process the interrupt. The SCSI FCP fast-path ring event are handled in
14255  * the intrrupt context. This function is called without any lock held.
14256  * It gets the hbalock to access and update SLI data structures. Note that,
14257  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
14258  * equal to that of FCP CQ index.
14259  *
14260  * The link attention and ELS ring attention events are handled
14261  * by the worker thread. The interrupt handler signals the worker thread
14262  * and returns for these events. This function is called without any lock
14263  * held. It gets the hbalock to access and update SLI data structures.
14264  *
14265  * This function returns IRQ_HANDLED when interrupt is handled else it
14266  * returns IRQ_NONE.
14267  **/
14268 irqreturn_t
14269 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
14270 {
14271 	struct lpfc_hba *phba;
14272 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
14273 	struct lpfc_queue *fpeq;
14274 	unsigned long iflag;
14275 	int ecount = 0;
14276 	int hba_eqidx;
14277 	struct lpfc_eq_intr_info *eqi;
14278 	uint32_t icnt;
14279 
14280 	/* Get the driver's phba structure from the dev_id */
14281 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
14282 	phba = hba_eq_hdl->phba;
14283 	hba_eqidx = hba_eq_hdl->idx;
14284 
14285 	if (unlikely(!phba))
14286 		return IRQ_NONE;
14287 	if (unlikely(!phba->sli4_hba.hdwq))
14288 		return IRQ_NONE;
14289 
14290 	/* Get to the EQ struct associated with this vector */
14291 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
14292 	if (unlikely(!fpeq))
14293 		return IRQ_NONE;
14294 
14295 	/* Check device state for handling interrupt */
14296 	if (unlikely(lpfc_intr_state_check(phba))) {
14297 		/* Check again for link_state with lock held */
14298 		spin_lock_irqsave(&phba->hbalock, iflag);
14299 		if (phba->link_state < LPFC_LINK_DOWN)
14300 			/* Flush, clear interrupt, and rearm the EQ */
14301 			lpfc_sli4_eqcq_flush(phba, fpeq);
14302 		spin_unlock_irqrestore(&phba->hbalock, iflag);
14303 		return IRQ_NONE;
14304 	}
14305 
14306 	eqi = phba->sli4_hba.eq_info;
14307 	icnt = this_cpu_inc_return(eqi->icnt);
14308 	fpeq->last_cpu = raw_smp_processor_id();
14309 
14310 	if (icnt > LPFC_EQD_ISR_TRIGGER &&
14311 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
14312 	    phba->cfg_auto_imax &&
14313 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
14314 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
14315 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
14316 
14317 	/* process and rearm the EQ */
14318 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
14319 
14320 	if (unlikely(ecount == 0)) {
14321 		fpeq->EQ_no_entry++;
14322 		if (phba->intr_type == MSIX)
14323 			/* MSI-X treated interrupt served as no EQ share INT */
14324 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14325 					"0358 MSI-X interrupt with no EQE\n");
14326 		else
14327 			/* Non MSI-X treated on interrupt as EQ share INT */
14328 			return IRQ_NONE;
14329 	}
14330 
14331 	return IRQ_HANDLED;
14332 } /* lpfc_sli4_fp_intr_handler */
14333 
14334 /**
14335  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
14336  * @irq: Interrupt number.
14337  * @dev_id: The device context pointer.
14338  *
14339  * This function is the device-level interrupt handler to device with SLI-4
14340  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
14341  * interrupt mode is enabled and there is an event in the HBA which requires
14342  * driver attention. This function invokes the slow-path interrupt attention
14343  * handling function and fast-path interrupt attention handling function in
14344  * turn to process the relevant HBA attention events. This function is called
14345  * without any lock held. It gets the hbalock to access and update SLI data
14346  * structures.
14347  *
14348  * This function returns IRQ_HANDLED when interrupt is handled, else it
14349  * returns IRQ_NONE.
14350  **/
14351 irqreturn_t
14352 lpfc_sli4_intr_handler(int irq, void *dev_id)
14353 {
14354 	struct lpfc_hba  *phba;
14355 	irqreturn_t hba_irq_rc;
14356 	bool hba_handled = false;
14357 	int qidx;
14358 
14359 	/* Get the driver's phba structure from the dev_id */
14360 	phba = (struct lpfc_hba *)dev_id;
14361 
14362 	if (unlikely(!phba))
14363 		return IRQ_NONE;
14364 
14365 	/*
14366 	 * Invoke fast-path host attention interrupt handling as appropriate.
14367 	 */
14368 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
14369 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
14370 					&phba->sli4_hba.hba_eq_hdl[qidx]);
14371 		if (hba_irq_rc == IRQ_HANDLED)
14372 			hba_handled |= true;
14373 	}
14374 
14375 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
14376 } /* lpfc_sli4_intr_handler */
14377 
14378 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
14379 {
14380 	struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
14381 	struct lpfc_queue *eq;
14382 	int i = 0;
14383 
14384 	rcu_read_lock();
14385 
14386 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
14387 		i += lpfc_sli4_poll_eq(eq, LPFC_POLL_SLOWPATH);
14388 	if (!list_empty(&phba->poll_list))
14389 		mod_timer(&phba->cpuhp_poll_timer,
14390 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
14391 
14392 	rcu_read_unlock();
14393 }
14394 
14395 inline int lpfc_sli4_poll_eq(struct lpfc_queue *eq, uint8_t path)
14396 {
14397 	struct lpfc_hba *phba = eq->phba;
14398 	int i = 0;
14399 
14400 	/*
14401 	 * Unlocking an irq is one of the entry point to check
14402 	 * for re-schedule, but we are good for io submission
14403 	 * path as midlayer does a get_cpu to glue us in. Flush
14404 	 * out the invalidate queue so we can see the updated
14405 	 * value for flag.
14406 	 */
14407 	smp_rmb();
14408 
14409 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
14410 		/* We will not likely get the completion for the caller
14411 		 * during this iteration but i guess that's fine.
14412 		 * Future io's coming on this eq should be able to
14413 		 * pick it up.  As for the case of single io's, they
14414 		 * will be handled through a sched from polling timer
14415 		 * function which is currently triggered every 1msec.
14416 		 */
14417 		i = lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM);
14418 
14419 	return i;
14420 }
14421 
14422 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
14423 {
14424 	struct lpfc_hba *phba = eq->phba;
14425 
14426 	/* kickstart slowpath processing if needed */
14427 	if (list_empty(&phba->poll_list))
14428 		mod_timer(&phba->cpuhp_poll_timer,
14429 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
14430 
14431 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
14432 	synchronize_rcu();
14433 }
14434 
14435 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
14436 {
14437 	struct lpfc_hba *phba = eq->phba;
14438 
14439 	/* Disable slowpath processing for this eq.  Kick start the eq
14440 	 * by RE-ARMING the eq's ASAP
14441 	 */
14442 	list_del_rcu(&eq->_poll_list);
14443 	synchronize_rcu();
14444 
14445 	if (list_empty(&phba->poll_list))
14446 		del_timer_sync(&phba->cpuhp_poll_timer);
14447 }
14448 
14449 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
14450 {
14451 	struct lpfc_queue *eq, *next;
14452 
14453 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
14454 		list_del(&eq->_poll_list);
14455 
14456 	INIT_LIST_HEAD(&phba->poll_list);
14457 	synchronize_rcu();
14458 }
14459 
14460 static inline void
14461 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
14462 {
14463 	if (mode == eq->mode)
14464 		return;
14465 	/*
14466 	 * currently this function is only called during a hotplug
14467 	 * event and the cpu on which this function is executing
14468 	 * is going offline.  By now the hotplug has instructed
14469 	 * the scheduler to remove this cpu from cpu active mask.
14470 	 * So we don't need to work about being put aside by the
14471 	 * scheduler for a high priority process.  Yes, the inte-
14472 	 * rrupts could come but they are known to retire ASAP.
14473 	 */
14474 
14475 	/* Disable polling in the fastpath */
14476 	WRITE_ONCE(eq->mode, mode);
14477 	/* flush out the store buffer */
14478 	smp_wmb();
14479 
14480 	/*
14481 	 * Add this eq to the polling list and start polling. For
14482 	 * a grace period both interrupt handler and poller will
14483 	 * try to process the eq _but_ that's fine.  We have a
14484 	 * synchronization mechanism in place (queue_claimed) to
14485 	 * deal with it.  This is just a draining phase for int-
14486 	 * errupt handler (not eq's) as we have guranteed through
14487 	 * barrier that all the CPUs have seen the new CQ_POLLED
14488 	 * state. which will effectively disable the REARMING of
14489 	 * the EQ.  The whole idea is eq's die off eventually as
14490 	 * we are not rearming EQ's anymore.
14491 	 */
14492 	mode ? lpfc_sli4_add_to_poll_list(eq) :
14493 	       lpfc_sli4_remove_from_poll_list(eq);
14494 }
14495 
14496 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
14497 {
14498 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
14499 }
14500 
14501 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
14502 {
14503 	struct lpfc_hba *phba = eq->phba;
14504 
14505 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
14506 
14507 	/* Kick start for the pending io's in h/w.
14508 	 * Once we switch back to interrupt processing on a eq
14509 	 * the io path completion will only arm eq's when it
14510 	 * receives a completion.  But since eq's are in disa-
14511 	 * rmed state it doesn't receive a completion.  This
14512 	 * creates a deadlock scenaro.
14513 	 */
14514 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
14515 }
14516 
14517 /**
14518  * lpfc_sli4_queue_free - free a queue structure and associated memory
14519  * @queue: The queue structure to free.
14520  *
14521  * This function frees a queue structure and the DMAable memory used for
14522  * the host resident queue. This function must be called after destroying the
14523  * queue on the HBA.
14524  **/
14525 void
14526 lpfc_sli4_queue_free(struct lpfc_queue *queue)
14527 {
14528 	struct lpfc_dmabuf *dmabuf;
14529 
14530 	if (!queue)
14531 		return;
14532 
14533 	if (!list_empty(&queue->wq_list))
14534 		list_del(&queue->wq_list);
14535 
14536 	while (!list_empty(&queue->page_list)) {
14537 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
14538 				 list);
14539 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
14540 				  dmabuf->virt, dmabuf->phys);
14541 		kfree(dmabuf);
14542 	}
14543 	if (queue->rqbp) {
14544 		lpfc_free_rq_buffer(queue->phba, queue);
14545 		kfree(queue->rqbp);
14546 	}
14547 
14548 	if (!list_empty(&queue->cpu_list))
14549 		list_del(&queue->cpu_list);
14550 
14551 	kfree(queue);
14552 	return;
14553 }
14554 
14555 /**
14556  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
14557  * @phba: The HBA that this queue is being created on.
14558  * @page_size: The size of a queue page
14559  * @entry_size: The size of each queue entry for this queue.
14560  * @entry count: The number of entries that this queue will handle.
14561  * @cpu: The cpu that will primarily utilize this queue.
14562  *
14563  * This function allocates a queue structure and the DMAable memory used for
14564  * the host resident queue. This function must be called before creating the
14565  * queue on the HBA.
14566  **/
14567 struct lpfc_queue *
14568 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
14569 		      uint32_t entry_size, uint32_t entry_count, int cpu)
14570 {
14571 	struct lpfc_queue *queue;
14572 	struct lpfc_dmabuf *dmabuf;
14573 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14574 	uint16_t x, pgcnt;
14575 
14576 	if (!phba->sli4_hba.pc_sli4_params.supported)
14577 		hw_page_size = page_size;
14578 
14579 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
14580 
14581 	/* If needed, Adjust page count to match the max the adapter supports */
14582 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
14583 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
14584 
14585 	queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
14586 			     GFP_KERNEL, cpu_to_node(cpu));
14587 	if (!queue)
14588 		return NULL;
14589 
14590 	INIT_LIST_HEAD(&queue->list);
14591 	INIT_LIST_HEAD(&queue->_poll_list);
14592 	INIT_LIST_HEAD(&queue->wq_list);
14593 	INIT_LIST_HEAD(&queue->wqfull_list);
14594 	INIT_LIST_HEAD(&queue->page_list);
14595 	INIT_LIST_HEAD(&queue->child_list);
14596 	INIT_LIST_HEAD(&queue->cpu_list);
14597 
14598 	/* Set queue parameters now.  If the system cannot provide memory
14599 	 * resources, the free routine needs to know what was allocated.
14600 	 */
14601 	queue->page_count = pgcnt;
14602 	queue->q_pgs = (void **)&queue[1];
14603 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
14604 	queue->entry_size = entry_size;
14605 	queue->entry_count = entry_count;
14606 	queue->page_size = hw_page_size;
14607 	queue->phba = phba;
14608 
14609 	for (x = 0; x < queue->page_count; x++) {
14610 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
14611 				      dev_to_node(&phba->pcidev->dev));
14612 		if (!dmabuf)
14613 			goto out_fail;
14614 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14615 						  hw_page_size, &dmabuf->phys,
14616 						  GFP_KERNEL);
14617 		if (!dmabuf->virt) {
14618 			kfree(dmabuf);
14619 			goto out_fail;
14620 		}
14621 		dmabuf->buffer_tag = x;
14622 		list_add_tail(&dmabuf->list, &queue->page_list);
14623 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
14624 		queue->q_pgs[x] = dmabuf->virt;
14625 	}
14626 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
14627 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
14628 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
14629 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
14630 
14631 	/* notify_interval will be set during q creation */
14632 
14633 	return queue;
14634 out_fail:
14635 	lpfc_sli4_queue_free(queue);
14636 	return NULL;
14637 }
14638 
14639 /**
14640  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
14641  * @phba: HBA structure that indicates port to create a queue on.
14642  * @pci_barset: PCI BAR set flag.
14643  *
14644  * This function shall perform iomap of the specified PCI BAR address to host
14645  * memory address if not already done so and return it. The returned host
14646  * memory address can be NULL.
14647  */
14648 static void __iomem *
14649 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
14650 {
14651 	if (!phba->pcidev)
14652 		return NULL;
14653 
14654 	switch (pci_barset) {
14655 	case WQ_PCI_BAR_0_AND_1:
14656 		return phba->pci_bar0_memmap_p;
14657 	case WQ_PCI_BAR_2_AND_3:
14658 		return phba->pci_bar2_memmap_p;
14659 	case WQ_PCI_BAR_4_AND_5:
14660 		return phba->pci_bar4_memmap_p;
14661 	default:
14662 		break;
14663 	}
14664 	return NULL;
14665 }
14666 
14667 /**
14668  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
14669  * @phba: HBA structure that EQs are on.
14670  * @startq: The starting EQ index to modify
14671  * @numq: The number of EQs (consecutive indexes) to modify
14672  * @usdelay: amount of delay
14673  *
14674  * This function revises the EQ delay on 1 or more EQs. The EQ delay
14675  * is set either by writing to a register (if supported by the SLI Port)
14676  * or by mailbox command. The mailbox command allows several EQs to be
14677  * updated at once.
14678  *
14679  * The @phba struct is used to send a mailbox command to HBA. The @startq
14680  * is used to get the starting EQ index to change. The @numq value is
14681  * used to specify how many consecutive EQ indexes, starting at EQ index,
14682  * are to be changed. This function is asynchronous and will wait for any
14683  * mailbox commands to finish before returning.
14684  *
14685  * On success this function will return a zero. If unable to allocate
14686  * enough memory this function will return -ENOMEM. If a mailbox command
14687  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
14688  * have had their delay multipler changed.
14689  **/
14690 void
14691 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
14692 			 uint32_t numq, uint32_t usdelay)
14693 {
14694 	struct lpfc_mbx_modify_eq_delay *eq_delay;
14695 	LPFC_MBOXQ_t *mbox;
14696 	struct lpfc_queue *eq;
14697 	int cnt = 0, rc, length;
14698 	uint32_t shdr_status, shdr_add_status;
14699 	uint32_t dmult;
14700 	int qidx;
14701 	union lpfc_sli4_cfg_shdr *shdr;
14702 
14703 	if (startq >= phba->cfg_irq_chann)
14704 		return;
14705 
14706 	if (usdelay > 0xFFFF) {
14707 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
14708 				"6429 usdelay %d too large. Scaled down to "
14709 				"0xFFFF.\n", usdelay);
14710 		usdelay = 0xFFFF;
14711 	}
14712 
14713 	/* set values by EQ_DELAY register if supported */
14714 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
14715 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
14716 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
14717 			if (!eq)
14718 				continue;
14719 
14720 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
14721 
14722 			if (++cnt >= numq)
14723 				break;
14724 		}
14725 		return;
14726 	}
14727 
14728 	/* Otherwise, set values by mailbox cmd */
14729 
14730 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14731 	if (!mbox) {
14732 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_FCP | LOG_NVME,
14733 				"6428 Failed allocating mailbox cmd buffer."
14734 				" EQ delay was not set.\n");
14735 		return;
14736 	}
14737 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
14738 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14739 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14740 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
14741 			 length, LPFC_SLI4_MBX_EMBED);
14742 	eq_delay = &mbox->u.mqe.un.eq_delay;
14743 
14744 	/* Calculate delay multiper from maximum interrupt per second */
14745 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
14746 	if (dmult)
14747 		dmult--;
14748 	if (dmult > LPFC_DMULT_MAX)
14749 		dmult = LPFC_DMULT_MAX;
14750 
14751 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
14752 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
14753 		if (!eq)
14754 			continue;
14755 		eq->q_mode = usdelay;
14756 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
14757 		eq_delay->u.request.eq[cnt].phase = 0;
14758 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
14759 
14760 		if (++cnt >= numq)
14761 			break;
14762 	}
14763 	eq_delay->u.request.num_eq = cnt;
14764 
14765 	mbox->vport = phba->pport;
14766 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14767 	mbox->ctx_buf = NULL;
14768 	mbox->ctx_ndlp = NULL;
14769 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14770 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
14771 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14772 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14773 	if (shdr_status || shdr_add_status || rc) {
14774 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14775 				"2512 MODIFY_EQ_DELAY mailbox failed with "
14776 				"status x%x add_status x%x, mbx status x%x\n",
14777 				shdr_status, shdr_add_status, rc);
14778 	}
14779 	mempool_free(mbox, phba->mbox_mem_pool);
14780 	return;
14781 }
14782 
14783 /**
14784  * lpfc_eq_create - Create an Event Queue on the HBA
14785  * @phba: HBA structure that indicates port to create a queue on.
14786  * @eq: The queue structure to use to create the event queue.
14787  * @imax: The maximum interrupt per second limit.
14788  *
14789  * This function creates an event queue, as detailed in @eq, on a port,
14790  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
14791  *
14792  * The @phba struct is used to send mailbox command to HBA. The @eq struct
14793  * is used to get the entry count and entry size that are necessary to
14794  * determine the number of pages to allocate and use for this queue. This
14795  * function will send the EQ_CREATE mailbox command to the HBA to setup the
14796  * event queue. This function is asynchronous and will wait for the mailbox
14797  * command to finish before continuing.
14798  *
14799  * On success this function will return a zero. If unable to allocate enough
14800  * memory this function will return -ENOMEM. If the queue create mailbox command
14801  * fails this function will return -ENXIO.
14802  **/
14803 int
14804 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
14805 {
14806 	struct lpfc_mbx_eq_create *eq_create;
14807 	LPFC_MBOXQ_t *mbox;
14808 	int rc, length, status = 0;
14809 	struct lpfc_dmabuf *dmabuf;
14810 	uint32_t shdr_status, shdr_add_status;
14811 	union lpfc_sli4_cfg_shdr *shdr;
14812 	uint16_t dmult;
14813 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14814 
14815 	/* sanity check on queue memory */
14816 	if (!eq)
14817 		return -ENODEV;
14818 	if (!phba->sli4_hba.pc_sli4_params.supported)
14819 		hw_page_size = SLI4_PAGE_SIZE;
14820 
14821 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14822 	if (!mbox)
14823 		return -ENOMEM;
14824 	length = (sizeof(struct lpfc_mbx_eq_create) -
14825 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14826 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14827 			 LPFC_MBOX_OPCODE_EQ_CREATE,
14828 			 length, LPFC_SLI4_MBX_EMBED);
14829 	eq_create = &mbox->u.mqe.un.eq_create;
14830 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
14831 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
14832 	       eq->page_count);
14833 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
14834 	       LPFC_EQE_SIZE);
14835 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
14836 
14837 	/* Use version 2 of CREATE_EQ if eqav is set */
14838 	if (phba->sli4_hba.pc_sli4_params.eqav) {
14839 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
14840 		       LPFC_Q_CREATE_VERSION_2);
14841 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
14842 		       phba->sli4_hba.pc_sli4_params.eqav);
14843 	}
14844 
14845 	/* don't setup delay multiplier using EQ_CREATE */
14846 	dmult = 0;
14847 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
14848 	       dmult);
14849 	switch (eq->entry_count) {
14850 	default:
14851 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14852 				"0360 Unsupported EQ count. (%d)\n",
14853 				eq->entry_count);
14854 		if (eq->entry_count < 256) {
14855 			status = -EINVAL;
14856 			goto out;
14857 		}
14858 		/* fall through - otherwise default to smallest count */
14859 	case 256:
14860 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14861 		       LPFC_EQ_CNT_256);
14862 		break;
14863 	case 512:
14864 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14865 		       LPFC_EQ_CNT_512);
14866 		break;
14867 	case 1024:
14868 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14869 		       LPFC_EQ_CNT_1024);
14870 		break;
14871 	case 2048:
14872 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14873 		       LPFC_EQ_CNT_2048);
14874 		break;
14875 	case 4096:
14876 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14877 		       LPFC_EQ_CNT_4096);
14878 		break;
14879 	}
14880 	list_for_each_entry(dmabuf, &eq->page_list, list) {
14881 		memset(dmabuf->virt, 0, hw_page_size);
14882 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
14883 					putPaddrLow(dmabuf->phys);
14884 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
14885 					putPaddrHigh(dmabuf->phys);
14886 	}
14887 	mbox->vport = phba->pport;
14888 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14889 	mbox->ctx_buf = NULL;
14890 	mbox->ctx_ndlp = NULL;
14891 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14892 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14893 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14894 	if (shdr_status || shdr_add_status || rc) {
14895 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14896 				"2500 EQ_CREATE mailbox failed with "
14897 				"status x%x add_status x%x, mbx status x%x\n",
14898 				shdr_status, shdr_add_status, rc);
14899 		status = -ENXIO;
14900 	}
14901 	eq->type = LPFC_EQ;
14902 	eq->subtype = LPFC_NONE;
14903 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
14904 	if (eq->queue_id == 0xFFFF)
14905 		status = -ENXIO;
14906 	eq->host_index = 0;
14907 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
14908 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
14909 out:
14910 	mempool_free(mbox, phba->mbox_mem_pool);
14911 	return status;
14912 }
14913 
14914 /**
14915  * lpfc_cq_create - Create a Completion Queue on the HBA
14916  * @phba: HBA structure that indicates port to create a queue on.
14917  * @cq: The queue structure to use to create the completion queue.
14918  * @eq: The event queue to bind this completion queue to.
14919  *
14920  * This function creates a completion queue, as detailed in @wq, on a port,
14921  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
14922  *
14923  * The @phba struct is used to send mailbox command to HBA. The @cq struct
14924  * is used to get the entry count and entry size that are necessary to
14925  * determine the number of pages to allocate and use for this queue. The @eq
14926  * is used to indicate which event queue to bind this completion queue to. This
14927  * function will send the CQ_CREATE mailbox command to the HBA to setup the
14928  * completion queue. This function is asynchronous and will wait for the mailbox
14929  * command to finish before continuing.
14930  *
14931  * On success this function will return a zero. If unable to allocate enough
14932  * memory this function will return -ENOMEM. If the queue create mailbox command
14933  * fails this function will return -ENXIO.
14934  **/
14935 int
14936 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
14937 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
14938 {
14939 	struct lpfc_mbx_cq_create *cq_create;
14940 	struct lpfc_dmabuf *dmabuf;
14941 	LPFC_MBOXQ_t *mbox;
14942 	int rc, length, status = 0;
14943 	uint32_t shdr_status, shdr_add_status;
14944 	union lpfc_sli4_cfg_shdr *shdr;
14945 
14946 	/* sanity check on queue memory */
14947 	if (!cq || !eq)
14948 		return -ENODEV;
14949 
14950 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14951 	if (!mbox)
14952 		return -ENOMEM;
14953 	length = (sizeof(struct lpfc_mbx_cq_create) -
14954 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14955 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14956 			 LPFC_MBOX_OPCODE_CQ_CREATE,
14957 			 length, LPFC_SLI4_MBX_EMBED);
14958 	cq_create = &mbox->u.mqe.un.cq_create;
14959 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
14960 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
14961 		    cq->page_count);
14962 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
14963 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
14964 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
14965 	       phba->sli4_hba.pc_sli4_params.cqv);
14966 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
14967 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
14968 		       (cq->page_size / SLI4_PAGE_SIZE));
14969 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
14970 		       eq->queue_id);
14971 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
14972 		       phba->sli4_hba.pc_sli4_params.cqav);
14973 	} else {
14974 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
14975 		       eq->queue_id);
14976 	}
14977 	switch (cq->entry_count) {
14978 	case 2048:
14979 	case 4096:
14980 		if (phba->sli4_hba.pc_sli4_params.cqv ==
14981 		    LPFC_Q_CREATE_VERSION_2) {
14982 			cq_create->u.request.context.lpfc_cq_context_count =
14983 				cq->entry_count;
14984 			bf_set(lpfc_cq_context_count,
14985 			       &cq_create->u.request.context,
14986 			       LPFC_CQ_CNT_WORD7);
14987 			break;
14988 		}
14989 		/* fall through */
14990 	default:
14991 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14992 				"0361 Unsupported CQ count: "
14993 				"entry cnt %d sz %d pg cnt %d\n",
14994 				cq->entry_count, cq->entry_size,
14995 				cq->page_count);
14996 		if (cq->entry_count < 256) {
14997 			status = -EINVAL;
14998 			goto out;
14999 		}
15000 		/* fall through - otherwise default to smallest count */
15001 	case 256:
15002 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15003 		       LPFC_CQ_CNT_256);
15004 		break;
15005 	case 512:
15006 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15007 		       LPFC_CQ_CNT_512);
15008 		break;
15009 	case 1024:
15010 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15011 		       LPFC_CQ_CNT_1024);
15012 		break;
15013 	}
15014 	list_for_each_entry(dmabuf, &cq->page_list, list) {
15015 		memset(dmabuf->virt, 0, cq->page_size);
15016 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15017 					putPaddrLow(dmabuf->phys);
15018 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15019 					putPaddrHigh(dmabuf->phys);
15020 	}
15021 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15022 
15023 	/* The IOCTL status is embedded in the mailbox subheader. */
15024 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15025 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15026 	if (shdr_status || shdr_add_status || rc) {
15027 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15028 				"2501 CQ_CREATE mailbox failed with "
15029 				"status x%x add_status x%x, mbx status x%x\n",
15030 				shdr_status, shdr_add_status, rc);
15031 		status = -ENXIO;
15032 		goto out;
15033 	}
15034 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15035 	if (cq->queue_id == 0xFFFF) {
15036 		status = -ENXIO;
15037 		goto out;
15038 	}
15039 	/* link the cq onto the parent eq child list */
15040 	list_add_tail(&cq->list, &eq->child_list);
15041 	/* Set up completion queue's type and subtype */
15042 	cq->type = type;
15043 	cq->subtype = subtype;
15044 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15045 	cq->assoc_qid = eq->queue_id;
15046 	cq->assoc_qp = eq;
15047 	cq->host_index = 0;
15048 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15049 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
15050 
15051 	if (cq->queue_id > phba->sli4_hba.cq_max)
15052 		phba->sli4_hba.cq_max = cq->queue_id;
15053 out:
15054 	mempool_free(mbox, phba->mbox_mem_pool);
15055 	return status;
15056 }
15057 
15058 /**
15059  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
15060  * @phba: HBA structure that indicates port to create a queue on.
15061  * @cqp: The queue structure array to use to create the completion queues.
15062  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
15063  *
15064  * This function creates a set of  completion queue, s to support MRQ
15065  * as detailed in @cqp, on a port,
15066  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
15067  *
15068  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15069  * is used to get the entry count and entry size that are necessary to
15070  * determine the number of pages to allocate and use for this queue. The @eq
15071  * is used to indicate which event queue to bind this completion queue to. This
15072  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
15073  * completion queue. This function is asynchronous and will wait for the mailbox
15074  * command to finish before continuing.
15075  *
15076  * On success this function will return a zero. If unable to allocate enough
15077  * memory this function will return -ENOMEM. If the queue create mailbox command
15078  * fails this function will return -ENXIO.
15079  **/
15080 int
15081 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
15082 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
15083 		   uint32_t subtype)
15084 {
15085 	struct lpfc_queue *cq;
15086 	struct lpfc_queue *eq;
15087 	struct lpfc_mbx_cq_create_set *cq_set;
15088 	struct lpfc_dmabuf *dmabuf;
15089 	LPFC_MBOXQ_t *mbox;
15090 	int rc, length, alloclen, status = 0;
15091 	int cnt, idx, numcq, page_idx = 0;
15092 	uint32_t shdr_status, shdr_add_status;
15093 	union lpfc_sli4_cfg_shdr *shdr;
15094 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15095 
15096 	/* sanity check on queue memory */
15097 	numcq = phba->cfg_nvmet_mrq;
15098 	if (!cqp || !hdwq || !numcq)
15099 		return -ENODEV;
15100 
15101 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15102 	if (!mbox)
15103 		return -ENOMEM;
15104 
15105 	length = sizeof(struct lpfc_mbx_cq_create_set);
15106 	length += ((numcq * cqp[0]->page_count) *
15107 		   sizeof(struct dma_address));
15108 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15109 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
15110 			LPFC_SLI4_MBX_NEMBED);
15111 	if (alloclen < length) {
15112 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15113 				"3098 Allocated DMA memory size (%d) is "
15114 				"less than the requested DMA memory size "
15115 				"(%d)\n", alloclen, length);
15116 		status = -ENOMEM;
15117 		goto out;
15118 	}
15119 	cq_set = mbox->sge_array->addr[0];
15120 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
15121 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
15122 
15123 	for (idx = 0; idx < numcq; idx++) {
15124 		cq = cqp[idx];
15125 		eq = hdwq[idx].hba_eq;
15126 		if (!cq || !eq) {
15127 			status = -ENOMEM;
15128 			goto out;
15129 		}
15130 		if (!phba->sli4_hba.pc_sli4_params.supported)
15131 			hw_page_size = cq->page_size;
15132 
15133 		switch (idx) {
15134 		case 0:
15135 			bf_set(lpfc_mbx_cq_create_set_page_size,
15136 			       &cq_set->u.request,
15137 			       (hw_page_size / SLI4_PAGE_SIZE));
15138 			bf_set(lpfc_mbx_cq_create_set_num_pages,
15139 			       &cq_set->u.request, cq->page_count);
15140 			bf_set(lpfc_mbx_cq_create_set_evt,
15141 			       &cq_set->u.request, 1);
15142 			bf_set(lpfc_mbx_cq_create_set_valid,
15143 			       &cq_set->u.request, 1);
15144 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
15145 			       &cq_set->u.request, 0);
15146 			bf_set(lpfc_mbx_cq_create_set_num_cq,
15147 			       &cq_set->u.request, numcq);
15148 			bf_set(lpfc_mbx_cq_create_set_autovalid,
15149 			       &cq_set->u.request,
15150 			       phba->sli4_hba.pc_sli4_params.cqav);
15151 			switch (cq->entry_count) {
15152 			case 2048:
15153 			case 4096:
15154 				if (phba->sli4_hba.pc_sli4_params.cqv ==
15155 				    LPFC_Q_CREATE_VERSION_2) {
15156 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15157 					       &cq_set->u.request,
15158 						cq->entry_count);
15159 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15160 					       &cq_set->u.request,
15161 					       LPFC_CQ_CNT_WORD7);
15162 					break;
15163 				}
15164 				/* fall through */
15165 			default:
15166 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15167 						"3118 Bad CQ count. (%d)\n",
15168 						cq->entry_count);
15169 				if (cq->entry_count < 256) {
15170 					status = -EINVAL;
15171 					goto out;
15172 				}
15173 				/* fall through - otherwise default to smallest */
15174 			case 256:
15175 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15176 				       &cq_set->u.request, LPFC_CQ_CNT_256);
15177 				break;
15178 			case 512:
15179 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15180 				       &cq_set->u.request, LPFC_CQ_CNT_512);
15181 				break;
15182 			case 1024:
15183 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15184 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
15185 				break;
15186 			}
15187 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
15188 			       &cq_set->u.request, eq->queue_id);
15189 			break;
15190 		case 1:
15191 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
15192 			       &cq_set->u.request, eq->queue_id);
15193 			break;
15194 		case 2:
15195 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
15196 			       &cq_set->u.request, eq->queue_id);
15197 			break;
15198 		case 3:
15199 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
15200 			       &cq_set->u.request, eq->queue_id);
15201 			break;
15202 		case 4:
15203 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
15204 			       &cq_set->u.request, eq->queue_id);
15205 			break;
15206 		case 5:
15207 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
15208 			       &cq_set->u.request, eq->queue_id);
15209 			break;
15210 		case 6:
15211 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
15212 			       &cq_set->u.request, eq->queue_id);
15213 			break;
15214 		case 7:
15215 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
15216 			       &cq_set->u.request, eq->queue_id);
15217 			break;
15218 		case 8:
15219 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
15220 			       &cq_set->u.request, eq->queue_id);
15221 			break;
15222 		case 9:
15223 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
15224 			       &cq_set->u.request, eq->queue_id);
15225 			break;
15226 		case 10:
15227 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
15228 			       &cq_set->u.request, eq->queue_id);
15229 			break;
15230 		case 11:
15231 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
15232 			       &cq_set->u.request, eq->queue_id);
15233 			break;
15234 		case 12:
15235 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
15236 			       &cq_set->u.request, eq->queue_id);
15237 			break;
15238 		case 13:
15239 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
15240 			       &cq_set->u.request, eq->queue_id);
15241 			break;
15242 		case 14:
15243 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
15244 			       &cq_set->u.request, eq->queue_id);
15245 			break;
15246 		case 15:
15247 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
15248 			       &cq_set->u.request, eq->queue_id);
15249 			break;
15250 		}
15251 
15252 		/* link the cq onto the parent eq child list */
15253 		list_add_tail(&cq->list, &eq->child_list);
15254 		/* Set up completion queue's type and subtype */
15255 		cq->type = type;
15256 		cq->subtype = subtype;
15257 		cq->assoc_qid = eq->queue_id;
15258 		cq->assoc_qp = eq;
15259 		cq->host_index = 0;
15260 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15261 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
15262 					 cq->entry_count);
15263 		cq->chann = idx;
15264 
15265 		rc = 0;
15266 		list_for_each_entry(dmabuf, &cq->page_list, list) {
15267 			memset(dmabuf->virt, 0, hw_page_size);
15268 			cnt = page_idx + dmabuf->buffer_tag;
15269 			cq_set->u.request.page[cnt].addr_lo =
15270 					putPaddrLow(dmabuf->phys);
15271 			cq_set->u.request.page[cnt].addr_hi =
15272 					putPaddrHigh(dmabuf->phys);
15273 			rc++;
15274 		}
15275 		page_idx += rc;
15276 	}
15277 
15278 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15279 
15280 	/* The IOCTL status is embedded in the mailbox subheader. */
15281 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15282 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15283 	if (shdr_status || shdr_add_status || rc) {
15284 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15285 				"3119 CQ_CREATE_SET mailbox failed with "
15286 				"status x%x add_status x%x, mbx status x%x\n",
15287 				shdr_status, shdr_add_status, rc);
15288 		status = -ENXIO;
15289 		goto out;
15290 	}
15291 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
15292 	if (rc == 0xFFFF) {
15293 		status = -ENXIO;
15294 		goto out;
15295 	}
15296 
15297 	for (idx = 0; idx < numcq; idx++) {
15298 		cq = cqp[idx];
15299 		cq->queue_id = rc + idx;
15300 		if (cq->queue_id > phba->sli4_hba.cq_max)
15301 			phba->sli4_hba.cq_max = cq->queue_id;
15302 	}
15303 
15304 out:
15305 	lpfc_sli4_mbox_cmd_free(phba, mbox);
15306 	return status;
15307 }
15308 
15309 /**
15310  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
15311  * @phba: HBA structure that indicates port to create a queue on.
15312  * @mq: The queue structure to use to create the mailbox queue.
15313  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
15314  * @cq: The completion queue to associate with this cq.
15315  *
15316  * This function provides failback (fb) functionality when the
15317  * mq_create_ext fails on older FW generations.  It's purpose is identical
15318  * to mq_create_ext otherwise.
15319  *
15320  * This routine cannot fail as all attributes were previously accessed and
15321  * initialized in mq_create_ext.
15322  **/
15323 static void
15324 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
15325 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
15326 {
15327 	struct lpfc_mbx_mq_create *mq_create;
15328 	struct lpfc_dmabuf *dmabuf;
15329 	int length;
15330 
15331 	length = (sizeof(struct lpfc_mbx_mq_create) -
15332 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15333 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15334 			 LPFC_MBOX_OPCODE_MQ_CREATE,
15335 			 length, LPFC_SLI4_MBX_EMBED);
15336 	mq_create = &mbox->u.mqe.un.mq_create;
15337 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
15338 	       mq->page_count);
15339 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
15340 	       cq->queue_id);
15341 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
15342 	switch (mq->entry_count) {
15343 	case 16:
15344 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15345 		       LPFC_MQ_RING_SIZE_16);
15346 		break;
15347 	case 32:
15348 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15349 		       LPFC_MQ_RING_SIZE_32);
15350 		break;
15351 	case 64:
15352 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15353 		       LPFC_MQ_RING_SIZE_64);
15354 		break;
15355 	case 128:
15356 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15357 		       LPFC_MQ_RING_SIZE_128);
15358 		break;
15359 	}
15360 	list_for_each_entry(dmabuf, &mq->page_list, list) {
15361 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15362 			putPaddrLow(dmabuf->phys);
15363 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15364 			putPaddrHigh(dmabuf->phys);
15365 	}
15366 }
15367 
15368 /**
15369  * lpfc_mq_create - Create a mailbox Queue on the HBA
15370  * @phba: HBA structure that indicates port to create a queue on.
15371  * @mq: The queue structure to use to create the mailbox queue.
15372  * @cq: The completion queue to associate with this cq.
15373  * @subtype: The queue's subtype.
15374  *
15375  * This function creates a mailbox queue, as detailed in @mq, on a port,
15376  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
15377  *
15378  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15379  * is used to get the entry count and entry size that are necessary to
15380  * determine the number of pages to allocate and use for this queue. This
15381  * function will send the MQ_CREATE mailbox command to the HBA to setup the
15382  * mailbox queue. This function is asynchronous and will wait for the mailbox
15383  * command to finish before continuing.
15384  *
15385  * On success this function will return a zero. If unable to allocate enough
15386  * memory this function will return -ENOMEM. If the queue create mailbox command
15387  * fails this function will return -ENXIO.
15388  **/
15389 int32_t
15390 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
15391 	       struct lpfc_queue *cq, uint32_t subtype)
15392 {
15393 	struct lpfc_mbx_mq_create *mq_create;
15394 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
15395 	struct lpfc_dmabuf *dmabuf;
15396 	LPFC_MBOXQ_t *mbox;
15397 	int rc, length, status = 0;
15398 	uint32_t shdr_status, shdr_add_status;
15399 	union lpfc_sli4_cfg_shdr *shdr;
15400 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15401 
15402 	/* sanity check on queue memory */
15403 	if (!mq || !cq)
15404 		return -ENODEV;
15405 	if (!phba->sli4_hba.pc_sli4_params.supported)
15406 		hw_page_size = SLI4_PAGE_SIZE;
15407 
15408 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15409 	if (!mbox)
15410 		return -ENOMEM;
15411 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
15412 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15413 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15414 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
15415 			 length, LPFC_SLI4_MBX_EMBED);
15416 
15417 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
15418 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
15419 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
15420 	       &mq_create_ext->u.request, mq->page_count);
15421 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
15422 	       &mq_create_ext->u.request, 1);
15423 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
15424 	       &mq_create_ext->u.request, 1);
15425 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
15426 	       &mq_create_ext->u.request, 1);
15427 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
15428 	       &mq_create_ext->u.request, 1);
15429 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
15430 	       &mq_create_ext->u.request, 1);
15431 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
15432 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15433 	       phba->sli4_hba.pc_sli4_params.mqv);
15434 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
15435 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
15436 		       cq->queue_id);
15437 	else
15438 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
15439 		       cq->queue_id);
15440 	switch (mq->entry_count) {
15441 	default:
15442 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15443 				"0362 Unsupported MQ count. (%d)\n",
15444 				mq->entry_count);
15445 		if (mq->entry_count < 16) {
15446 			status = -EINVAL;
15447 			goto out;
15448 		}
15449 		/* fall through - otherwise default to smallest count */
15450 	case 16:
15451 		bf_set(lpfc_mq_context_ring_size,
15452 		       &mq_create_ext->u.request.context,
15453 		       LPFC_MQ_RING_SIZE_16);
15454 		break;
15455 	case 32:
15456 		bf_set(lpfc_mq_context_ring_size,
15457 		       &mq_create_ext->u.request.context,
15458 		       LPFC_MQ_RING_SIZE_32);
15459 		break;
15460 	case 64:
15461 		bf_set(lpfc_mq_context_ring_size,
15462 		       &mq_create_ext->u.request.context,
15463 		       LPFC_MQ_RING_SIZE_64);
15464 		break;
15465 	case 128:
15466 		bf_set(lpfc_mq_context_ring_size,
15467 		       &mq_create_ext->u.request.context,
15468 		       LPFC_MQ_RING_SIZE_128);
15469 		break;
15470 	}
15471 	list_for_each_entry(dmabuf, &mq->page_list, list) {
15472 		memset(dmabuf->virt, 0, hw_page_size);
15473 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
15474 					putPaddrLow(dmabuf->phys);
15475 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
15476 					putPaddrHigh(dmabuf->phys);
15477 	}
15478 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15479 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
15480 			      &mq_create_ext->u.response);
15481 	if (rc != MBX_SUCCESS) {
15482 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15483 				"2795 MQ_CREATE_EXT failed with "
15484 				"status x%x. Failback to MQ_CREATE.\n",
15485 				rc);
15486 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
15487 		mq_create = &mbox->u.mqe.un.mq_create;
15488 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15489 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
15490 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
15491 				      &mq_create->u.response);
15492 	}
15493 
15494 	/* The IOCTL status is embedded in the mailbox subheader. */
15495 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15496 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15497 	if (shdr_status || shdr_add_status || rc) {
15498 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15499 				"2502 MQ_CREATE mailbox failed with "
15500 				"status x%x add_status x%x, mbx status x%x\n",
15501 				shdr_status, shdr_add_status, rc);
15502 		status = -ENXIO;
15503 		goto out;
15504 	}
15505 	if (mq->queue_id == 0xFFFF) {
15506 		status = -ENXIO;
15507 		goto out;
15508 	}
15509 	mq->type = LPFC_MQ;
15510 	mq->assoc_qid = cq->queue_id;
15511 	mq->subtype = subtype;
15512 	mq->host_index = 0;
15513 	mq->hba_index = 0;
15514 
15515 	/* link the mq onto the parent cq child list */
15516 	list_add_tail(&mq->list, &cq->child_list);
15517 out:
15518 	mempool_free(mbox, phba->mbox_mem_pool);
15519 	return status;
15520 }
15521 
15522 /**
15523  * lpfc_wq_create - Create a Work Queue on the HBA
15524  * @phba: HBA structure that indicates port to create a queue on.
15525  * @wq: The queue structure to use to create the work queue.
15526  * @cq: The completion queue to bind this work queue to.
15527  * @subtype: The subtype of the work queue indicating its functionality.
15528  *
15529  * This function creates a work queue, as detailed in @wq, on a port, described
15530  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
15531  *
15532  * The @phba struct is used to send mailbox command to HBA. The @wq struct
15533  * is used to get the entry count and entry size that are necessary to
15534  * determine the number of pages to allocate and use for this queue. The @cq
15535  * is used to indicate which completion queue to bind this work queue to. This
15536  * function will send the WQ_CREATE mailbox command to the HBA to setup the
15537  * work queue. This function is asynchronous and will wait for the mailbox
15538  * command to finish before continuing.
15539  *
15540  * On success this function will return a zero. If unable to allocate enough
15541  * memory this function will return -ENOMEM. If the queue create mailbox command
15542  * fails this function will return -ENXIO.
15543  **/
15544 int
15545 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
15546 	       struct lpfc_queue *cq, uint32_t subtype)
15547 {
15548 	struct lpfc_mbx_wq_create *wq_create;
15549 	struct lpfc_dmabuf *dmabuf;
15550 	LPFC_MBOXQ_t *mbox;
15551 	int rc, length, status = 0;
15552 	uint32_t shdr_status, shdr_add_status;
15553 	union lpfc_sli4_cfg_shdr *shdr;
15554 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15555 	struct dma_address *page;
15556 	void __iomem *bar_memmap_p;
15557 	uint32_t db_offset;
15558 	uint16_t pci_barset;
15559 	uint8_t dpp_barset;
15560 	uint32_t dpp_offset;
15561 	unsigned long pg_addr;
15562 	uint8_t wq_create_version;
15563 
15564 	/* sanity check on queue memory */
15565 	if (!wq || !cq)
15566 		return -ENODEV;
15567 	if (!phba->sli4_hba.pc_sli4_params.supported)
15568 		hw_page_size = wq->page_size;
15569 
15570 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15571 	if (!mbox)
15572 		return -ENOMEM;
15573 	length = (sizeof(struct lpfc_mbx_wq_create) -
15574 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15575 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15576 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
15577 			 length, LPFC_SLI4_MBX_EMBED);
15578 	wq_create = &mbox->u.mqe.un.wq_create;
15579 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
15580 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
15581 		    wq->page_count);
15582 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
15583 		    cq->queue_id);
15584 
15585 	/* wqv is the earliest version supported, NOT the latest */
15586 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15587 	       phba->sli4_hba.pc_sli4_params.wqv);
15588 
15589 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
15590 	    (wq->page_size > SLI4_PAGE_SIZE))
15591 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
15592 	else
15593 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
15594 
15595 
15596 	if (phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT)
15597 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
15598 	else
15599 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
15600 
15601 	switch (wq_create_version) {
15602 	case LPFC_Q_CREATE_VERSION_1:
15603 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
15604 		       wq->entry_count);
15605 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
15606 		       LPFC_Q_CREATE_VERSION_1);
15607 
15608 		switch (wq->entry_size) {
15609 		default:
15610 		case 64:
15611 			bf_set(lpfc_mbx_wq_create_wqe_size,
15612 			       &wq_create->u.request_1,
15613 			       LPFC_WQ_WQE_SIZE_64);
15614 			break;
15615 		case 128:
15616 			bf_set(lpfc_mbx_wq_create_wqe_size,
15617 			       &wq_create->u.request_1,
15618 			       LPFC_WQ_WQE_SIZE_128);
15619 			break;
15620 		}
15621 		/* Request DPP by default */
15622 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
15623 		bf_set(lpfc_mbx_wq_create_page_size,
15624 		       &wq_create->u.request_1,
15625 		       (wq->page_size / SLI4_PAGE_SIZE));
15626 		page = wq_create->u.request_1.page;
15627 		break;
15628 	default:
15629 		page = wq_create->u.request.page;
15630 		break;
15631 	}
15632 
15633 	list_for_each_entry(dmabuf, &wq->page_list, list) {
15634 		memset(dmabuf->virt, 0, hw_page_size);
15635 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
15636 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
15637 	}
15638 
15639 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
15640 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
15641 
15642 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15643 	/* The IOCTL status is embedded in the mailbox subheader. */
15644 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15645 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15646 	if (shdr_status || shdr_add_status || rc) {
15647 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15648 				"2503 WQ_CREATE mailbox failed with "
15649 				"status x%x add_status x%x, mbx status x%x\n",
15650 				shdr_status, shdr_add_status, rc);
15651 		status = -ENXIO;
15652 		goto out;
15653 	}
15654 
15655 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
15656 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
15657 					&wq_create->u.response);
15658 	else
15659 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
15660 					&wq_create->u.response_1);
15661 
15662 	if (wq->queue_id == 0xFFFF) {
15663 		status = -ENXIO;
15664 		goto out;
15665 	}
15666 
15667 	wq->db_format = LPFC_DB_LIST_FORMAT;
15668 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
15669 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
15670 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
15671 					       &wq_create->u.response);
15672 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
15673 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
15674 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15675 						"3265 WQ[%d] doorbell format "
15676 						"not supported: x%x\n",
15677 						wq->queue_id, wq->db_format);
15678 				status = -EINVAL;
15679 				goto out;
15680 			}
15681 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
15682 					    &wq_create->u.response);
15683 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15684 								   pci_barset);
15685 			if (!bar_memmap_p) {
15686 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15687 						"3263 WQ[%d] failed to memmap "
15688 						"pci barset:x%x\n",
15689 						wq->queue_id, pci_barset);
15690 				status = -ENOMEM;
15691 				goto out;
15692 			}
15693 			db_offset = wq_create->u.response.doorbell_offset;
15694 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
15695 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
15696 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15697 						"3252 WQ[%d] doorbell offset "
15698 						"not supported: x%x\n",
15699 						wq->queue_id, db_offset);
15700 				status = -EINVAL;
15701 				goto out;
15702 			}
15703 			wq->db_regaddr = bar_memmap_p + db_offset;
15704 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15705 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
15706 					"format:x%x\n", wq->queue_id,
15707 					pci_barset, db_offset, wq->db_format);
15708 		} else
15709 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
15710 	} else {
15711 		/* Check if DPP was honored by the firmware */
15712 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
15713 				    &wq_create->u.response_1);
15714 		if (wq->dpp_enable) {
15715 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
15716 					    &wq_create->u.response_1);
15717 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15718 								   pci_barset);
15719 			if (!bar_memmap_p) {
15720 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15721 						"3267 WQ[%d] failed to memmap "
15722 						"pci barset:x%x\n",
15723 						wq->queue_id, pci_barset);
15724 				status = -ENOMEM;
15725 				goto out;
15726 			}
15727 			db_offset = wq_create->u.response_1.doorbell_offset;
15728 			wq->db_regaddr = bar_memmap_p + db_offset;
15729 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
15730 					    &wq_create->u.response_1);
15731 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
15732 					    &wq_create->u.response_1);
15733 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15734 								   dpp_barset);
15735 			if (!bar_memmap_p) {
15736 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15737 						"3268 WQ[%d] failed to memmap "
15738 						"pci barset:x%x\n",
15739 						wq->queue_id, dpp_barset);
15740 				status = -ENOMEM;
15741 				goto out;
15742 			}
15743 			dpp_offset = wq_create->u.response_1.dpp_offset;
15744 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
15745 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15746 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
15747 					"dpp_id:x%x dpp_barset:x%x "
15748 					"dpp_offset:x%x\n",
15749 					wq->queue_id, pci_barset, db_offset,
15750 					wq->dpp_id, dpp_barset, dpp_offset);
15751 
15752 			/* Enable combined writes for DPP aperture */
15753 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
15754 #ifdef CONFIG_X86
15755 			rc = set_memory_wc(pg_addr, 1);
15756 			if (rc) {
15757 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15758 					"3272 Cannot setup Combined "
15759 					"Write on WQ[%d] - disable DPP\n",
15760 					wq->queue_id);
15761 				phba->cfg_enable_dpp = 0;
15762 			}
15763 #else
15764 			phba->cfg_enable_dpp = 0;
15765 #endif
15766 		} else
15767 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
15768 	}
15769 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
15770 	if (wq->pring == NULL) {
15771 		status = -ENOMEM;
15772 		goto out;
15773 	}
15774 	wq->type = LPFC_WQ;
15775 	wq->assoc_qid = cq->queue_id;
15776 	wq->subtype = subtype;
15777 	wq->host_index = 0;
15778 	wq->hba_index = 0;
15779 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
15780 
15781 	/* link the wq onto the parent cq child list */
15782 	list_add_tail(&wq->list, &cq->child_list);
15783 out:
15784 	mempool_free(mbox, phba->mbox_mem_pool);
15785 	return status;
15786 }
15787 
15788 /**
15789  * lpfc_rq_create - Create a Receive Queue on the HBA
15790  * @phba: HBA structure that indicates port to create a queue on.
15791  * @hrq: The queue structure to use to create the header receive queue.
15792  * @drq: The queue structure to use to create the data receive queue.
15793  * @cq: The completion queue to bind this work queue to.
15794  *
15795  * This function creates a receive buffer queue pair , as detailed in @hrq and
15796  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
15797  * to the HBA.
15798  *
15799  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
15800  * struct is used to get the entry count that is necessary to determine the
15801  * number of pages to use for this queue. The @cq is used to indicate which
15802  * completion queue to bind received buffers that are posted to these queues to.
15803  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
15804  * receive queue pair. This function is asynchronous and will wait for the
15805  * mailbox command to finish before continuing.
15806  *
15807  * On success this function will return a zero. If unable to allocate enough
15808  * memory this function will return -ENOMEM. If the queue create mailbox command
15809  * fails this function will return -ENXIO.
15810  **/
15811 int
15812 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
15813 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
15814 {
15815 	struct lpfc_mbx_rq_create *rq_create;
15816 	struct lpfc_dmabuf *dmabuf;
15817 	LPFC_MBOXQ_t *mbox;
15818 	int rc, length, status = 0;
15819 	uint32_t shdr_status, shdr_add_status;
15820 	union lpfc_sli4_cfg_shdr *shdr;
15821 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15822 	void __iomem *bar_memmap_p;
15823 	uint32_t db_offset;
15824 	uint16_t pci_barset;
15825 
15826 	/* sanity check on queue memory */
15827 	if (!hrq || !drq || !cq)
15828 		return -ENODEV;
15829 	if (!phba->sli4_hba.pc_sli4_params.supported)
15830 		hw_page_size = SLI4_PAGE_SIZE;
15831 
15832 	if (hrq->entry_count != drq->entry_count)
15833 		return -EINVAL;
15834 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15835 	if (!mbox)
15836 		return -ENOMEM;
15837 	length = (sizeof(struct lpfc_mbx_rq_create) -
15838 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15839 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15840 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
15841 			 length, LPFC_SLI4_MBX_EMBED);
15842 	rq_create = &mbox->u.mqe.un.rq_create;
15843 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
15844 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15845 	       phba->sli4_hba.pc_sli4_params.rqv);
15846 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
15847 		bf_set(lpfc_rq_context_rqe_count_1,
15848 		       &rq_create->u.request.context,
15849 		       hrq->entry_count);
15850 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
15851 		bf_set(lpfc_rq_context_rqe_size,
15852 		       &rq_create->u.request.context,
15853 		       LPFC_RQE_SIZE_8);
15854 		bf_set(lpfc_rq_context_page_size,
15855 		       &rq_create->u.request.context,
15856 		       LPFC_RQ_PAGE_SIZE_4096);
15857 	} else {
15858 		switch (hrq->entry_count) {
15859 		default:
15860 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15861 					"2535 Unsupported RQ count. (%d)\n",
15862 					hrq->entry_count);
15863 			if (hrq->entry_count < 512) {
15864 				status = -EINVAL;
15865 				goto out;
15866 			}
15867 			/* fall through - otherwise default to smallest count */
15868 		case 512:
15869 			bf_set(lpfc_rq_context_rqe_count,
15870 			       &rq_create->u.request.context,
15871 			       LPFC_RQ_RING_SIZE_512);
15872 			break;
15873 		case 1024:
15874 			bf_set(lpfc_rq_context_rqe_count,
15875 			       &rq_create->u.request.context,
15876 			       LPFC_RQ_RING_SIZE_1024);
15877 			break;
15878 		case 2048:
15879 			bf_set(lpfc_rq_context_rqe_count,
15880 			       &rq_create->u.request.context,
15881 			       LPFC_RQ_RING_SIZE_2048);
15882 			break;
15883 		case 4096:
15884 			bf_set(lpfc_rq_context_rqe_count,
15885 			       &rq_create->u.request.context,
15886 			       LPFC_RQ_RING_SIZE_4096);
15887 			break;
15888 		}
15889 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
15890 		       LPFC_HDR_BUF_SIZE);
15891 	}
15892 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
15893 	       cq->queue_id);
15894 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
15895 	       hrq->page_count);
15896 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
15897 		memset(dmabuf->virt, 0, hw_page_size);
15898 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15899 					putPaddrLow(dmabuf->phys);
15900 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15901 					putPaddrHigh(dmabuf->phys);
15902 	}
15903 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
15904 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
15905 
15906 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15907 	/* The IOCTL status is embedded in the mailbox subheader. */
15908 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15909 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15910 	if (shdr_status || shdr_add_status || rc) {
15911 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15912 				"2504 RQ_CREATE mailbox failed with "
15913 				"status x%x add_status x%x, mbx status x%x\n",
15914 				shdr_status, shdr_add_status, rc);
15915 		status = -ENXIO;
15916 		goto out;
15917 	}
15918 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
15919 	if (hrq->queue_id == 0xFFFF) {
15920 		status = -ENXIO;
15921 		goto out;
15922 	}
15923 
15924 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
15925 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
15926 					&rq_create->u.response);
15927 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
15928 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
15929 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15930 					"3262 RQ [%d] doorbell format not "
15931 					"supported: x%x\n", hrq->queue_id,
15932 					hrq->db_format);
15933 			status = -EINVAL;
15934 			goto out;
15935 		}
15936 
15937 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
15938 				    &rq_create->u.response);
15939 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
15940 		if (!bar_memmap_p) {
15941 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15942 					"3269 RQ[%d] failed to memmap pci "
15943 					"barset:x%x\n", hrq->queue_id,
15944 					pci_barset);
15945 			status = -ENOMEM;
15946 			goto out;
15947 		}
15948 
15949 		db_offset = rq_create->u.response.doorbell_offset;
15950 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
15951 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
15952 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15953 					"3270 RQ[%d] doorbell offset not "
15954 					"supported: x%x\n", hrq->queue_id,
15955 					db_offset);
15956 			status = -EINVAL;
15957 			goto out;
15958 		}
15959 		hrq->db_regaddr = bar_memmap_p + db_offset;
15960 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15961 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
15962 				"format:x%x\n", hrq->queue_id, pci_barset,
15963 				db_offset, hrq->db_format);
15964 	} else {
15965 		hrq->db_format = LPFC_DB_RING_FORMAT;
15966 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
15967 	}
15968 	hrq->type = LPFC_HRQ;
15969 	hrq->assoc_qid = cq->queue_id;
15970 	hrq->subtype = subtype;
15971 	hrq->host_index = 0;
15972 	hrq->hba_index = 0;
15973 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
15974 
15975 	/* now create the data queue */
15976 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15977 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
15978 			 length, LPFC_SLI4_MBX_EMBED);
15979 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15980 	       phba->sli4_hba.pc_sli4_params.rqv);
15981 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
15982 		bf_set(lpfc_rq_context_rqe_count_1,
15983 		       &rq_create->u.request.context, hrq->entry_count);
15984 		if (subtype == LPFC_NVMET)
15985 			rq_create->u.request.context.buffer_size =
15986 				LPFC_NVMET_DATA_BUF_SIZE;
15987 		else
15988 			rq_create->u.request.context.buffer_size =
15989 				LPFC_DATA_BUF_SIZE;
15990 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
15991 		       LPFC_RQE_SIZE_8);
15992 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
15993 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
15994 	} else {
15995 		switch (drq->entry_count) {
15996 		default:
15997 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15998 					"2536 Unsupported RQ count. (%d)\n",
15999 					drq->entry_count);
16000 			if (drq->entry_count < 512) {
16001 				status = -EINVAL;
16002 				goto out;
16003 			}
16004 			/* fall through - otherwise default to smallest count */
16005 		case 512:
16006 			bf_set(lpfc_rq_context_rqe_count,
16007 			       &rq_create->u.request.context,
16008 			       LPFC_RQ_RING_SIZE_512);
16009 			break;
16010 		case 1024:
16011 			bf_set(lpfc_rq_context_rqe_count,
16012 			       &rq_create->u.request.context,
16013 			       LPFC_RQ_RING_SIZE_1024);
16014 			break;
16015 		case 2048:
16016 			bf_set(lpfc_rq_context_rqe_count,
16017 			       &rq_create->u.request.context,
16018 			       LPFC_RQ_RING_SIZE_2048);
16019 			break;
16020 		case 4096:
16021 			bf_set(lpfc_rq_context_rqe_count,
16022 			       &rq_create->u.request.context,
16023 			       LPFC_RQ_RING_SIZE_4096);
16024 			break;
16025 		}
16026 		if (subtype == LPFC_NVMET)
16027 			bf_set(lpfc_rq_context_buf_size,
16028 			       &rq_create->u.request.context,
16029 			       LPFC_NVMET_DATA_BUF_SIZE);
16030 		else
16031 			bf_set(lpfc_rq_context_buf_size,
16032 			       &rq_create->u.request.context,
16033 			       LPFC_DATA_BUF_SIZE);
16034 	}
16035 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16036 	       cq->queue_id);
16037 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16038 	       drq->page_count);
16039 	list_for_each_entry(dmabuf, &drq->page_list, list) {
16040 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16041 					putPaddrLow(dmabuf->phys);
16042 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16043 					putPaddrHigh(dmabuf->phys);
16044 	}
16045 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16046 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16047 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16048 	/* The IOCTL status is embedded in the mailbox subheader. */
16049 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
16050 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16051 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16052 	if (shdr_status || shdr_add_status || rc) {
16053 		status = -ENXIO;
16054 		goto out;
16055 	}
16056 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16057 	if (drq->queue_id == 0xFFFF) {
16058 		status = -ENXIO;
16059 		goto out;
16060 	}
16061 	drq->type = LPFC_DRQ;
16062 	drq->assoc_qid = cq->queue_id;
16063 	drq->subtype = subtype;
16064 	drq->host_index = 0;
16065 	drq->hba_index = 0;
16066 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16067 
16068 	/* link the header and data RQs onto the parent cq child list */
16069 	list_add_tail(&hrq->list, &cq->child_list);
16070 	list_add_tail(&drq->list, &cq->child_list);
16071 
16072 out:
16073 	mempool_free(mbox, phba->mbox_mem_pool);
16074 	return status;
16075 }
16076 
16077 /**
16078  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
16079  * @phba: HBA structure that indicates port to create a queue on.
16080  * @hrqp: The queue structure array to use to create the header receive queues.
16081  * @drqp: The queue structure array to use to create the data receive queues.
16082  * @cqp: The completion queue array to bind these receive queues to.
16083  *
16084  * This function creates a receive buffer queue pair , as detailed in @hrq and
16085  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
16086  * to the HBA.
16087  *
16088  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
16089  * struct is used to get the entry count that is necessary to determine the
16090  * number of pages to use for this queue. The @cq is used to indicate which
16091  * completion queue to bind received buffers that are posted to these queues to.
16092  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
16093  * receive queue pair. This function is asynchronous and will wait for the
16094  * mailbox command to finish before continuing.
16095  *
16096  * On success this function will return a zero. If unable to allocate enough
16097  * memory this function will return -ENOMEM. If the queue create mailbox command
16098  * fails this function will return -ENXIO.
16099  **/
16100 int
16101 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
16102 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
16103 		uint32_t subtype)
16104 {
16105 	struct lpfc_queue *hrq, *drq, *cq;
16106 	struct lpfc_mbx_rq_create_v2 *rq_create;
16107 	struct lpfc_dmabuf *dmabuf;
16108 	LPFC_MBOXQ_t *mbox;
16109 	int rc, length, alloclen, status = 0;
16110 	int cnt, idx, numrq, page_idx = 0;
16111 	uint32_t shdr_status, shdr_add_status;
16112 	union lpfc_sli4_cfg_shdr *shdr;
16113 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16114 
16115 	numrq = phba->cfg_nvmet_mrq;
16116 	/* sanity check on array memory */
16117 	if (!hrqp || !drqp || !cqp || !numrq)
16118 		return -ENODEV;
16119 	if (!phba->sli4_hba.pc_sli4_params.supported)
16120 		hw_page_size = SLI4_PAGE_SIZE;
16121 
16122 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16123 	if (!mbox)
16124 		return -ENOMEM;
16125 
16126 	length = sizeof(struct lpfc_mbx_rq_create_v2);
16127 	length += ((2 * numrq * hrqp[0]->page_count) *
16128 		   sizeof(struct dma_address));
16129 
16130 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16131 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
16132 				    LPFC_SLI4_MBX_NEMBED);
16133 	if (alloclen < length) {
16134 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16135 				"3099 Allocated DMA memory size (%d) is "
16136 				"less than the requested DMA memory size "
16137 				"(%d)\n", alloclen, length);
16138 		status = -ENOMEM;
16139 		goto out;
16140 	}
16141 
16142 
16143 
16144 	rq_create = mbox->sge_array->addr[0];
16145 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
16146 
16147 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
16148 	cnt = 0;
16149 
16150 	for (idx = 0; idx < numrq; idx++) {
16151 		hrq = hrqp[idx];
16152 		drq = drqp[idx];
16153 		cq  = cqp[idx];
16154 
16155 		/* sanity check on queue memory */
16156 		if (!hrq || !drq || !cq) {
16157 			status = -ENODEV;
16158 			goto out;
16159 		}
16160 
16161 		if (hrq->entry_count != drq->entry_count) {
16162 			status = -EINVAL;
16163 			goto out;
16164 		}
16165 
16166 		if (idx == 0) {
16167 			bf_set(lpfc_mbx_rq_create_num_pages,
16168 			       &rq_create->u.request,
16169 			       hrq->page_count);
16170 			bf_set(lpfc_mbx_rq_create_rq_cnt,
16171 			       &rq_create->u.request, (numrq * 2));
16172 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
16173 			       1);
16174 			bf_set(lpfc_rq_context_base_cq,
16175 			       &rq_create->u.request.context,
16176 			       cq->queue_id);
16177 			bf_set(lpfc_rq_context_data_size,
16178 			       &rq_create->u.request.context,
16179 			       LPFC_NVMET_DATA_BUF_SIZE);
16180 			bf_set(lpfc_rq_context_hdr_size,
16181 			       &rq_create->u.request.context,
16182 			       LPFC_HDR_BUF_SIZE);
16183 			bf_set(lpfc_rq_context_rqe_count_1,
16184 			       &rq_create->u.request.context,
16185 			       hrq->entry_count);
16186 			bf_set(lpfc_rq_context_rqe_size,
16187 			       &rq_create->u.request.context,
16188 			       LPFC_RQE_SIZE_8);
16189 			bf_set(lpfc_rq_context_page_size,
16190 			       &rq_create->u.request.context,
16191 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
16192 		}
16193 		rc = 0;
16194 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
16195 			memset(dmabuf->virt, 0, hw_page_size);
16196 			cnt = page_idx + dmabuf->buffer_tag;
16197 			rq_create->u.request.page[cnt].addr_lo =
16198 					putPaddrLow(dmabuf->phys);
16199 			rq_create->u.request.page[cnt].addr_hi =
16200 					putPaddrHigh(dmabuf->phys);
16201 			rc++;
16202 		}
16203 		page_idx += rc;
16204 
16205 		rc = 0;
16206 		list_for_each_entry(dmabuf, &drq->page_list, list) {
16207 			memset(dmabuf->virt, 0, hw_page_size);
16208 			cnt = page_idx + dmabuf->buffer_tag;
16209 			rq_create->u.request.page[cnt].addr_lo =
16210 					putPaddrLow(dmabuf->phys);
16211 			rq_create->u.request.page[cnt].addr_hi =
16212 					putPaddrHigh(dmabuf->phys);
16213 			rc++;
16214 		}
16215 		page_idx += rc;
16216 
16217 		hrq->db_format = LPFC_DB_RING_FORMAT;
16218 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16219 		hrq->type = LPFC_HRQ;
16220 		hrq->assoc_qid = cq->queue_id;
16221 		hrq->subtype = subtype;
16222 		hrq->host_index = 0;
16223 		hrq->hba_index = 0;
16224 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16225 
16226 		drq->db_format = LPFC_DB_RING_FORMAT;
16227 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16228 		drq->type = LPFC_DRQ;
16229 		drq->assoc_qid = cq->queue_id;
16230 		drq->subtype = subtype;
16231 		drq->host_index = 0;
16232 		drq->hba_index = 0;
16233 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16234 
16235 		list_add_tail(&hrq->list, &cq->child_list);
16236 		list_add_tail(&drq->list, &cq->child_list);
16237 	}
16238 
16239 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16240 	/* The IOCTL status is embedded in the mailbox subheader. */
16241 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16242 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16243 	if (shdr_status || shdr_add_status || rc) {
16244 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16245 				"3120 RQ_CREATE mailbox failed with "
16246 				"status x%x add_status x%x, mbx status x%x\n",
16247 				shdr_status, shdr_add_status, rc);
16248 		status = -ENXIO;
16249 		goto out;
16250 	}
16251 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16252 	if (rc == 0xFFFF) {
16253 		status = -ENXIO;
16254 		goto out;
16255 	}
16256 
16257 	/* Initialize all RQs with associated queue id */
16258 	for (idx = 0; idx < numrq; idx++) {
16259 		hrq = hrqp[idx];
16260 		hrq->queue_id = rc + (2 * idx);
16261 		drq = drqp[idx];
16262 		drq->queue_id = rc + (2 * idx) + 1;
16263 	}
16264 
16265 out:
16266 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16267 	return status;
16268 }
16269 
16270 /**
16271  * lpfc_eq_destroy - Destroy an event Queue on the HBA
16272  * @eq: The queue structure associated with the queue to destroy.
16273  *
16274  * This function destroys a queue, as detailed in @eq by sending an mailbox
16275  * command, specific to the type of queue, to the HBA.
16276  *
16277  * The @eq struct is used to get the queue ID of the queue to destroy.
16278  *
16279  * On success this function will return a zero. If the queue destroy mailbox
16280  * command fails this function will return -ENXIO.
16281  **/
16282 int
16283 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
16284 {
16285 	LPFC_MBOXQ_t *mbox;
16286 	int rc, length, status = 0;
16287 	uint32_t shdr_status, shdr_add_status;
16288 	union lpfc_sli4_cfg_shdr *shdr;
16289 
16290 	/* sanity check on queue memory */
16291 	if (!eq)
16292 		return -ENODEV;
16293 
16294 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
16295 	if (!mbox)
16296 		return -ENOMEM;
16297 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
16298 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16299 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16300 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
16301 			 length, LPFC_SLI4_MBX_EMBED);
16302 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
16303 	       eq->queue_id);
16304 	mbox->vport = eq->phba->pport;
16305 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16306 
16307 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
16308 	/* The IOCTL status is embedded in the mailbox subheader. */
16309 	shdr = (union lpfc_sli4_cfg_shdr *)
16310 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
16311 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16312 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16313 	if (shdr_status || shdr_add_status || rc) {
16314 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16315 				"2505 EQ_DESTROY mailbox failed with "
16316 				"status x%x add_status x%x, mbx status x%x\n",
16317 				shdr_status, shdr_add_status, rc);
16318 		status = -ENXIO;
16319 	}
16320 
16321 	/* Remove eq from any list */
16322 	list_del_init(&eq->list);
16323 	mempool_free(mbox, eq->phba->mbox_mem_pool);
16324 	return status;
16325 }
16326 
16327 /**
16328  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
16329  * @cq: The queue structure associated with the queue to destroy.
16330  *
16331  * This function destroys a queue, as detailed in @cq by sending an mailbox
16332  * command, specific to the type of queue, to the HBA.
16333  *
16334  * The @cq struct is used to get the queue ID of the queue to destroy.
16335  *
16336  * On success this function will return a zero. If the queue destroy mailbox
16337  * command fails this function will return -ENXIO.
16338  **/
16339 int
16340 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
16341 {
16342 	LPFC_MBOXQ_t *mbox;
16343 	int rc, length, status = 0;
16344 	uint32_t shdr_status, shdr_add_status;
16345 	union lpfc_sli4_cfg_shdr *shdr;
16346 
16347 	/* sanity check on queue memory */
16348 	if (!cq)
16349 		return -ENODEV;
16350 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
16351 	if (!mbox)
16352 		return -ENOMEM;
16353 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
16354 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16355 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16356 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
16357 			 length, LPFC_SLI4_MBX_EMBED);
16358 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
16359 	       cq->queue_id);
16360 	mbox->vport = cq->phba->pport;
16361 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16362 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
16363 	/* The IOCTL status is embedded in the mailbox subheader. */
16364 	shdr = (union lpfc_sli4_cfg_shdr *)
16365 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
16366 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16367 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16368 	if (shdr_status || shdr_add_status || rc) {
16369 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16370 				"2506 CQ_DESTROY mailbox failed with "
16371 				"status x%x add_status x%x, mbx status x%x\n",
16372 				shdr_status, shdr_add_status, rc);
16373 		status = -ENXIO;
16374 	}
16375 	/* Remove cq from any list */
16376 	list_del_init(&cq->list);
16377 	mempool_free(mbox, cq->phba->mbox_mem_pool);
16378 	return status;
16379 }
16380 
16381 /**
16382  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
16383  * @qm: The queue structure associated with the queue to destroy.
16384  *
16385  * This function destroys a queue, as detailed in @mq by sending an mailbox
16386  * command, specific to the type of queue, to the HBA.
16387  *
16388  * The @mq struct is used to get the queue ID of the queue to destroy.
16389  *
16390  * On success this function will return a zero. If the queue destroy mailbox
16391  * command fails this function will return -ENXIO.
16392  **/
16393 int
16394 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
16395 {
16396 	LPFC_MBOXQ_t *mbox;
16397 	int rc, length, status = 0;
16398 	uint32_t shdr_status, shdr_add_status;
16399 	union lpfc_sli4_cfg_shdr *shdr;
16400 
16401 	/* sanity check on queue memory */
16402 	if (!mq)
16403 		return -ENODEV;
16404 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
16405 	if (!mbox)
16406 		return -ENOMEM;
16407 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
16408 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16409 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16410 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
16411 			 length, LPFC_SLI4_MBX_EMBED);
16412 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
16413 	       mq->queue_id);
16414 	mbox->vport = mq->phba->pport;
16415 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16416 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
16417 	/* The IOCTL status is embedded in the mailbox subheader. */
16418 	shdr = (union lpfc_sli4_cfg_shdr *)
16419 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
16420 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16421 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16422 	if (shdr_status || shdr_add_status || rc) {
16423 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16424 				"2507 MQ_DESTROY mailbox failed with "
16425 				"status x%x add_status x%x, mbx status x%x\n",
16426 				shdr_status, shdr_add_status, rc);
16427 		status = -ENXIO;
16428 	}
16429 	/* Remove mq from any list */
16430 	list_del_init(&mq->list);
16431 	mempool_free(mbox, mq->phba->mbox_mem_pool);
16432 	return status;
16433 }
16434 
16435 /**
16436  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
16437  * @wq: The queue structure associated with the queue to destroy.
16438  *
16439  * This function destroys a queue, as detailed in @wq by sending an mailbox
16440  * command, specific to the type of queue, to the HBA.
16441  *
16442  * The @wq struct is used to get the queue ID of the queue to destroy.
16443  *
16444  * On success this function will return a zero. If the queue destroy mailbox
16445  * command fails this function will return -ENXIO.
16446  **/
16447 int
16448 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
16449 {
16450 	LPFC_MBOXQ_t *mbox;
16451 	int rc, length, status = 0;
16452 	uint32_t shdr_status, shdr_add_status;
16453 	union lpfc_sli4_cfg_shdr *shdr;
16454 
16455 	/* sanity check on queue memory */
16456 	if (!wq)
16457 		return -ENODEV;
16458 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
16459 	if (!mbox)
16460 		return -ENOMEM;
16461 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
16462 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16463 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16464 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
16465 			 length, LPFC_SLI4_MBX_EMBED);
16466 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
16467 	       wq->queue_id);
16468 	mbox->vport = wq->phba->pport;
16469 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16470 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
16471 	shdr = (union lpfc_sli4_cfg_shdr *)
16472 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
16473 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16474 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16475 	if (shdr_status || shdr_add_status || rc) {
16476 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16477 				"2508 WQ_DESTROY mailbox failed with "
16478 				"status x%x add_status x%x, mbx status x%x\n",
16479 				shdr_status, shdr_add_status, rc);
16480 		status = -ENXIO;
16481 	}
16482 	/* Remove wq from any list */
16483 	list_del_init(&wq->list);
16484 	kfree(wq->pring);
16485 	wq->pring = NULL;
16486 	mempool_free(mbox, wq->phba->mbox_mem_pool);
16487 	return status;
16488 }
16489 
16490 /**
16491  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
16492  * @rq: The queue structure associated with the queue to destroy.
16493  *
16494  * This function destroys a queue, as detailed in @rq by sending an mailbox
16495  * command, specific to the type of queue, to the HBA.
16496  *
16497  * The @rq struct is used to get the queue ID of the queue to destroy.
16498  *
16499  * On success this function will return a zero. If the queue destroy mailbox
16500  * command fails this function will return -ENXIO.
16501  **/
16502 int
16503 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
16504 		struct lpfc_queue *drq)
16505 {
16506 	LPFC_MBOXQ_t *mbox;
16507 	int rc, length, status = 0;
16508 	uint32_t shdr_status, shdr_add_status;
16509 	union lpfc_sli4_cfg_shdr *shdr;
16510 
16511 	/* sanity check on queue memory */
16512 	if (!hrq || !drq)
16513 		return -ENODEV;
16514 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
16515 	if (!mbox)
16516 		return -ENOMEM;
16517 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
16518 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16519 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16520 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
16521 			 length, LPFC_SLI4_MBX_EMBED);
16522 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
16523 	       hrq->queue_id);
16524 	mbox->vport = hrq->phba->pport;
16525 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16526 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
16527 	/* The IOCTL status is embedded in the mailbox subheader. */
16528 	shdr = (union lpfc_sli4_cfg_shdr *)
16529 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
16530 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16531 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16532 	if (shdr_status || shdr_add_status || rc) {
16533 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16534 				"2509 RQ_DESTROY mailbox failed with "
16535 				"status x%x add_status x%x, mbx status x%x\n",
16536 				shdr_status, shdr_add_status, rc);
16537 		if (rc != MBX_TIMEOUT)
16538 			mempool_free(mbox, hrq->phba->mbox_mem_pool);
16539 		return -ENXIO;
16540 	}
16541 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
16542 	       drq->queue_id);
16543 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
16544 	shdr = (union lpfc_sli4_cfg_shdr *)
16545 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
16546 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16547 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16548 	if (shdr_status || shdr_add_status || rc) {
16549 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16550 				"2510 RQ_DESTROY mailbox failed with "
16551 				"status x%x add_status x%x, mbx status x%x\n",
16552 				shdr_status, shdr_add_status, rc);
16553 		status = -ENXIO;
16554 	}
16555 	list_del_init(&hrq->list);
16556 	list_del_init(&drq->list);
16557 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
16558 	return status;
16559 }
16560 
16561 /**
16562  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
16563  * @phba: The virtual port for which this call being executed.
16564  * @pdma_phys_addr0: Physical address of the 1st SGL page.
16565  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
16566  * @xritag: the xritag that ties this io to the SGL pages.
16567  *
16568  * This routine will post the sgl pages for the IO that has the xritag
16569  * that is in the iocbq structure. The xritag is assigned during iocbq
16570  * creation and persists for as long as the driver is loaded.
16571  * if the caller has fewer than 256 scatter gather segments to map then
16572  * pdma_phys_addr1 should be 0.
16573  * If the caller needs to map more than 256 scatter gather segment then
16574  * pdma_phys_addr1 should be a valid physical address.
16575  * physical address for SGLs must be 64 byte aligned.
16576  * If you are going to map 2 SGL's then the first one must have 256 entries
16577  * the second sgl can have between 1 and 256 entries.
16578  *
16579  * Return codes:
16580  * 	0 - Success
16581  * 	-ENXIO, -ENOMEM - Failure
16582  **/
16583 int
16584 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
16585 		dma_addr_t pdma_phys_addr0,
16586 		dma_addr_t pdma_phys_addr1,
16587 		uint16_t xritag)
16588 {
16589 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
16590 	LPFC_MBOXQ_t *mbox;
16591 	int rc;
16592 	uint32_t shdr_status, shdr_add_status;
16593 	uint32_t mbox_tmo;
16594 	union lpfc_sli4_cfg_shdr *shdr;
16595 
16596 	if (xritag == NO_XRI) {
16597 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16598 				"0364 Invalid param:\n");
16599 		return -EINVAL;
16600 	}
16601 
16602 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16603 	if (!mbox)
16604 		return -ENOMEM;
16605 
16606 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16607 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
16608 			sizeof(struct lpfc_mbx_post_sgl_pages) -
16609 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
16610 
16611 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
16612 				&mbox->u.mqe.un.post_sgl_pages;
16613 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
16614 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
16615 
16616 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
16617 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
16618 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
16619 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
16620 
16621 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
16622 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
16623 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
16624 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
16625 	if (!phba->sli4_hba.intr_enable)
16626 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16627 	else {
16628 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16629 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16630 	}
16631 	/* The IOCTL status is embedded in the mailbox subheader. */
16632 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
16633 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16634 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16635 	if (rc != MBX_TIMEOUT)
16636 		mempool_free(mbox, phba->mbox_mem_pool);
16637 	if (shdr_status || shdr_add_status || rc) {
16638 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16639 				"2511 POST_SGL mailbox failed with "
16640 				"status x%x add_status x%x, mbx status x%x\n",
16641 				shdr_status, shdr_add_status, rc);
16642 	}
16643 	return 0;
16644 }
16645 
16646 /**
16647  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
16648  * @phba: pointer to lpfc hba data structure.
16649  *
16650  * This routine is invoked to post rpi header templates to the
16651  * HBA consistent with the SLI-4 interface spec.  This routine
16652  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
16653  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
16654  *
16655  * Returns
16656  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
16657  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
16658  **/
16659 static uint16_t
16660 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
16661 {
16662 	unsigned long xri;
16663 
16664 	/*
16665 	 * Fetch the next logical xri.  Because this index is logical,
16666 	 * the driver starts at 0 each time.
16667 	 */
16668 	spin_lock_irq(&phba->hbalock);
16669 	xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
16670 				 phba->sli4_hba.max_cfg_param.max_xri, 0);
16671 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
16672 		spin_unlock_irq(&phba->hbalock);
16673 		return NO_XRI;
16674 	} else {
16675 		set_bit(xri, phba->sli4_hba.xri_bmask);
16676 		phba->sli4_hba.max_cfg_param.xri_used++;
16677 	}
16678 	spin_unlock_irq(&phba->hbalock);
16679 	return xri;
16680 }
16681 
16682 /**
16683  * lpfc_sli4_free_xri - Release an xri for reuse.
16684  * @phba: pointer to lpfc hba data structure.
16685  *
16686  * This routine is invoked to release an xri to the pool of
16687  * available rpis maintained by the driver.
16688  **/
16689 static void
16690 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
16691 {
16692 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
16693 		phba->sli4_hba.max_cfg_param.xri_used--;
16694 	}
16695 }
16696 
16697 /**
16698  * lpfc_sli4_free_xri - Release an xri for reuse.
16699  * @phba: pointer to lpfc hba data structure.
16700  *
16701  * This routine is invoked to release an xri to the pool of
16702  * available rpis maintained by the driver.
16703  **/
16704 void
16705 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
16706 {
16707 	spin_lock_irq(&phba->hbalock);
16708 	__lpfc_sli4_free_xri(phba, xri);
16709 	spin_unlock_irq(&phba->hbalock);
16710 }
16711 
16712 /**
16713  * lpfc_sli4_next_xritag - Get an xritag for the io
16714  * @phba: Pointer to HBA context object.
16715  *
16716  * This function gets an xritag for the iocb. If there is no unused xritag
16717  * it will return 0xffff.
16718  * The function returns the allocated xritag if successful, else returns zero.
16719  * Zero is not a valid xritag.
16720  * The caller is not required to hold any lock.
16721  **/
16722 uint16_t
16723 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
16724 {
16725 	uint16_t xri_index;
16726 
16727 	xri_index = lpfc_sli4_alloc_xri(phba);
16728 	if (xri_index == NO_XRI)
16729 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
16730 				"2004 Failed to allocate XRI.last XRITAG is %d"
16731 				" Max XRI is %d, Used XRI is %d\n",
16732 				xri_index,
16733 				phba->sli4_hba.max_cfg_param.max_xri,
16734 				phba->sli4_hba.max_cfg_param.xri_used);
16735 	return xri_index;
16736 }
16737 
16738 /**
16739  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
16740  * @phba: pointer to lpfc hba data structure.
16741  * @post_sgl_list: pointer to els sgl entry list.
16742  * @count: number of els sgl entries on the list.
16743  *
16744  * This routine is invoked to post a block of driver's sgl pages to the
16745  * HBA using non-embedded mailbox command. No Lock is held. This routine
16746  * is only called when the driver is loading and after all IO has been
16747  * stopped.
16748  **/
16749 static int
16750 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
16751 			    struct list_head *post_sgl_list,
16752 			    int post_cnt)
16753 {
16754 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
16755 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
16756 	struct sgl_page_pairs *sgl_pg_pairs;
16757 	void *viraddr;
16758 	LPFC_MBOXQ_t *mbox;
16759 	uint32_t reqlen, alloclen, pg_pairs;
16760 	uint32_t mbox_tmo;
16761 	uint16_t xritag_start = 0;
16762 	int rc = 0;
16763 	uint32_t shdr_status, shdr_add_status;
16764 	union lpfc_sli4_cfg_shdr *shdr;
16765 
16766 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
16767 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
16768 	if (reqlen > SLI4_PAGE_SIZE) {
16769 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16770 				"2559 Block sgl registration required DMA "
16771 				"size (%d) great than a page\n", reqlen);
16772 		return -ENOMEM;
16773 	}
16774 
16775 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16776 	if (!mbox)
16777 		return -ENOMEM;
16778 
16779 	/* Allocate DMA memory and set up the non-embedded mailbox command */
16780 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16781 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
16782 			 LPFC_SLI4_MBX_NEMBED);
16783 
16784 	if (alloclen < reqlen) {
16785 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16786 				"0285 Allocated DMA memory size (%d) is "
16787 				"less than the requested DMA memory "
16788 				"size (%d)\n", alloclen, reqlen);
16789 		lpfc_sli4_mbox_cmd_free(phba, mbox);
16790 		return -ENOMEM;
16791 	}
16792 	/* Set up the SGL pages in the non-embedded DMA pages */
16793 	viraddr = mbox->sge_array->addr[0];
16794 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
16795 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
16796 
16797 	pg_pairs = 0;
16798 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
16799 		/* Set up the sge entry */
16800 		sgl_pg_pairs->sgl_pg0_addr_lo =
16801 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
16802 		sgl_pg_pairs->sgl_pg0_addr_hi =
16803 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
16804 		sgl_pg_pairs->sgl_pg1_addr_lo =
16805 				cpu_to_le32(putPaddrLow(0));
16806 		sgl_pg_pairs->sgl_pg1_addr_hi =
16807 				cpu_to_le32(putPaddrHigh(0));
16808 
16809 		/* Keep the first xritag on the list */
16810 		if (pg_pairs == 0)
16811 			xritag_start = sglq_entry->sli4_xritag;
16812 		sgl_pg_pairs++;
16813 		pg_pairs++;
16814 	}
16815 
16816 	/* Complete initialization and perform endian conversion. */
16817 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
16818 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
16819 	sgl->word0 = cpu_to_le32(sgl->word0);
16820 
16821 	if (!phba->sli4_hba.intr_enable)
16822 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16823 	else {
16824 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16825 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16826 	}
16827 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
16828 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16829 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16830 	if (rc != MBX_TIMEOUT)
16831 		lpfc_sli4_mbox_cmd_free(phba, mbox);
16832 	if (shdr_status || shdr_add_status || rc) {
16833 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16834 				"2513 POST_SGL_BLOCK mailbox command failed "
16835 				"status x%x add_status x%x mbx status x%x\n",
16836 				shdr_status, shdr_add_status, rc);
16837 		rc = -ENXIO;
16838 	}
16839 	return rc;
16840 }
16841 
16842 /**
16843  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
16844  * @phba: pointer to lpfc hba data structure.
16845  * @nblist: pointer to nvme buffer list.
16846  * @count: number of scsi buffers on the list.
16847  *
16848  * This routine is invoked to post a block of @count scsi sgl pages from a
16849  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
16850  * No Lock is held.
16851  *
16852  **/
16853 static int
16854 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
16855 			    int count)
16856 {
16857 	struct lpfc_io_buf *lpfc_ncmd;
16858 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
16859 	struct sgl_page_pairs *sgl_pg_pairs;
16860 	void *viraddr;
16861 	LPFC_MBOXQ_t *mbox;
16862 	uint32_t reqlen, alloclen, pg_pairs;
16863 	uint32_t mbox_tmo;
16864 	uint16_t xritag_start = 0;
16865 	int rc = 0;
16866 	uint32_t shdr_status, shdr_add_status;
16867 	dma_addr_t pdma_phys_bpl1;
16868 	union lpfc_sli4_cfg_shdr *shdr;
16869 
16870 	/* Calculate the requested length of the dma memory */
16871 	reqlen = count * sizeof(struct sgl_page_pairs) +
16872 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
16873 	if (reqlen > SLI4_PAGE_SIZE) {
16874 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
16875 				"6118 Block sgl registration required DMA "
16876 				"size (%d) great than a page\n", reqlen);
16877 		return -ENOMEM;
16878 	}
16879 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16880 	if (!mbox) {
16881 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16882 				"6119 Failed to allocate mbox cmd memory\n");
16883 		return -ENOMEM;
16884 	}
16885 
16886 	/* Allocate DMA memory and set up the non-embedded mailbox command */
16887 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16888 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
16889 				    reqlen, LPFC_SLI4_MBX_NEMBED);
16890 
16891 	if (alloclen < reqlen) {
16892 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16893 				"6120 Allocated DMA memory size (%d) is "
16894 				"less than the requested DMA memory "
16895 				"size (%d)\n", alloclen, reqlen);
16896 		lpfc_sli4_mbox_cmd_free(phba, mbox);
16897 		return -ENOMEM;
16898 	}
16899 
16900 	/* Get the first SGE entry from the non-embedded DMA memory */
16901 	viraddr = mbox->sge_array->addr[0];
16902 
16903 	/* Set up the SGL pages in the non-embedded DMA pages */
16904 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
16905 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
16906 
16907 	pg_pairs = 0;
16908 	list_for_each_entry(lpfc_ncmd, nblist, list) {
16909 		/* Set up the sge entry */
16910 		sgl_pg_pairs->sgl_pg0_addr_lo =
16911 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
16912 		sgl_pg_pairs->sgl_pg0_addr_hi =
16913 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
16914 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
16915 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
16916 						SGL_PAGE_SIZE;
16917 		else
16918 			pdma_phys_bpl1 = 0;
16919 		sgl_pg_pairs->sgl_pg1_addr_lo =
16920 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
16921 		sgl_pg_pairs->sgl_pg1_addr_hi =
16922 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
16923 		/* Keep the first xritag on the list */
16924 		if (pg_pairs == 0)
16925 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
16926 		sgl_pg_pairs++;
16927 		pg_pairs++;
16928 	}
16929 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
16930 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
16931 	/* Perform endian conversion if necessary */
16932 	sgl->word0 = cpu_to_le32(sgl->word0);
16933 
16934 	if (!phba->sli4_hba.intr_enable) {
16935 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16936 	} else {
16937 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16938 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16939 	}
16940 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
16941 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16942 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16943 	if (rc != MBX_TIMEOUT)
16944 		lpfc_sli4_mbox_cmd_free(phba, mbox);
16945 	if (shdr_status || shdr_add_status || rc) {
16946 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16947 				"6125 POST_SGL_BLOCK mailbox command failed "
16948 				"status x%x add_status x%x mbx status x%x\n",
16949 				shdr_status, shdr_add_status, rc);
16950 		rc = -ENXIO;
16951 	}
16952 	return rc;
16953 }
16954 
16955 /**
16956  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
16957  * @phba: pointer to lpfc hba data structure.
16958  * @post_nblist: pointer to the nvme buffer list.
16959  *
16960  * This routine walks a list of nvme buffers that was passed in. It attempts
16961  * to construct blocks of nvme buffer sgls which contains contiguous xris and
16962  * uses the non-embedded SGL block post mailbox commands to post to the port.
16963  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
16964  * embedded SGL post mailbox command for posting. The @post_nblist passed in
16965  * must be local list, thus no lock is needed when manipulate the list.
16966  *
16967  * Returns: 0 = failure, non-zero number of successfully posted buffers.
16968  **/
16969 int
16970 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
16971 			   struct list_head *post_nblist, int sb_count)
16972 {
16973 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
16974 	int status, sgl_size;
16975 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
16976 	dma_addr_t pdma_phys_sgl1;
16977 	int last_xritag = NO_XRI;
16978 	int cur_xritag;
16979 	LIST_HEAD(prep_nblist);
16980 	LIST_HEAD(blck_nblist);
16981 	LIST_HEAD(nvme_nblist);
16982 
16983 	/* sanity check */
16984 	if (sb_count <= 0)
16985 		return -EINVAL;
16986 
16987 	sgl_size = phba->cfg_sg_dma_buf_size;
16988 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
16989 		list_del_init(&lpfc_ncmd->list);
16990 		block_cnt++;
16991 		if ((last_xritag != NO_XRI) &&
16992 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
16993 			/* a hole in xri block, form a sgl posting block */
16994 			list_splice_init(&prep_nblist, &blck_nblist);
16995 			post_cnt = block_cnt - 1;
16996 			/* prepare list for next posting block */
16997 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
16998 			block_cnt = 1;
16999 		} else {
17000 			/* prepare list for next posting block */
17001 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17002 			/* enough sgls for non-embed sgl mbox command */
17003 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
17004 				list_splice_init(&prep_nblist, &blck_nblist);
17005 				post_cnt = block_cnt;
17006 				block_cnt = 0;
17007 			}
17008 		}
17009 		num_posting++;
17010 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17011 
17012 		/* end of repost sgl list condition for NVME buffers */
17013 		if (num_posting == sb_count) {
17014 			if (post_cnt == 0) {
17015 				/* last sgl posting block */
17016 				list_splice_init(&prep_nblist, &blck_nblist);
17017 				post_cnt = block_cnt;
17018 			} else if (block_cnt == 1) {
17019 				/* last single sgl with non-contiguous xri */
17020 				if (sgl_size > SGL_PAGE_SIZE)
17021 					pdma_phys_sgl1 =
17022 						lpfc_ncmd->dma_phys_sgl +
17023 						SGL_PAGE_SIZE;
17024 				else
17025 					pdma_phys_sgl1 = 0;
17026 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17027 				status = lpfc_sli4_post_sgl(
17028 						phba, lpfc_ncmd->dma_phys_sgl,
17029 						pdma_phys_sgl1, cur_xritag);
17030 				if (status) {
17031 					/* Post error.  Buffer unavailable. */
17032 					lpfc_ncmd->flags |=
17033 						LPFC_SBUF_NOT_POSTED;
17034 				} else {
17035 					/* Post success. Bffer available. */
17036 					lpfc_ncmd->flags &=
17037 						~LPFC_SBUF_NOT_POSTED;
17038 					lpfc_ncmd->status = IOSTAT_SUCCESS;
17039 					num_posted++;
17040 				}
17041 				/* success, put on NVME buffer sgl list */
17042 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17043 			}
17044 		}
17045 
17046 		/* continue until a nembed page worth of sgls */
17047 		if (post_cnt == 0)
17048 			continue;
17049 
17050 		/* post block of NVME buffer list sgls */
17051 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
17052 						     post_cnt);
17053 
17054 		/* don't reset xirtag due to hole in xri block */
17055 		if (block_cnt == 0)
17056 			last_xritag = NO_XRI;
17057 
17058 		/* reset NVME buffer post count for next round of posting */
17059 		post_cnt = 0;
17060 
17061 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
17062 		while (!list_empty(&blck_nblist)) {
17063 			list_remove_head(&blck_nblist, lpfc_ncmd,
17064 					 struct lpfc_io_buf, list);
17065 			if (status) {
17066 				/* Post error.  Mark buffer unavailable. */
17067 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
17068 			} else {
17069 				/* Post success, Mark buffer available. */
17070 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
17071 				lpfc_ncmd->status = IOSTAT_SUCCESS;
17072 				num_posted++;
17073 			}
17074 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17075 		}
17076 	}
17077 	/* Push NVME buffers with sgl posted to the available list */
17078 	lpfc_io_buf_replenish(phba, &nvme_nblist);
17079 
17080 	return num_posted;
17081 }
17082 
17083 /**
17084  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
17085  * @phba: pointer to lpfc_hba struct that the frame was received on
17086  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17087  *
17088  * This function checks the fields in the @fc_hdr to see if the FC frame is a
17089  * valid type of frame that the LPFC driver will handle. This function will
17090  * return a zero if the frame is a valid frame or a non zero value when the
17091  * frame does not pass the check.
17092  **/
17093 static int
17094 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
17095 {
17096 	/*  make rctl_names static to save stack space */
17097 	struct fc_vft_header *fc_vft_hdr;
17098 	uint32_t *header = (uint32_t *) fc_hdr;
17099 
17100 #define FC_RCTL_MDS_DIAGS	0xF4
17101 
17102 	switch (fc_hdr->fh_r_ctl) {
17103 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
17104 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
17105 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
17106 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
17107 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
17108 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
17109 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
17110 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
17111 	case FC_RCTL_ELS_REQ:	/* extended link services request */
17112 	case FC_RCTL_ELS_REP:	/* extended link services reply */
17113 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
17114 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
17115 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
17116 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
17117 	case FC_RCTL_BA_RMC: 	/* remove connection */
17118 	case FC_RCTL_BA_ACC:	/* basic accept */
17119 	case FC_RCTL_BA_RJT:	/* basic reject */
17120 	case FC_RCTL_BA_PRMT:
17121 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
17122 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
17123 	case FC_RCTL_P_RJT:	/* port reject */
17124 	case FC_RCTL_F_RJT:	/* fabric reject */
17125 	case FC_RCTL_P_BSY:	/* port busy */
17126 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
17127 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
17128 	case FC_RCTL_LCR:	/* link credit reset */
17129 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
17130 	case FC_RCTL_END:	/* end */
17131 		break;
17132 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
17133 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17134 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
17135 		return lpfc_fc_frame_check(phba, fc_hdr);
17136 	default:
17137 		goto drop;
17138 	}
17139 
17140 	switch (fc_hdr->fh_type) {
17141 	case FC_TYPE_BLS:
17142 	case FC_TYPE_ELS:
17143 	case FC_TYPE_FCP:
17144 	case FC_TYPE_CT:
17145 	case FC_TYPE_NVME:
17146 		break;
17147 	case FC_TYPE_IP:
17148 	case FC_TYPE_ILS:
17149 	default:
17150 		goto drop;
17151 	}
17152 
17153 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
17154 			"2538 Received frame rctl:x%x, type:x%x, "
17155 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
17156 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
17157 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
17158 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
17159 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
17160 			be32_to_cpu(header[6]));
17161 	return 0;
17162 drop:
17163 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
17164 			"2539 Dropped frame rctl:x%x type:x%x\n",
17165 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17166 	return 1;
17167 }
17168 
17169 /**
17170  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
17171  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17172  *
17173  * This function processes the FC header to retrieve the VFI from the VF
17174  * header, if one exists. This function will return the VFI if one exists
17175  * or 0 if no VSAN Header exists.
17176  **/
17177 static uint32_t
17178 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
17179 {
17180 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17181 
17182 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
17183 		return 0;
17184 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
17185 }
17186 
17187 /**
17188  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
17189  * @phba: Pointer to the HBA structure to search for the vport on
17190  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17191  * @fcfi: The FC Fabric ID that the frame came from
17192  *
17193  * This function searches the @phba for a vport that matches the content of the
17194  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
17195  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
17196  * returns the matching vport pointer or NULL if unable to match frame to a
17197  * vport.
17198  **/
17199 static struct lpfc_vport *
17200 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
17201 		       uint16_t fcfi, uint32_t did)
17202 {
17203 	struct lpfc_vport **vports;
17204 	struct lpfc_vport *vport = NULL;
17205 	int i;
17206 
17207 	if (did == Fabric_DID)
17208 		return phba->pport;
17209 	if ((phba->pport->fc_flag & FC_PT2PT) &&
17210 		!(phba->link_state == LPFC_HBA_READY))
17211 		return phba->pport;
17212 
17213 	vports = lpfc_create_vport_work_array(phba);
17214 	if (vports != NULL) {
17215 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
17216 			if (phba->fcf.fcfi == fcfi &&
17217 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
17218 			    vports[i]->fc_myDID == did) {
17219 				vport = vports[i];
17220 				break;
17221 			}
17222 		}
17223 	}
17224 	lpfc_destroy_vport_work_array(phba, vports);
17225 	return vport;
17226 }
17227 
17228 /**
17229  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
17230  * @vport: The vport to work on.
17231  *
17232  * This function updates the receive sequence time stamp for this vport. The
17233  * receive sequence time stamp indicates the time that the last frame of the
17234  * the sequence that has been idle for the longest amount of time was received.
17235  * the driver uses this time stamp to indicate if any received sequences have
17236  * timed out.
17237  **/
17238 static void
17239 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
17240 {
17241 	struct lpfc_dmabuf *h_buf;
17242 	struct hbq_dmabuf *dmabuf = NULL;
17243 
17244 	/* get the oldest sequence on the rcv list */
17245 	h_buf = list_get_first(&vport->rcv_buffer_list,
17246 			       struct lpfc_dmabuf, list);
17247 	if (!h_buf)
17248 		return;
17249 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17250 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
17251 }
17252 
17253 /**
17254  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
17255  * @vport: The vport that the received sequences were sent to.
17256  *
17257  * This function cleans up all outstanding received sequences. This is called
17258  * by the driver when a link event or user action invalidates all the received
17259  * sequences.
17260  **/
17261 void
17262 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
17263 {
17264 	struct lpfc_dmabuf *h_buf, *hnext;
17265 	struct lpfc_dmabuf *d_buf, *dnext;
17266 	struct hbq_dmabuf *dmabuf = NULL;
17267 
17268 	/* start with the oldest sequence on the rcv list */
17269 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17270 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17271 		list_del_init(&dmabuf->hbuf.list);
17272 		list_for_each_entry_safe(d_buf, dnext,
17273 					 &dmabuf->dbuf.list, list) {
17274 			list_del_init(&d_buf->list);
17275 			lpfc_in_buf_free(vport->phba, d_buf);
17276 		}
17277 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17278 	}
17279 }
17280 
17281 /**
17282  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
17283  * @vport: The vport that the received sequences were sent to.
17284  *
17285  * This function determines whether any received sequences have timed out by
17286  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
17287  * indicates that there is at least one timed out sequence this routine will
17288  * go through the received sequences one at a time from most inactive to most
17289  * active to determine which ones need to be cleaned up. Once it has determined
17290  * that a sequence needs to be cleaned up it will simply free up the resources
17291  * without sending an abort.
17292  **/
17293 void
17294 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
17295 {
17296 	struct lpfc_dmabuf *h_buf, *hnext;
17297 	struct lpfc_dmabuf *d_buf, *dnext;
17298 	struct hbq_dmabuf *dmabuf = NULL;
17299 	unsigned long timeout;
17300 	int abort_count = 0;
17301 
17302 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17303 		   vport->rcv_buffer_time_stamp);
17304 	if (list_empty(&vport->rcv_buffer_list) ||
17305 	    time_before(jiffies, timeout))
17306 		return;
17307 	/* start with the oldest sequence on the rcv list */
17308 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17309 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17310 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17311 			   dmabuf->time_stamp);
17312 		if (time_before(jiffies, timeout))
17313 			break;
17314 		abort_count++;
17315 		list_del_init(&dmabuf->hbuf.list);
17316 		list_for_each_entry_safe(d_buf, dnext,
17317 					 &dmabuf->dbuf.list, list) {
17318 			list_del_init(&d_buf->list);
17319 			lpfc_in_buf_free(vport->phba, d_buf);
17320 		}
17321 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17322 	}
17323 	if (abort_count)
17324 		lpfc_update_rcv_time_stamp(vport);
17325 }
17326 
17327 /**
17328  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
17329  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
17330  *
17331  * This function searches through the existing incomplete sequences that have
17332  * been sent to this @vport. If the frame matches one of the incomplete
17333  * sequences then the dbuf in the @dmabuf is added to the list of frames that
17334  * make up that sequence. If no sequence is found that matches this frame then
17335  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
17336  * This function returns a pointer to the first dmabuf in the sequence list that
17337  * the frame was linked to.
17338  **/
17339 static struct hbq_dmabuf *
17340 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
17341 {
17342 	struct fc_frame_header *new_hdr;
17343 	struct fc_frame_header *temp_hdr;
17344 	struct lpfc_dmabuf *d_buf;
17345 	struct lpfc_dmabuf *h_buf;
17346 	struct hbq_dmabuf *seq_dmabuf = NULL;
17347 	struct hbq_dmabuf *temp_dmabuf = NULL;
17348 	uint8_t	found = 0;
17349 
17350 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
17351 	dmabuf->time_stamp = jiffies;
17352 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17353 
17354 	/* Use the hdr_buf to find the sequence that this frame belongs to */
17355 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
17356 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
17357 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
17358 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
17359 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
17360 			continue;
17361 		/* found a pending sequence that matches this frame */
17362 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17363 		break;
17364 	}
17365 	if (!seq_dmabuf) {
17366 		/*
17367 		 * This indicates first frame received for this sequence.
17368 		 * Queue the buffer on the vport's rcv_buffer_list.
17369 		 */
17370 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17371 		lpfc_update_rcv_time_stamp(vport);
17372 		return dmabuf;
17373 	}
17374 	temp_hdr = seq_dmabuf->hbuf.virt;
17375 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
17376 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17377 		list_del_init(&seq_dmabuf->hbuf.list);
17378 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17379 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17380 		lpfc_update_rcv_time_stamp(vport);
17381 		return dmabuf;
17382 	}
17383 	/* move this sequence to the tail to indicate a young sequence */
17384 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
17385 	seq_dmabuf->time_stamp = jiffies;
17386 	lpfc_update_rcv_time_stamp(vport);
17387 	if (list_empty(&seq_dmabuf->dbuf.list)) {
17388 		temp_hdr = dmabuf->hbuf.virt;
17389 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17390 		return seq_dmabuf;
17391 	}
17392 	/* find the correct place in the sequence to insert this frame */
17393 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
17394 	while (!found) {
17395 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17396 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
17397 		/*
17398 		 * If the frame's sequence count is greater than the frame on
17399 		 * the list then insert the frame right after this frame
17400 		 */
17401 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
17402 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17403 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
17404 			found = 1;
17405 			break;
17406 		}
17407 
17408 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
17409 			break;
17410 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
17411 	}
17412 
17413 	if (found)
17414 		return seq_dmabuf;
17415 	return NULL;
17416 }
17417 
17418 /**
17419  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
17420  * @vport: pointer to a vitural port
17421  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17422  *
17423  * This function tries to abort from the partially assembed sequence, described
17424  * by the information from basic abbort @dmabuf. It checks to see whether such
17425  * partially assembled sequence held by the driver. If so, it shall free up all
17426  * the frames from the partially assembled sequence.
17427  *
17428  * Return
17429  * true  -- if there is matching partially assembled sequence present and all
17430  *          the frames freed with the sequence;
17431  * false -- if there is no matching partially assembled sequence present so
17432  *          nothing got aborted in the lower layer driver
17433  **/
17434 static bool
17435 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
17436 			    struct hbq_dmabuf *dmabuf)
17437 {
17438 	struct fc_frame_header *new_hdr;
17439 	struct fc_frame_header *temp_hdr;
17440 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
17441 	struct hbq_dmabuf *seq_dmabuf = NULL;
17442 
17443 	/* Use the hdr_buf to find the sequence that matches this frame */
17444 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
17445 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
17446 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17447 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
17448 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
17449 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
17450 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
17451 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
17452 			continue;
17453 		/* found a pending sequence that matches this frame */
17454 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17455 		break;
17456 	}
17457 
17458 	/* Free up all the frames from the partially assembled sequence */
17459 	if (seq_dmabuf) {
17460 		list_for_each_entry_safe(d_buf, n_buf,
17461 					 &seq_dmabuf->dbuf.list, list) {
17462 			list_del_init(&d_buf->list);
17463 			lpfc_in_buf_free(vport->phba, d_buf);
17464 		}
17465 		return true;
17466 	}
17467 	return false;
17468 }
17469 
17470 /**
17471  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
17472  * @vport: pointer to a vitural port
17473  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17474  *
17475  * This function tries to abort from the assembed sequence from upper level
17476  * protocol, described by the information from basic abbort @dmabuf. It
17477  * checks to see whether such pending context exists at upper level protocol.
17478  * If so, it shall clean up the pending context.
17479  *
17480  * Return
17481  * true  -- if there is matching pending context of the sequence cleaned
17482  *          at ulp;
17483  * false -- if there is no matching pending context of the sequence present
17484  *          at ulp.
17485  **/
17486 static bool
17487 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
17488 {
17489 	struct lpfc_hba *phba = vport->phba;
17490 	int handled;
17491 
17492 	/* Accepting abort at ulp with SLI4 only */
17493 	if (phba->sli_rev < LPFC_SLI_REV4)
17494 		return false;
17495 
17496 	/* Register all caring upper level protocols to attend abort */
17497 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
17498 	if (handled)
17499 		return true;
17500 
17501 	return false;
17502 }
17503 
17504 /**
17505  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
17506  * @phba: Pointer to HBA context object.
17507  * @cmd_iocbq: pointer to the command iocbq structure.
17508  * @rsp_iocbq: pointer to the response iocbq structure.
17509  *
17510  * This function handles the sequence abort response iocb command complete
17511  * event. It properly releases the memory allocated to the sequence abort
17512  * accept iocb.
17513  **/
17514 static void
17515 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
17516 			     struct lpfc_iocbq *cmd_iocbq,
17517 			     struct lpfc_iocbq *rsp_iocbq)
17518 {
17519 	struct lpfc_nodelist *ndlp;
17520 
17521 	if (cmd_iocbq) {
17522 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
17523 		lpfc_nlp_put(ndlp);
17524 		lpfc_nlp_not_used(ndlp);
17525 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
17526 	}
17527 
17528 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
17529 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
17530 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17531 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
17532 			rsp_iocbq->iocb.ulpStatus,
17533 			rsp_iocbq->iocb.un.ulpWord[4]);
17534 }
17535 
17536 /**
17537  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
17538  * @phba: Pointer to HBA context object.
17539  * @xri: xri id in transaction.
17540  *
17541  * This function validates the xri maps to the known range of XRIs allocated an
17542  * used by the driver.
17543  **/
17544 uint16_t
17545 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
17546 		      uint16_t xri)
17547 {
17548 	uint16_t i;
17549 
17550 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
17551 		if (xri == phba->sli4_hba.xri_ids[i])
17552 			return i;
17553 	}
17554 	return NO_XRI;
17555 }
17556 
17557 /**
17558  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
17559  * @phba: Pointer to HBA context object.
17560  * @fc_hdr: pointer to a FC frame header.
17561  *
17562  * This function sends a basic response to a previous unsol sequence abort
17563  * event after aborting the sequence handling.
17564  **/
17565 void
17566 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
17567 			struct fc_frame_header *fc_hdr, bool aborted)
17568 {
17569 	struct lpfc_hba *phba = vport->phba;
17570 	struct lpfc_iocbq *ctiocb = NULL;
17571 	struct lpfc_nodelist *ndlp;
17572 	uint16_t oxid, rxid, xri, lxri;
17573 	uint32_t sid, fctl;
17574 	IOCB_t *icmd;
17575 	int rc;
17576 
17577 	if (!lpfc_is_link_up(phba))
17578 		return;
17579 
17580 	sid = sli4_sid_from_fc_hdr(fc_hdr);
17581 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
17582 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
17583 
17584 	ndlp = lpfc_findnode_did(vport, sid);
17585 	if (!ndlp) {
17586 		ndlp = lpfc_nlp_init(vport, sid);
17587 		if (!ndlp) {
17588 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
17589 					 "1268 Failed to allocate ndlp for "
17590 					 "oxid:x%x SID:x%x\n", oxid, sid);
17591 			return;
17592 		}
17593 		/* Put ndlp onto pport node list */
17594 		lpfc_enqueue_node(vport, ndlp);
17595 	} else if (!NLP_CHK_NODE_ACT(ndlp)) {
17596 		/* re-setup ndlp without removing from node list */
17597 		ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
17598 		if (!ndlp) {
17599 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
17600 					 "3275 Failed to active ndlp found "
17601 					 "for oxid:x%x SID:x%x\n", oxid, sid);
17602 			return;
17603 		}
17604 	}
17605 
17606 	/* Allocate buffer for rsp iocb */
17607 	ctiocb = lpfc_sli_get_iocbq(phba);
17608 	if (!ctiocb)
17609 		return;
17610 
17611 	/* Extract the F_CTL field from FC_HDR */
17612 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
17613 
17614 	icmd = &ctiocb->iocb;
17615 	icmd->un.xseq64.bdl.bdeSize = 0;
17616 	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
17617 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
17618 	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
17619 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
17620 
17621 	/* Fill in the rest of iocb fields */
17622 	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
17623 	icmd->ulpBdeCount = 0;
17624 	icmd->ulpLe = 1;
17625 	icmd->ulpClass = CLASS3;
17626 	icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
17627 	ctiocb->context1 = lpfc_nlp_get(ndlp);
17628 
17629 	ctiocb->vport = phba->pport;
17630 	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
17631 	ctiocb->sli4_lxritag = NO_XRI;
17632 	ctiocb->sli4_xritag = NO_XRI;
17633 
17634 	if (fctl & FC_FC_EX_CTX)
17635 		/* Exchange responder sent the abort so we
17636 		 * own the oxid.
17637 		 */
17638 		xri = oxid;
17639 	else
17640 		xri = rxid;
17641 	lxri = lpfc_sli4_xri_inrange(phba, xri);
17642 	if (lxri != NO_XRI)
17643 		lpfc_set_rrq_active(phba, ndlp, lxri,
17644 			(xri == oxid) ? rxid : oxid, 0);
17645 	/* For BA_ABTS from exchange responder, if the logical xri with
17646 	 * the oxid maps to the FCP XRI range, the port no longer has
17647 	 * that exchange context, send a BLS_RJT. Override the IOCB for
17648 	 * a BA_RJT.
17649 	 */
17650 	if ((fctl & FC_FC_EX_CTX) &&
17651 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
17652 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
17653 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
17654 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
17655 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
17656 	}
17657 
17658 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
17659 	 * the driver no longer has that exchange, send a BLS_RJT. Override
17660 	 * the IOCB for a BA_RJT.
17661 	 */
17662 	if (aborted == false) {
17663 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
17664 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
17665 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
17666 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
17667 	}
17668 
17669 	if (fctl & FC_FC_EX_CTX) {
17670 		/* ABTS sent by responder to CT exchange, construction
17671 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
17672 		 * field and RX_ID from ABTS for RX_ID field.
17673 		 */
17674 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
17675 	} else {
17676 		/* ABTS sent by initiator to CT exchange, construction
17677 		 * of BA_ACC will need to allocate a new XRI as for the
17678 		 * XRI_TAG field.
17679 		 */
17680 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
17681 	}
17682 	bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
17683 	bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
17684 
17685 	/* Xmit CT abts response on exchange <xid> */
17686 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
17687 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
17688 			 icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
17689 
17690 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
17691 	if (rc == IOCB_ERROR) {
17692 		lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
17693 				 "2925 Failed to issue CT ABTS RSP x%x on "
17694 				 "xri x%x, Data x%x\n",
17695 				 icmd->un.xseq64.w5.hcsw.Rctl, oxid,
17696 				 phba->link_state);
17697 		lpfc_nlp_put(ndlp);
17698 		ctiocb->context1 = NULL;
17699 		lpfc_sli_release_iocbq(phba, ctiocb);
17700 	}
17701 }
17702 
17703 /**
17704  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
17705  * @vport: Pointer to the vport on which this sequence was received
17706  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17707  *
17708  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
17709  * receive sequence is only partially assembed by the driver, it shall abort
17710  * the partially assembled frames for the sequence. Otherwise, if the
17711  * unsolicited receive sequence has been completely assembled and passed to
17712  * the Upper Layer Protocol (UPL), it then mark the per oxid status for the
17713  * unsolicited sequence has been aborted. After that, it will issue a basic
17714  * accept to accept the abort.
17715  **/
17716 static void
17717 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
17718 			     struct hbq_dmabuf *dmabuf)
17719 {
17720 	struct lpfc_hba *phba = vport->phba;
17721 	struct fc_frame_header fc_hdr;
17722 	uint32_t fctl;
17723 	bool aborted;
17724 
17725 	/* Make a copy of fc_hdr before the dmabuf being released */
17726 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
17727 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
17728 
17729 	if (fctl & FC_FC_EX_CTX) {
17730 		/* ABTS by responder to exchange, no cleanup needed */
17731 		aborted = true;
17732 	} else {
17733 		/* ABTS by initiator to exchange, need to do cleanup */
17734 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
17735 		if (aborted == false)
17736 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
17737 	}
17738 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
17739 
17740 	if (phba->nvmet_support) {
17741 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
17742 		return;
17743 	}
17744 
17745 	/* Respond with BA_ACC or BA_RJT accordingly */
17746 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
17747 }
17748 
17749 /**
17750  * lpfc_seq_complete - Indicates if a sequence is complete
17751  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17752  *
17753  * This function checks the sequence, starting with the frame described by
17754  * @dmabuf, to see if all the frames associated with this sequence are present.
17755  * the frames associated with this sequence are linked to the @dmabuf using the
17756  * dbuf list. This function looks for two major things. 1) That the first frame
17757  * has a sequence count of zero. 2) There is a frame with last frame of sequence
17758  * set. 3) That there are no holes in the sequence count. The function will
17759  * return 1 when the sequence is complete, otherwise it will return 0.
17760  **/
17761 static int
17762 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
17763 {
17764 	struct fc_frame_header *hdr;
17765 	struct lpfc_dmabuf *d_buf;
17766 	struct hbq_dmabuf *seq_dmabuf;
17767 	uint32_t fctl;
17768 	int seq_count = 0;
17769 
17770 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17771 	/* make sure first fame of sequence has a sequence count of zero */
17772 	if (hdr->fh_seq_cnt != seq_count)
17773 		return 0;
17774 	fctl = (hdr->fh_f_ctl[0] << 16 |
17775 		hdr->fh_f_ctl[1] << 8 |
17776 		hdr->fh_f_ctl[2]);
17777 	/* If last frame of sequence we can return success. */
17778 	if (fctl & FC_FC_END_SEQ)
17779 		return 1;
17780 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
17781 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17782 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
17783 		/* If there is a hole in the sequence count then fail. */
17784 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
17785 			return 0;
17786 		fctl = (hdr->fh_f_ctl[0] << 16 |
17787 			hdr->fh_f_ctl[1] << 8 |
17788 			hdr->fh_f_ctl[2]);
17789 		/* If last frame of sequence we can return success. */
17790 		if (fctl & FC_FC_END_SEQ)
17791 			return 1;
17792 	}
17793 	return 0;
17794 }
17795 
17796 /**
17797  * lpfc_prep_seq - Prep sequence for ULP processing
17798  * @vport: Pointer to the vport on which this sequence was received
17799  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17800  *
17801  * This function takes a sequence, described by a list of frames, and creates
17802  * a list of iocbq structures to describe the sequence. This iocbq list will be
17803  * used to issue to the generic unsolicited sequence handler. This routine
17804  * returns a pointer to the first iocbq in the list. If the function is unable
17805  * to allocate an iocbq then it throw out the received frames that were not
17806  * able to be described and return a pointer to the first iocbq. If unable to
17807  * allocate any iocbqs (including the first) this function will return NULL.
17808  **/
17809 static struct lpfc_iocbq *
17810 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
17811 {
17812 	struct hbq_dmabuf *hbq_buf;
17813 	struct lpfc_dmabuf *d_buf, *n_buf;
17814 	struct lpfc_iocbq *first_iocbq, *iocbq;
17815 	struct fc_frame_header *fc_hdr;
17816 	uint32_t sid;
17817 	uint32_t len, tot_len;
17818 	struct ulp_bde64 *pbde;
17819 
17820 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
17821 	/* remove from receive buffer list */
17822 	list_del_init(&seq_dmabuf->hbuf.list);
17823 	lpfc_update_rcv_time_stamp(vport);
17824 	/* get the Remote Port's SID */
17825 	sid = sli4_sid_from_fc_hdr(fc_hdr);
17826 	tot_len = 0;
17827 	/* Get an iocbq struct to fill in. */
17828 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
17829 	if (first_iocbq) {
17830 		/* Initialize the first IOCB. */
17831 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
17832 		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
17833 		first_iocbq->vport = vport;
17834 
17835 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
17836 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
17837 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
17838 			first_iocbq->iocb.un.rcvels.parmRo =
17839 				sli4_did_from_fc_hdr(fc_hdr);
17840 			first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
17841 		} else
17842 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
17843 		first_iocbq->iocb.ulpContext = NO_XRI;
17844 		first_iocbq->iocb.unsli3.rcvsli3.ox_id =
17845 			be16_to_cpu(fc_hdr->fh_ox_id);
17846 		/* iocbq is prepped for internal consumption.  Physical vpi. */
17847 		first_iocbq->iocb.unsli3.rcvsli3.vpi =
17848 			vport->phba->vpi_ids[vport->vpi];
17849 		/* put the first buffer into the first IOCBq */
17850 		tot_len = bf_get(lpfc_rcqe_length,
17851 				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
17852 
17853 		first_iocbq->context2 = &seq_dmabuf->dbuf;
17854 		first_iocbq->context3 = NULL;
17855 		first_iocbq->iocb.ulpBdeCount = 1;
17856 		if (tot_len > LPFC_DATA_BUF_SIZE)
17857 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
17858 							LPFC_DATA_BUF_SIZE;
17859 		else
17860 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
17861 
17862 		first_iocbq->iocb.un.rcvels.remoteID = sid;
17863 
17864 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
17865 	}
17866 	iocbq = first_iocbq;
17867 	/*
17868 	 * Each IOCBq can have two Buffers assigned, so go through the list
17869 	 * of buffers for this sequence and save two buffers in each IOCBq
17870 	 */
17871 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
17872 		if (!iocbq) {
17873 			lpfc_in_buf_free(vport->phba, d_buf);
17874 			continue;
17875 		}
17876 		if (!iocbq->context3) {
17877 			iocbq->context3 = d_buf;
17878 			iocbq->iocb.ulpBdeCount++;
17879 			/* We need to get the size out of the right CQE */
17880 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17881 			len = bf_get(lpfc_rcqe_length,
17882 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
17883 			pbde = (struct ulp_bde64 *)
17884 					&iocbq->iocb.unsli3.sli3Words[4];
17885 			if (len > LPFC_DATA_BUF_SIZE)
17886 				pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
17887 			else
17888 				pbde->tus.f.bdeSize = len;
17889 
17890 			iocbq->iocb.unsli3.rcvsli3.acc_len += len;
17891 			tot_len += len;
17892 		} else {
17893 			iocbq = lpfc_sli_get_iocbq(vport->phba);
17894 			if (!iocbq) {
17895 				if (first_iocbq) {
17896 					first_iocbq->iocb.ulpStatus =
17897 							IOSTAT_FCP_RSP_ERROR;
17898 					first_iocbq->iocb.un.ulpWord[4] =
17899 							IOERR_NO_RESOURCES;
17900 				}
17901 				lpfc_in_buf_free(vport->phba, d_buf);
17902 				continue;
17903 			}
17904 			/* We need to get the size out of the right CQE */
17905 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17906 			len = bf_get(lpfc_rcqe_length,
17907 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
17908 			iocbq->context2 = d_buf;
17909 			iocbq->context3 = NULL;
17910 			iocbq->iocb.ulpBdeCount = 1;
17911 			if (len > LPFC_DATA_BUF_SIZE)
17912 				iocbq->iocb.un.cont64[0].tus.f.bdeSize =
17913 							LPFC_DATA_BUF_SIZE;
17914 			else
17915 				iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
17916 
17917 			tot_len += len;
17918 			iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
17919 
17920 			iocbq->iocb.un.rcvels.remoteID = sid;
17921 			list_add_tail(&iocbq->list, &first_iocbq->list);
17922 		}
17923 	}
17924 	/* Free the sequence's header buffer */
17925 	if (!first_iocbq)
17926 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
17927 
17928 	return first_iocbq;
17929 }
17930 
17931 static void
17932 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
17933 			  struct hbq_dmabuf *seq_dmabuf)
17934 {
17935 	struct fc_frame_header *fc_hdr;
17936 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
17937 	struct lpfc_hba *phba = vport->phba;
17938 
17939 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
17940 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
17941 	if (!iocbq) {
17942 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17943 				"2707 Ring %d handler: Failed to allocate "
17944 				"iocb Rctl x%x Type x%x received\n",
17945 				LPFC_ELS_RING,
17946 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17947 		return;
17948 	}
17949 	if (!lpfc_complete_unsol_iocb(phba,
17950 				      phba->sli4_hba.els_wq->pring,
17951 				      iocbq, fc_hdr->fh_r_ctl,
17952 				      fc_hdr->fh_type))
17953 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17954 				"2540 Ring %d handler: unexpected Rctl "
17955 				"x%x Type x%x received\n",
17956 				LPFC_ELS_RING,
17957 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17958 
17959 	/* Free iocb created in lpfc_prep_seq */
17960 	list_for_each_entry_safe(curr_iocb, next_iocb,
17961 		&iocbq->list, list) {
17962 		list_del_init(&curr_iocb->list);
17963 		lpfc_sli_release_iocbq(phba, curr_iocb);
17964 	}
17965 	lpfc_sli_release_iocbq(phba, iocbq);
17966 }
17967 
17968 static void
17969 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
17970 			    struct lpfc_iocbq *rspiocb)
17971 {
17972 	struct lpfc_dmabuf *pcmd = cmdiocb->context2;
17973 
17974 	if (pcmd && pcmd->virt)
17975 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
17976 	kfree(pcmd);
17977 	lpfc_sli_release_iocbq(phba, cmdiocb);
17978 	lpfc_drain_txq(phba);
17979 }
17980 
17981 static void
17982 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
17983 			      struct hbq_dmabuf *dmabuf)
17984 {
17985 	struct fc_frame_header *fc_hdr;
17986 	struct lpfc_hba *phba = vport->phba;
17987 	struct lpfc_iocbq *iocbq = NULL;
17988 	union  lpfc_wqe *wqe;
17989 	struct lpfc_dmabuf *pcmd = NULL;
17990 	uint32_t frame_len;
17991 	int rc;
17992 	unsigned long iflags;
17993 
17994 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17995 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
17996 
17997 	/* Send the received frame back */
17998 	iocbq = lpfc_sli_get_iocbq(phba);
17999 	if (!iocbq) {
18000 		/* Queue cq event and wakeup worker thread to process it */
18001 		spin_lock_irqsave(&phba->hbalock, iflags);
18002 		list_add_tail(&dmabuf->cq_event.list,
18003 			      &phba->sli4_hba.sp_queue_event);
18004 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
18005 		spin_unlock_irqrestore(&phba->hbalock, iflags);
18006 		lpfc_worker_wake_up(phba);
18007 		return;
18008 	}
18009 
18010 	/* Allocate buffer for command payload */
18011 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
18012 	if (pcmd)
18013 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
18014 					    &pcmd->phys);
18015 	if (!pcmd || !pcmd->virt)
18016 		goto exit;
18017 
18018 	INIT_LIST_HEAD(&pcmd->list);
18019 
18020 	/* copyin the payload */
18021 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
18022 
18023 	/* fill in BDE's for command */
18024 	iocbq->iocb.un.xseq64.bdl.addrHigh = putPaddrHigh(pcmd->phys);
18025 	iocbq->iocb.un.xseq64.bdl.addrLow = putPaddrLow(pcmd->phys);
18026 	iocbq->iocb.un.xseq64.bdl.bdeFlags = BUFF_TYPE_BDE_64;
18027 	iocbq->iocb.un.xseq64.bdl.bdeSize = frame_len;
18028 
18029 	iocbq->context2 = pcmd;
18030 	iocbq->vport = vport;
18031 	iocbq->iocb_flag &= ~LPFC_FIP_ELS_ID_MASK;
18032 	iocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
18033 
18034 	/*
18035 	 * Setup rest of the iocb as though it were a WQE
18036 	 * Build the SEND_FRAME WQE
18037 	 */
18038 	wqe = (union lpfc_wqe *)&iocbq->iocb;
18039 
18040 	wqe->send_frame.frame_len = frame_len;
18041 	wqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((uint32_t *)fc_hdr));
18042 	wqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((uint32_t *)fc_hdr + 1));
18043 	wqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((uint32_t *)fc_hdr + 2));
18044 	wqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((uint32_t *)fc_hdr + 3));
18045 	wqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((uint32_t *)fc_hdr + 4));
18046 	wqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((uint32_t *)fc_hdr + 5));
18047 
18048 	iocbq->iocb.ulpCommand = CMD_SEND_FRAME;
18049 	iocbq->iocb.ulpLe = 1;
18050 	iocbq->iocb_cmpl = lpfc_sli4_mds_loopback_cmpl;
18051 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
18052 	if (rc == IOCB_ERROR)
18053 		goto exit;
18054 
18055 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18056 	return;
18057 
18058 exit:
18059 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18060 			"2023 Unable to process MDS loopback frame\n");
18061 	if (pcmd && pcmd->virt)
18062 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18063 	kfree(pcmd);
18064 	if (iocbq)
18065 		lpfc_sli_release_iocbq(phba, iocbq);
18066 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18067 }
18068 
18069 /**
18070  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
18071  * @phba: Pointer to HBA context object.
18072  *
18073  * This function is called with no lock held. This function processes all
18074  * the received buffers and gives it to upper layers when a received buffer
18075  * indicates that it is the final frame in the sequence. The interrupt
18076  * service routine processes received buffers at interrupt contexts.
18077  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
18078  * appropriate receive function when the final frame in a sequence is received.
18079  **/
18080 void
18081 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
18082 				 struct hbq_dmabuf *dmabuf)
18083 {
18084 	struct hbq_dmabuf *seq_dmabuf;
18085 	struct fc_frame_header *fc_hdr;
18086 	struct lpfc_vport *vport;
18087 	uint32_t fcfi;
18088 	uint32_t did;
18089 
18090 	/* Process each received buffer */
18091 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18092 
18093 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
18094 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
18095 		vport = phba->pport;
18096 		/* Handle MDS Loopback frames */
18097 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18098 		return;
18099 	}
18100 
18101 	/* check to see if this a valid type of frame */
18102 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
18103 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18104 		return;
18105 	}
18106 
18107 	if ((bf_get(lpfc_cqe_code,
18108 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
18109 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
18110 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
18111 	else
18112 		fcfi = bf_get(lpfc_rcqe_fcf_id,
18113 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
18114 
18115 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
18116 		vport = phba->pport;
18117 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
18118 				"2023 MDS Loopback %d bytes\n",
18119 				bf_get(lpfc_rcqe_length,
18120 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
18121 		/* Handle MDS Loopback frames */
18122 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18123 		return;
18124 	}
18125 
18126 	/* d_id this frame is directed to */
18127 	did = sli4_did_from_fc_hdr(fc_hdr);
18128 
18129 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
18130 	if (!vport) {
18131 		/* throw out the frame */
18132 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18133 		return;
18134 	}
18135 
18136 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
18137 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
18138 		(did != Fabric_DID)) {
18139 		/*
18140 		 * Throw out the frame if we are not pt2pt.
18141 		 * The pt2pt protocol allows for discovery frames
18142 		 * to be received without a registered VPI.
18143 		 */
18144 		if (!(vport->fc_flag & FC_PT2PT) ||
18145 			(phba->link_state == LPFC_HBA_READY)) {
18146 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
18147 			return;
18148 		}
18149 	}
18150 
18151 	/* Handle the basic abort sequence (BA_ABTS) event */
18152 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
18153 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
18154 		return;
18155 	}
18156 
18157 	/* Link this frame */
18158 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
18159 	if (!seq_dmabuf) {
18160 		/* unable to add frame to vport - throw it out */
18161 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18162 		return;
18163 	}
18164 	/* If not last frame in sequence continue processing frames. */
18165 	if (!lpfc_seq_complete(seq_dmabuf))
18166 		return;
18167 
18168 	/* Send the complete sequence to the upper layer protocol */
18169 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
18170 }
18171 
18172 /**
18173  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
18174  * @phba: pointer to lpfc hba data structure.
18175  *
18176  * This routine is invoked to post rpi header templates to the
18177  * HBA consistent with the SLI-4 interface spec.  This routine
18178  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18179  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18180  *
18181  * This routine does not require any locks.  It's usage is expected
18182  * to be driver load or reset recovery when the driver is
18183  * sequential.
18184  *
18185  * Return codes
18186  * 	0 - successful
18187  *      -EIO - The mailbox failed to complete successfully.
18188  * 	When this error occurs, the driver is not guaranteed
18189  *	to have any rpi regions posted to the device and
18190  *	must either attempt to repost the regions or take a
18191  *	fatal error.
18192  **/
18193 int
18194 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
18195 {
18196 	struct lpfc_rpi_hdr *rpi_page;
18197 	uint32_t rc = 0;
18198 	uint16_t lrpi = 0;
18199 
18200 	/* SLI4 ports that support extents do not require RPI headers. */
18201 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18202 		goto exit;
18203 	if (phba->sli4_hba.extents_in_use)
18204 		return -EIO;
18205 
18206 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
18207 		/*
18208 		 * Assign the rpi headers a physical rpi only if the driver
18209 		 * has not initialized those resources.  A port reset only
18210 		 * needs the headers posted.
18211 		 */
18212 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
18213 		    LPFC_RPI_RSRC_RDY)
18214 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18215 
18216 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
18217 		if (rc != MBX_SUCCESS) {
18218 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18219 					"2008 Error %d posting all rpi "
18220 					"headers\n", rc);
18221 			rc = -EIO;
18222 			break;
18223 		}
18224 	}
18225 
18226  exit:
18227 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
18228 	       LPFC_RPI_RSRC_RDY);
18229 	return rc;
18230 }
18231 
18232 /**
18233  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
18234  * @phba: pointer to lpfc hba data structure.
18235  * @rpi_page:  pointer to the rpi memory region.
18236  *
18237  * This routine is invoked to post a single rpi header to the
18238  * HBA consistent with the SLI-4 interface spec.  This memory region
18239  * maps up to 64 rpi context regions.
18240  *
18241  * Return codes
18242  * 	0 - successful
18243  * 	-ENOMEM - No available memory
18244  *      -EIO - The mailbox failed to complete successfully.
18245  **/
18246 int
18247 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
18248 {
18249 	LPFC_MBOXQ_t *mboxq;
18250 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
18251 	uint32_t rc = 0;
18252 	uint32_t shdr_status, shdr_add_status;
18253 	union lpfc_sli4_cfg_shdr *shdr;
18254 
18255 	/* SLI4 ports that support extents do not require RPI headers. */
18256 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18257 		return rc;
18258 	if (phba->sli4_hba.extents_in_use)
18259 		return -EIO;
18260 
18261 	/* The port is notified of the header region via a mailbox command. */
18262 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18263 	if (!mboxq) {
18264 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18265 				"2001 Unable to allocate memory for issuing "
18266 				"SLI_CONFIG_SPECIAL mailbox command\n");
18267 		return -ENOMEM;
18268 	}
18269 
18270 	/* Post all rpi memory regions to the port. */
18271 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
18272 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
18273 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
18274 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
18275 			 sizeof(struct lpfc_sli4_cfg_mhdr),
18276 			 LPFC_SLI4_MBX_EMBED);
18277 
18278 
18279 	/* Post the physical rpi to the port for this rpi header. */
18280 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
18281 	       rpi_page->start_rpi);
18282 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
18283 	       hdr_tmpl, rpi_page->page_count);
18284 
18285 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
18286 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
18287 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
18288 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
18289 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18290 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18291 	if (rc != MBX_TIMEOUT)
18292 		mempool_free(mboxq, phba->mbox_mem_pool);
18293 	if (shdr_status || shdr_add_status || rc) {
18294 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18295 				"2514 POST_RPI_HDR mailbox failed with "
18296 				"status x%x add_status x%x, mbx status x%x\n",
18297 				shdr_status, shdr_add_status, rc);
18298 		rc = -ENXIO;
18299 	} else {
18300 		/*
18301 		 * The next_rpi stores the next logical module-64 rpi value used
18302 		 * to post physical rpis in subsequent rpi postings.
18303 		 */
18304 		spin_lock_irq(&phba->hbalock);
18305 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
18306 		spin_unlock_irq(&phba->hbalock);
18307 	}
18308 	return rc;
18309 }
18310 
18311 /**
18312  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
18313  * @phba: pointer to lpfc hba data structure.
18314  *
18315  * This routine is invoked to post rpi header templates to the
18316  * HBA consistent with the SLI-4 interface spec.  This routine
18317  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18318  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18319  *
18320  * Returns
18321  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
18322  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
18323  **/
18324 int
18325 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
18326 {
18327 	unsigned long rpi;
18328 	uint16_t max_rpi, rpi_limit;
18329 	uint16_t rpi_remaining, lrpi = 0;
18330 	struct lpfc_rpi_hdr *rpi_hdr;
18331 	unsigned long iflag;
18332 
18333 	/*
18334 	 * Fetch the next logical rpi.  Because this index is logical,
18335 	 * the  driver starts at 0 each time.
18336 	 */
18337 	spin_lock_irqsave(&phba->hbalock, iflag);
18338 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
18339 	rpi_limit = phba->sli4_hba.next_rpi;
18340 
18341 	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
18342 	if (rpi >= rpi_limit)
18343 		rpi = LPFC_RPI_ALLOC_ERROR;
18344 	else {
18345 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
18346 		phba->sli4_hba.max_cfg_param.rpi_used++;
18347 		phba->sli4_hba.rpi_count++;
18348 	}
18349 	lpfc_printf_log(phba, KERN_INFO,
18350 			LOG_NODE | LOG_DISCOVERY,
18351 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
18352 			(int) rpi, max_rpi, rpi_limit);
18353 
18354 	/*
18355 	 * Don't try to allocate more rpi header regions if the device limit
18356 	 * has been exhausted.
18357 	 */
18358 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
18359 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
18360 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18361 		return rpi;
18362 	}
18363 
18364 	/*
18365 	 * RPI header postings are not required for SLI4 ports capable of
18366 	 * extents.
18367 	 */
18368 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
18369 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18370 		return rpi;
18371 	}
18372 
18373 	/*
18374 	 * If the driver is running low on rpi resources, allocate another
18375 	 * page now.  Note that the next_rpi value is used because
18376 	 * it represents how many are actually in use whereas max_rpi notes
18377 	 * how many are supported max by the device.
18378 	 */
18379 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
18380 	spin_unlock_irqrestore(&phba->hbalock, iflag);
18381 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
18382 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
18383 		if (!rpi_hdr) {
18384 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18385 					"2002 Error Could not grow rpi "
18386 					"count\n");
18387 		} else {
18388 			lrpi = rpi_hdr->start_rpi;
18389 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18390 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
18391 		}
18392 	}
18393 
18394 	return rpi;
18395 }
18396 
18397 /**
18398  * lpfc_sli4_free_rpi - Release an rpi for reuse.
18399  * @phba: pointer to lpfc hba data structure.
18400  *
18401  * This routine is invoked to release an rpi to the pool of
18402  * available rpis maintained by the driver.
18403  **/
18404 static void
18405 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
18406 {
18407 	/*
18408 	 * if the rpi value indicates a prior unreg has already
18409 	 * been done, skip the unreg.
18410 	 */
18411 	if (rpi == LPFC_RPI_ALLOC_ERROR)
18412 		return;
18413 
18414 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
18415 		phba->sli4_hba.rpi_count--;
18416 		phba->sli4_hba.max_cfg_param.rpi_used--;
18417 	} else {
18418 		lpfc_printf_log(phba, KERN_INFO,
18419 				LOG_NODE | LOG_DISCOVERY,
18420 				"2016 rpi %x not inuse\n",
18421 				rpi);
18422 	}
18423 }
18424 
18425 /**
18426  * lpfc_sli4_free_rpi - Release an rpi for reuse.
18427  * @phba: pointer to lpfc hba data structure.
18428  *
18429  * This routine is invoked to release an rpi to the pool of
18430  * available rpis maintained by the driver.
18431  **/
18432 void
18433 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
18434 {
18435 	spin_lock_irq(&phba->hbalock);
18436 	__lpfc_sli4_free_rpi(phba, rpi);
18437 	spin_unlock_irq(&phba->hbalock);
18438 }
18439 
18440 /**
18441  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
18442  * @phba: pointer to lpfc hba data structure.
18443  *
18444  * This routine is invoked to remove the memory region that
18445  * provided rpi via a bitmask.
18446  **/
18447 void
18448 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
18449 {
18450 	kfree(phba->sli4_hba.rpi_bmask);
18451 	kfree(phba->sli4_hba.rpi_ids);
18452 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
18453 }
18454 
18455 /**
18456  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
18457  * @phba: pointer to lpfc hba data structure.
18458  *
18459  * This routine is invoked to remove the memory region that
18460  * provided rpi via a bitmask.
18461  **/
18462 int
18463 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
18464 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
18465 {
18466 	LPFC_MBOXQ_t *mboxq;
18467 	struct lpfc_hba *phba = ndlp->phba;
18468 	int rc;
18469 
18470 	/* The port is notified of the header region via a mailbox command. */
18471 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18472 	if (!mboxq)
18473 		return -ENOMEM;
18474 
18475 	/* Post all rpi memory regions to the port. */
18476 	lpfc_resume_rpi(mboxq, ndlp);
18477 	if (cmpl) {
18478 		mboxq->mbox_cmpl = cmpl;
18479 		mboxq->ctx_buf = arg;
18480 		mboxq->ctx_ndlp = ndlp;
18481 	} else
18482 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
18483 	mboxq->vport = ndlp->vport;
18484 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18485 	if (rc == MBX_NOT_FINISHED) {
18486 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18487 				"2010 Resume RPI Mailbox failed "
18488 				"status %d, mbxStatus x%x\n", rc,
18489 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
18490 		mempool_free(mboxq, phba->mbox_mem_pool);
18491 		return -EIO;
18492 	}
18493 	return 0;
18494 }
18495 
18496 /**
18497  * lpfc_sli4_init_vpi - Initialize a vpi with the port
18498  * @vport: Pointer to the vport for which the vpi is being initialized
18499  *
18500  * This routine is invoked to activate a vpi with the port.
18501  *
18502  * Returns:
18503  *    0 success
18504  *    -Evalue otherwise
18505  **/
18506 int
18507 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
18508 {
18509 	LPFC_MBOXQ_t *mboxq;
18510 	int rc = 0;
18511 	int retval = MBX_SUCCESS;
18512 	uint32_t mbox_tmo;
18513 	struct lpfc_hba *phba = vport->phba;
18514 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18515 	if (!mboxq)
18516 		return -ENOMEM;
18517 	lpfc_init_vpi(phba, mboxq, vport->vpi);
18518 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
18519 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
18520 	if (rc != MBX_SUCCESS) {
18521 		lpfc_printf_vlog(vport, KERN_ERR, LOG_SLI,
18522 				"2022 INIT VPI Mailbox failed "
18523 				"status %d, mbxStatus x%x\n", rc,
18524 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
18525 		retval = -EIO;
18526 	}
18527 	if (rc != MBX_TIMEOUT)
18528 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
18529 
18530 	return retval;
18531 }
18532 
18533 /**
18534  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
18535  * @phba: pointer to lpfc hba data structure.
18536  * @mboxq: Pointer to mailbox object.
18537  *
18538  * This routine is invoked to manually add a single FCF record. The caller
18539  * must pass a completely initialized FCF_Record.  This routine takes
18540  * care of the nonembedded mailbox operations.
18541  **/
18542 static void
18543 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
18544 {
18545 	void *virt_addr;
18546 	union lpfc_sli4_cfg_shdr *shdr;
18547 	uint32_t shdr_status, shdr_add_status;
18548 
18549 	virt_addr = mboxq->sge_array->addr[0];
18550 	/* The IOCTL status is embedded in the mailbox subheader. */
18551 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
18552 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18553 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18554 
18555 	if ((shdr_status || shdr_add_status) &&
18556 		(shdr_status != STATUS_FCF_IN_USE))
18557 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18558 			"2558 ADD_FCF_RECORD mailbox failed with "
18559 			"status x%x add_status x%x\n",
18560 			shdr_status, shdr_add_status);
18561 
18562 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
18563 }
18564 
18565 /**
18566  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
18567  * @phba: pointer to lpfc hba data structure.
18568  * @fcf_record:  pointer to the initialized fcf record to add.
18569  *
18570  * This routine is invoked to manually add a single FCF record. The caller
18571  * must pass a completely initialized FCF_Record.  This routine takes
18572  * care of the nonembedded mailbox operations.
18573  **/
18574 int
18575 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
18576 {
18577 	int rc = 0;
18578 	LPFC_MBOXQ_t *mboxq;
18579 	uint8_t *bytep;
18580 	void *virt_addr;
18581 	struct lpfc_mbx_sge sge;
18582 	uint32_t alloc_len, req_len;
18583 	uint32_t fcfindex;
18584 
18585 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18586 	if (!mboxq) {
18587 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18588 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
18589 		return -ENOMEM;
18590 	}
18591 
18592 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
18593 		  sizeof(uint32_t);
18594 
18595 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18596 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
18597 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
18598 				     req_len, LPFC_SLI4_MBX_NEMBED);
18599 	if (alloc_len < req_len) {
18600 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18601 			"2523 Allocated DMA memory size (x%x) is "
18602 			"less than the requested DMA memory "
18603 			"size (x%x)\n", alloc_len, req_len);
18604 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18605 		return -ENOMEM;
18606 	}
18607 
18608 	/*
18609 	 * Get the first SGE entry from the non-embedded DMA memory.  This
18610 	 * routine only uses a single SGE.
18611 	 */
18612 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
18613 	virt_addr = mboxq->sge_array->addr[0];
18614 	/*
18615 	 * Configure the FCF record for FCFI 0.  This is the driver's
18616 	 * hardcoded default and gets used in nonFIP mode.
18617 	 */
18618 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
18619 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
18620 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
18621 
18622 	/*
18623 	 * Copy the fcf_index and the FCF Record Data. The data starts after
18624 	 * the FCoE header plus word10. The data copy needs to be endian
18625 	 * correct.
18626 	 */
18627 	bytep += sizeof(uint32_t);
18628 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
18629 	mboxq->vport = phba->pport;
18630 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
18631 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18632 	if (rc == MBX_NOT_FINISHED) {
18633 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18634 			"2515 ADD_FCF_RECORD mailbox failed with "
18635 			"status 0x%x\n", rc);
18636 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18637 		rc = -EIO;
18638 	} else
18639 		rc = 0;
18640 
18641 	return rc;
18642 }
18643 
18644 /**
18645  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
18646  * @phba: pointer to lpfc hba data structure.
18647  * @fcf_record:  pointer to the fcf record to write the default data.
18648  * @fcf_index: FCF table entry index.
18649  *
18650  * This routine is invoked to build the driver's default FCF record.  The
18651  * values used are hardcoded.  This routine handles memory initialization.
18652  *
18653  **/
18654 void
18655 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
18656 				struct fcf_record *fcf_record,
18657 				uint16_t fcf_index)
18658 {
18659 	memset(fcf_record, 0, sizeof(struct fcf_record));
18660 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
18661 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
18662 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
18663 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
18664 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
18665 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
18666 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
18667 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
18668 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
18669 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
18670 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
18671 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
18672 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
18673 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
18674 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
18675 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
18676 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
18677 	/* Set the VLAN bit map */
18678 	if (phba->valid_vlan) {
18679 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
18680 			= 1 << (phba->vlan_id % 8);
18681 	}
18682 }
18683 
18684 /**
18685  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
18686  * @phba: pointer to lpfc hba data structure.
18687  * @fcf_index: FCF table entry offset.
18688  *
18689  * This routine is invoked to scan the entire FCF table by reading FCF
18690  * record and processing it one at a time starting from the @fcf_index
18691  * for initial FCF discovery or fast FCF failover rediscovery.
18692  *
18693  * Return 0 if the mailbox command is submitted successfully, none 0
18694  * otherwise.
18695  **/
18696 int
18697 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
18698 {
18699 	int rc = 0, error;
18700 	LPFC_MBOXQ_t *mboxq;
18701 
18702 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
18703 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
18704 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18705 	if (!mboxq) {
18706 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18707 				"2000 Failed to allocate mbox for "
18708 				"READ_FCF cmd\n");
18709 		error = -ENOMEM;
18710 		goto fail_fcf_scan;
18711 	}
18712 	/* Construct the read FCF record mailbox command */
18713 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
18714 	if (rc) {
18715 		error = -EINVAL;
18716 		goto fail_fcf_scan;
18717 	}
18718 	/* Issue the mailbox command asynchronously */
18719 	mboxq->vport = phba->pport;
18720 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
18721 
18722 	spin_lock_irq(&phba->hbalock);
18723 	phba->hba_flag |= FCF_TS_INPROG;
18724 	spin_unlock_irq(&phba->hbalock);
18725 
18726 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18727 	if (rc == MBX_NOT_FINISHED)
18728 		error = -EIO;
18729 	else {
18730 		/* Reset eligible FCF count for new scan */
18731 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
18732 			phba->fcf.eligible_fcf_cnt = 0;
18733 		error = 0;
18734 	}
18735 fail_fcf_scan:
18736 	if (error) {
18737 		if (mboxq)
18738 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
18739 		/* FCF scan failed, clear FCF_TS_INPROG flag */
18740 		spin_lock_irq(&phba->hbalock);
18741 		phba->hba_flag &= ~FCF_TS_INPROG;
18742 		spin_unlock_irq(&phba->hbalock);
18743 	}
18744 	return error;
18745 }
18746 
18747 /**
18748  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
18749  * @phba: pointer to lpfc hba data structure.
18750  * @fcf_index: FCF table entry offset.
18751  *
18752  * This routine is invoked to read an FCF record indicated by @fcf_index
18753  * and to use it for FLOGI roundrobin FCF failover.
18754  *
18755  * Return 0 if the mailbox command is submitted successfully, none 0
18756  * otherwise.
18757  **/
18758 int
18759 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
18760 {
18761 	int rc = 0, error;
18762 	LPFC_MBOXQ_t *mboxq;
18763 
18764 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18765 	if (!mboxq) {
18766 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
18767 				"2763 Failed to allocate mbox for "
18768 				"READ_FCF cmd\n");
18769 		error = -ENOMEM;
18770 		goto fail_fcf_read;
18771 	}
18772 	/* Construct the read FCF record mailbox command */
18773 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
18774 	if (rc) {
18775 		error = -EINVAL;
18776 		goto fail_fcf_read;
18777 	}
18778 	/* Issue the mailbox command asynchronously */
18779 	mboxq->vport = phba->pport;
18780 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
18781 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18782 	if (rc == MBX_NOT_FINISHED)
18783 		error = -EIO;
18784 	else
18785 		error = 0;
18786 
18787 fail_fcf_read:
18788 	if (error && mboxq)
18789 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18790 	return error;
18791 }
18792 
18793 /**
18794  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
18795  * @phba: pointer to lpfc hba data structure.
18796  * @fcf_index: FCF table entry offset.
18797  *
18798  * This routine is invoked to read an FCF record indicated by @fcf_index to
18799  * determine whether it's eligible for FLOGI roundrobin failover list.
18800  *
18801  * Return 0 if the mailbox command is submitted successfully, none 0
18802  * otherwise.
18803  **/
18804 int
18805 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
18806 {
18807 	int rc = 0, error;
18808 	LPFC_MBOXQ_t *mboxq;
18809 
18810 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18811 	if (!mboxq) {
18812 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
18813 				"2758 Failed to allocate mbox for "
18814 				"READ_FCF cmd\n");
18815 				error = -ENOMEM;
18816 				goto fail_fcf_read;
18817 	}
18818 	/* Construct the read FCF record mailbox command */
18819 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
18820 	if (rc) {
18821 		error = -EINVAL;
18822 		goto fail_fcf_read;
18823 	}
18824 	/* Issue the mailbox command asynchronously */
18825 	mboxq->vport = phba->pport;
18826 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
18827 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18828 	if (rc == MBX_NOT_FINISHED)
18829 		error = -EIO;
18830 	else
18831 		error = 0;
18832 
18833 fail_fcf_read:
18834 	if (error && mboxq)
18835 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18836 	return error;
18837 }
18838 
18839 /**
18840  * lpfc_check_next_fcf_pri_level
18841  * phba pointer to the lpfc_hba struct for this port.
18842  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
18843  * routine when the rr_bmask is empty. The FCF indecies are put into the
18844  * rr_bmask based on their priority level. Starting from the highest priority
18845  * to the lowest. The most likely FCF candidate will be in the highest
18846  * priority group. When this routine is called it searches the fcf_pri list for
18847  * next lowest priority group and repopulates the rr_bmask with only those
18848  * fcf_indexes.
18849  * returns:
18850  * 1=success 0=failure
18851  **/
18852 static int
18853 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
18854 {
18855 	uint16_t next_fcf_pri;
18856 	uint16_t last_index;
18857 	struct lpfc_fcf_pri *fcf_pri;
18858 	int rc;
18859 	int ret = 0;
18860 
18861 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
18862 			LPFC_SLI4_FCF_TBL_INDX_MAX);
18863 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
18864 			"3060 Last IDX %d\n", last_index);
18865 
18866 	/* Verify the priority list has 2 or more entries */
18867 	spin_lock_irq(&phba->hbalock);
18868 	if (list_empty(&phba->fcf.fcf_pri_list) ||
18869 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
18870 		spin_unlock_irq(&phba->hbalock);
18871 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
18872 			"3061 Last IDX %d\n", last_index);
18873 		return 0; /* Empty rr list */
18874 	}
18875 	spin_unlock_irq(&phba->hbalock);
18876 
18877 	next_fcf_pri = 0;
18878 	/*
18879 	 * Clear the rr_bmask and set all of the bits that are at this
18880 	 * priority.
18881 	 */
18882 	memset(phba->fcf.fcf_rr_bmask, 0,
18883 			sizeof(*phba->fcf.fcf_rr_bmask));
18884 	spin_lock_irq(&phba->hbalock);
18885 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
18886 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
18887 			continue;
18888 		/*
18889 		 * the 1st priority that has not FLOGI failed
18890 		 * will be the highest.
18891 		 */
18892 		if (!next_fcf_pri)
18893 			next_fcf_pri = fcf_pri->fcf_rec.priority;
18894 		spin_unlock_irq(&phba->hbalock);
18895 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
18896 			rc = lpfc_sli4_fcf_rr_index_set(phba,
18897 						fcf_pri->fcf_rec.fcf_index);
18898 			if (rc)
18899 				return 0;
18900 		}
18901 		spin_lock_irq(&phba->hbalock);
18902 	}
18903 	/*
18904 	 * if next_fcf_pri was not set above and the list is not empty then
18905 	 * we have failed flogis on all of them. So reset flogi failed
18906 	 * and start at the beginning.
18907 	 */
18908 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
18909 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
18910 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
18911 			/*
18912 			 * the 1st priority that has not FLOGI failed
18913 			 * will be the highest.
18914 			 */
18915 			if (!next_fcf_pri)
18916 				next_fcf_pri = fcf_pri->fcf_rec.priority;
18917 			spin_unlock_irq(&phba->hbalock);
18918 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
18919 				rc = lpfc_sli4_fcf_rr_index_set(phba,
18920 						fcf_pri->fcf_rec.fcf_index);
18921 				if (rc)
18922 					return 0;
18923 			}
18924 			spin_lock_irq(&phba->hbalock);
18925 		}
18926 	} else
18927 		ret = 1;
18928 	spin_unlock_irq(&phba->hbalock);
18929 
18930 	return ret;
18931 }
18932 /**
18933  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
18934  * @phba: pointer to lpfc hba data structure.
18935  *
18936  * This routine is to get the next eligible FCF record index in a round
18937  * robin fashion. If the next eligible FCF record index equals to the
18938  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
18939  * shall be returned, otherwise, the next eligible FCF record's index
18940  * shall be returned.
18941  **/
18942 uint16_t
18943 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
18944 {
18945 	uint16_t next_fcf_index;
18946 
18947 initial_priority:
18948 	/* Search start from next bit of currently registered FCF index */
18949 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
18950 
18951 next_priority:
18952 	/* Determine the next fcf index to check */
18953 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
18954 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
18955 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
18956 				       next_fcf_index);
18957 
18958 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
18959 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
18960 		/*
18961 		 * If we have wrapped then we need to clear the bits that
18962 		 * have been tested so that we can detect when we should
18963 		 * change the priority level.
18964 		 */
18965 		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
18966 					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
18967 	}
18968 
18969 
18970 	/* Check roundrobin failover list empty condition */
18971 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
18972 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
18973 		/*
18974 		 * If next fcf index is not found check if there are lower
18975 		 * Priority level fcf's in the fcf_priority list.
18976 		 * Set up the rr_bmask with all of the avaiable fcf bits
18977 		 * at that level and continue the selection process.
18978 		 */
18979 		if (lpfc_check_next_fcf_pri_level(phba))
18980 			goto initial_priority;
18981 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
18982 				"2844 No roundrobin failover FCF available\n");
18983 
18984 		return LPFC_FCOE_FCF_NEXT_NONE;
18985 	}
18986 
18987 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
18988 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
18989 		LPFC_FCF_FLOGI_FAILED) {
18990 		if (list_is_singular(&phba->fcf.fcf_pri_list))
18991 			return LPFC_FCOE_FCF_NEXT_NONE;
18992 
18993 		goto next_priority;
18994 	}
18995 
18996 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
18997 			"2845 Get next roundrobin failover FCF (x%x)\n",
18998 			next_fcf_index);
18999 
19000 	return next_fcf_index;
19001 }
19002 
19003 /**
19004  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
19005  * @phba: pointer to lpfc hba data structure.
19006  *
19007  * This routine sets the FCF record index in to the eligible bmask for
19008  * roundrobin failover search. It checks to make sure that the index
19009  * does not go beyond the range of the driver allocated bmask dimension
19010  * before setting the bit.
19011  *
19012  * Returns 0 if the index bit successfully set, otherwise, it returns
19013  * -EINVAL.
19014  **/
19015 int
19016 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
19017 {
19018 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19019 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19020 				"2610 FCF (x%x) reached driver's book "
19021 				"keeping dimension:x%x\n",
19022 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19023 		return -EINVAL;
19024 	}
19025 	/* Set the eligible FCF record index bmask */
19026 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19027 
19028 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19029 			"2790 Set FCF (x%x) to roundrobin FCF failover "
19030 			"bmask\n", fcf_index);
19031 
19032 	return 0;
19033 }
19034 
19035 /**
19036  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
19037  * @phba: pointer to lpfc hba data structure.
19038  *
19039  * This routine clears the FCF record index from the eligible bmask for
19040  * roundrobin failover search. It checks to make sure that the index
19041  * does not go beyond the range of the driver allocated bmask dimension
19042  * before clearing the bit.
19043  **/
19044 void
19045 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
19046 {
19047 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
19048 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19049 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19050 				"2762 FCF (x%x) reached driver's book "
19051 				"keeping dimension:x%x\n",
19052 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19053 		return;
19054 	}
19055 	/* Clear the eligible FCF record index bmask */
19056 	spin_lock_irq(&phba->hbalock);
19057 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
19058 				 list) {
19059 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
19060 			list_del_init(&fcf_pri->list);
19061 			break;
19062 		}
19063 	}
19064 	spin_unlock_irq(&phba->hbalock);
19065 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19066 
19067 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19068 			"2791 Clear FCF (x%x) from roundrobin failover "
19069 			"bmask\n", fcf_index);
19070 }
19071 
19072 /**
19073  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
19074  * @phba: pointer to lpfc hba data structure.
19075  *
19076  * This routine is the completion routine for the rediscover FCF table mailbox
19077  * command. If the mailbox command returned failure, it will try to stop the
19078  * FCF rediscover wait timer.
19079  **/
19080 static void
19081 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
19082 {
19083 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19084 	uint32_t shdr_status, shdr_add_status;
19085 
19086 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19087 
19088 	shdr_status = bf_get(lpfc_mbox_hdr_status,
19089 			     &redisc_fcf->header.cfg_shdr.response);
19090 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
19091 			     &redisc_fcf->header.cfg_shdr.response);
19092 	if (shdr_status || shdr_add_status) {
19093 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19094 				"2746 Requesting for FCF rediscovery failed "
19095 				"status x%x add_status x%x\n",
19096 				shdr_status, shdr_add_status);
19097 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
19098 			spin_lock_irq(&phba->hbalock);
19099 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
19100 			spin_unlock_irq(&phba->hbalock);
19101 			/*
19102 			 * CVL event triggered FCF rediscover request failed,
19103 			 * last resort to re-try current registered FCF entry.
19104 			 */
19105 			lpfc_retry_pport_discovery(phba);
19106 		} else {
19107 			spin_lock_irq(&phba->hbalock);
19108 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
19109 			spin_unlock_irq(&phba->hbalock);
19110 			/*
19111 			 * DEAD FCF event triggered FCF rediscover request
19112 			 * failed, last resort to fail over as a link down
19113 			 * to FCF registration.
19114 			 */
19115 			lpfc_sli4_fcf_dead_failthrough(phba);
19116 		}
19117 	} else {
19118 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19119 				"2775 Start FCF rediscover quiescent timer\n");
19120 		/*
19121 		 * Start FCF rediscovery wait timer for pending FCF
19122 		 * before rescan FCF record table.
19123 		 */
19124 		lpfc_fcf_redisc_wait_start_timer(phba);
19125 	}
19126 
19127 	mempool_free(mbox, phba->mbox_mem_pool);
19128 }
19129 
19130 /**
19131  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
19132  * @phba: pointer to lpfc hba data structure.
19133  *
19134  * This routine is invoked to request for rediscovery of the entire FCF table
19135  * by the port.
19136  **/
19137 int
19138 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
19139 {
19140 	LPFC_MBOXQ_t *mbox;
19141 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19142 	int rc, length;
19143 
19144 	/* Cancel retry delay timers to all vports before FCF rediscover */
19145 	lpfc_cancel_all_vport_retry_delay_timer(phba);
19146 
19147 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19148 	if (!mbox) {
19149 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
19150 				"2745 Failed to allocate mbox for "
19151 				"requesting FCF rediscover.\n");
19152 		return -ENOMEM;
19153 	}
19154 
19155 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
19156 		  sizeof(struct lpfc_sli4_cfg_mhdr));
19157 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
19158 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
19159 			 length, LPFC_SLI4_MBX_EMBED);
19160 
19161 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19162 	/* Set count to 0 for invalidating the entire FCF database */
19163 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
19164 
19165 	/* Issue the mailbox command asynchronously */
19166 	mbox->vport = phba->pport;
19167 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
19168 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
19169 
19170 	if (rc == MBX_NOT_FINISHED) {
19171 		mempool_free(mbox, phba->mbox_mem_pool);
19172 		return -EIO;
19173 	}
19174 	return 0;
19175 }
19176 
19177 /**
19178  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
19179  * @phba: pointer to lpfc hba data structure.
19180  *
19181  * This function is the failover routine as a last resort to the FCF DEAD
19182  * event when driver failed to perform fast FCF failover.
19183  **/
19184 void
19185 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
19186 {
19187 	uint32_t link_state;
19188 
19189 	/*
19190 	 * Last resort as FCF DEAD event failover will treat this as
19191 	 * a link down, but save the link state because we don't want
19192 	 * it to be changed to Link Down unless it is already down.
19193 	 */
19194 	link_state = phba->link_state;
19195 	lpfc_linkdown(phba);
19196 	phba->link_state = link_state;
19197 
19198 	/* Unregister FCF if no devices connected to it */
19199 	lpfc_unregister_unused_fcf(phba);
19200 }
19201 
19202 /**
19203  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
19204  * @phba: pointer to lpfc hba data structure.
19205  * @rgn23_data: pointer to configure region 23 data.
19206  *
19207  * This function gets SLI3 port configure region 23 data through memory dump
19208  * mailbox command. When it successfully retrieves data, the size of the data
19209  * will be returned, otherwise, 0 will be returned.
19210  **/
19211 static uint32_t
19212 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19213 {
19214 	LPFC_MBOXQ_t *pmb = NULL;
19215 	MAILBOX_t *mb;
19216 	uint32_t offset = 0;
19217 	int rc;
19218 
19219 	if (!rgn23_data)
19220 		return 0;
19221 
19222 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19223 	if (!pmb) {
19224 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19225 				"2600 failed to allocate mailbox memory\n");
19226 		return 0;
19227 	}
19228 	mb = &pmb->u.mb;
19229 
19230 	do {
19231 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
19232 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
19233 
19234 		if (rc != MBX_SUCCESS) {
19235 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19236 					"2601 failed to read config "
19237 					"region 23, rc 0x%x Status 0x%x\n",
19238 					rc, mb->mbxStatus);
19239 			mb->un.varDmp.word_cnt = 0;
19240 		}
19241 		/*
19242 		 * dump mem may return a zero when finished or we got a
19243 		 * mailbox error, either way we are done.
19244 		 */
19245 		if (mb->un.varDmp.word_cnt == 0)
19246 			break;
19247 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
19248 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
19249 
19250 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
19251 				       rgn23_data + offset,
19252 				       mb->un.varDmp.word_cnt);
19253 		offset += mb->un.varDmp.word_cnt;
19254 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
19255 
19256 	mempool_free(pmb, phba->mbox_mem_pool);
19257 	return offset;
19258 }
19259 
19260 /**
19261  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
19262  * @phba: pointer to lpfc hba data structure.
19263  * @rgn23_data: pointer to configure region 23 data.
19264  *
19265  * This function gets SLI4 port configure region 23 data through memory dump
19266  * mailbox command. When it successfully retrieves data, the size of the data
19267  * will be returned, otherwise, 0 will be returned.
19268  **/
19269 static uint32_t
19270 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19271 {
19272 	LPFC_MBOXQ_t *mboxq = NULL;
19273 	struct lpfc_dmabuf *mp = NULL;
19274 	struct lpfc_mqe *mqe;
19275 	uint32_t data_length = 0;
19276 	int rc;
19277 
19278 	if (!rgn23_data)
19279 		return 0;
19280 
19281 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19282 	if (!mboxq) {
19283 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19284 				"3105 failed to allocate mailbox memory\n");
19285 		return 0;
19286 	}
19287 
19288 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
19289 		goto out;
19290 	mqe = &mboxq->u.mqe;
19291 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
19292 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19293 	if (rc)
19294 		goto out;
19295 	data_length = mqe->un.mb_words[5];
19296 	if (data_length == 0)
19297 		goto out;
19298 	if (data_length > DMP_RGN23_SIZE) {
19299 		data_length = 0;
19300 		goto out;
19301 	}
19302 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
19303 out:
19304 	mempool_free(mboxq, phba->mbox_mem_pool);
19305 	if (mp) {
19306 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
19307 		kfree(mp);
19308 	}
19309 	return data_length;
19310 }
19311 
19312 /**
19313  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
19314  * @phba: pointer to lpfc hba data structure.
19315  *
19316  * This function read region 23 and parse TLV for port status to
19317  * decide if the user disaled the port. If the TLV indicates the
19318  * port is disabled, the hba_flag is set accordingly.
19319  **/
19320 void
19321 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
19322 {
19323 	uint8_t *rgn23_data = NULL;
19324 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
19325 	uint32_t offset = 0;
19326 
19327 	/* Get adapter Region 23 data */
19328 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
19329 	if (!rgn23_data)
19330 		goto out;
19331 
19332 	if (phba->sli_rev < LPFC_SLI_REV4)
19333 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
19334 	else {
19335 		if_type = bf_get(lpfc_sli_intf_if_type,
19336 				 &phba->sli4_hba.sli_intf);
19337 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
19338 			goto out;
19339 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
19340 	}
19341 
19342 	if (!data_size)
19343 		goto out;
19344 
19345 	/* Check the region signature first */
19346 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
19347 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19348 			"2619 Config region 23 has bad signature\n");
19349 			goto out;
19350 	}
19351 	offset += 4;
19352 
19353 	/* Check the data structure version */
19354 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
19355 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19356 			"2620 Config region 23 has bad version\n");
19357 		goto out;
19358 	}
19359 	offset += 4;
19360 
19361 	/* Parse TLV entries in the region */
19362 	while (offset < data_size) {
19363 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
19364 			break;
19365 		/*
19366 		 * If the TLV is not driver specific TLV or driver id is
19367 		 * not linux driver id, skip the record.
19368 		 */
19369 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
19370 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
19371 		    (rgn23_data[offset + 3] != 0)) {
19372 			offset += rgn23_data[offset + 1] * 4 + 4;
19373 			continue;
19374 		}
19375 
19376 		/* Driver found a driver specific TLV in the config region */
19377 		sub_tlv_len = rgn23_data[offset + 1] * 4;
19378 		offset += 4;
19379 		tlv_offset = 0;
19380 
19381 		/*
19382 		 * Search for configured port state sub-TLV.
19383 		 */
19384 		while ((offset < data_size) &&
19385 			(tlv_offset < sub_tlv_len)) {
19386 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
19387 				offset += 4;
19388 				tlv_offset += 4;
19389 				break;
19390 			}
19391 			if (rgn23_data[offset] != PORT_STE_TYPE) {
19392 				offset += rgn23_data[offset + 1] * 4 + 4;
19393 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
19394 				continue;
19395 			}
19396 
19397 			/* This HBA contains PORT_STE configured */
19398 			if (!rgn23_data[offset + 2])
19399 				phba->hba_flag |= LINK_DISABLED;
19400 
19401 			goto out;
19402 		}
19403 	}
19404 
19405 out:
19406 	kfree(rgn23_data);
19407 	return;
19408 }
19409 
19410 /**
19411  * lpfc_wr_object - write an object to the firmware
19412  * @phba: HBA structure that indicates port to create a queue on.
19413  * @dmabuf_list: list of dmabufs to write to the port.
19414  * @size: the total byte value of the objects to write to the port.
19415  * @offset: the current offset to be used to start the transfer.
19416  *
19417  * This routine will create a wr_object mailbox command to send to the port.
19418  * the mailbox command will be constructed using the dma buffers described in
19419  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
19420  * BDEs that the imbedded mailbox can support. The @offset variable will be
19421  * used to indicate the starting offset of the transfer and will also return
19422  * the offset after the write object mailbox has completed. @size is used to
19423  * determine the end of the object and whether the eof bit should be set.
19424  *
19425  * Return 0 is successful and offset will contain the the new offset to use
19426  * for the next write.
19427  * Return negative value for error cases.
19428  **/
19429 int
19430 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
19431 	       uint32_t size, uint32_t *offset)
19432 {
19433 	struct lpfc_mbx_wr_object *wr_object;
19434 	LPFC_MBOXQ_t *mbox;
19435 	int rc = 0, i = 0;
19436 	uint32_t shdr_status, shdr_add_status, shdr_change_status, shdr_csf;
19437 	uint32_t mbox_tmo;
19438 	struct lpfc_dmabuf *dmabuf;
19439 	uint32_t written = 0;
19440 	bool check_change_status = false;
19441 
19442 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19443 	if (!mbox)
19444 		return -ENOMEM;
19445 
19446 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
19447 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
19448 			sizeof(struct lpfc_mbx_wr_object) -
19449 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
19450 
19451 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
19452 	wr_object->u.request.write_offset = *offset;
19453 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
19454 	wr_object->u.request.object_name[0] =
19455 		cpu_to_le32(wr_object->u.request.object_name[0]);
19456 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
19457 	list_for_each_entry(dmabuf, dmabuf_list, list) {
19458 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
19459 			break;
19460 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
19461 		wr_object->u.request.bde[i].addrHigh =
19462 			putPaddrHigh(dmabuf->phys);
19463 		if (written + SLI4_PAGE_SIZE >= size) {
19464 			wr_object->u.request.bde[i].tus.f.bdeSize =
19465 				(size - written);
19466 			written += (size - written);
19467 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
19468 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
19469 			check_change_status = true;
19470 		} else {
19471 			wr_object->u.request.bde[i].tus.f.bdeSize =
19472 				SLI4_PAGE_SIZE;
19473 			written += SLI4_PAGE_SIZE;
19474 		}
19475 		i++;
19476 	}
19477 	wr_object->u.request.bde_count = i;
19478 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
19479 	if (!phba->sli4_hba.intr_enable)
19480 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
19481 	else {
19482 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
19483 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
19484 	}
19485 	/* The IOCTL status is embedded in the mailbox subheader. */
19486 	shdr_status = bf_get(lpfc_mbox_hdr_status,
19487 			     &wr_object->header.cfg_shdr.response);
19488 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
19489 				 &wr_object->header.cfg_shdr.response);
19490 	if (check_change_status) {
19491 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
19492 					    &wr_object->u.response);
19493 
19494 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
19495 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
19496 			shdr_csf = bf_get(lpfc_wr_object_csf,
19497 					  &wr_object->u.response);
19498 			if (shdr_csf)
19499 				shdr_change_status =
19500 						   LPFC_CHANGE_STATUS_PCI_RESET;
19501 		}
19502 
19503 		switch (shdr_change_status) {
19504 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
19505 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19506 					"3198 Firmware write complete: System "
19507 					"reboot required to instantiate\n");
19508 			break;
19509 		case (LPFC_CHANGE_STATUS_FW_RESET):
19510 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19511 					"3199 Firmware write complete: Firmware"
19512 					" reset required to instantiate\n");
19513 			break;
19514 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
19515 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19516 					"3200 Firmware write complete: Port "
19517 					"Migration or PCI Reset required to "
19518 					"instantiate\n");
19519 			break;
19520 		case (LPFC_CHANGE_STATUS_PCI_RESET):
19521 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19522 					"3201 Firmware write complete: PCI "
19523 					"Reset required to instantiate\n");
19524 			break;
19525 		default:
19526 			break;
19527 		}
19528 	}
19529 	if (rc != MBX_TIMEOUT)
19530 		mempool_free(mbox, phba->mbox_mem_pool);
19531 	if (shdr_status || shdr_add_status || rc) {
19532 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19533 				"3025 Write Object mailbox failed with "
19534 				"status x%x add_status x%x, mbx status x%x\n",
19535 				shdr_status, shdr_add_status, rc);
19536 		rc = -ENXIO;
19537 		*offset = shdr_add_status;
19538 	} else
19539 		*offset += wr_object->u.response.actual_write_length;
19540 	return rc;
19541 }
19542 
19543 /**
19544  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
19545  * @vport: pointer to vport data structure.
19546  *
19547  * This function iterate through the mailboxq and clean up all REG_LOGIN
19548  * and REG_VPI mailbox commands associated with the vport. This function
19549  * is called when driver want to restart discovery of the vport due to
19550  * a Clear Virtual Link event.
19551  **/
19552 void
19553 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
19554 {
19555 	struct lpfc_hba *phba = vport->phba;
19556 	LPFC_MBOXQ_t *mb, *nextmb;
19557 	struct lpfc_dmabuf *mp;
19558 	struct lpfc_nodelist *ndlp;
19559 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
19560 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
19561 	LIST_HEAD(mbox_cmd_list);
19562 	uint8_t restart_loop;
19563 
19564 	/* Clean up internally queued mailbox commands with the vport */
19565 	spin_lock_irq(&phba->hbalock);
19566 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
19567 		if (mb->vport != vport)
19568 			continue;
19569 
19570 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
19571 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
19572 			continue;
19573 
19574 		list_del(&mb->list);
19575 		list_add_tail(&mb->list, &mbox_cmd_list);
19576 	}
19577 	/* Clean up active mailbox command with the vport */
19578 	mb = phba->sli.mbox_active;
19579 	if (mb && (mb->vport == vport)) {
19580 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
19581 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
19582 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19583 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19584 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19585 			/* Put reference count for delayed processing */
19586 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
19587 			/* Unregister the RPI when mailbox complete */
19588 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
19589 		}
19590 	}
19591 	/* Cleanup any mailbox completions which are not yet processed */
19592 	do {
19593 		restart_loop = 0;
19594 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
19595 			/*
19596 			 * If this mailox is already processed or it is
19597 			 * for another vport ignore it.
19598 			 */
19599 			if ((mb->vport != vport) ||
19600 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
19601 				continue;
19602 
19603 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
19604 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
19605 				continue;
19606 
19607 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19608 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19609 				ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19610 				/* Unregister the RPI when mailbox complete */
19611 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
19612 				restart_loop = 1;
19613 				spin_unlock_irq(&phba->hbalock);
19614 				spin_lock(shost->host_lock);
19615 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19616 				spin_unlock(shost->host_lock);
19617 				spin_lock_irq(&phba->hbalock);
19618 				break;
19619 			}
19620 		}
19621 	} while (restart_loop);
19622 
19623 	spin_unlock_irq(&phba->hbalock);
19624 
19625 	/* Release the cleaned-up mailbox commands */
19626 	while (!list_empty(&mbox_cmd_list)) {
19627 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
19628 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19629 			mp = (struct lpfc_dmabuf *)(mb->ctx_buf);
19630 			if (mp) {
19631 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
19632 				kfree(mp);
19633 			}
19634 			mb->ctx_buf = NULL;
19635 			ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19636 			mb->ctx_ndlp = NULL;
19637 			if (ndlp) {
19638 				spin_lock(shost->host_lock);
19639 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19640 				spin_unlock(shost->host_lock);
19641 				lpfc_nlp_put(ndlp);
19642 			}
19643 		}
19644 		mempool_free(mb, phba->mbox_mem_pool);
19645 	}
19646 
19647 	/* Release the ndlp with the cleaned-up active mailbox command */
19648 	if (act_mbx_ndlp) {
19649 		spin_lock(shost->host_lock);
19650 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19651 		spin_unlock(shost->host_lock);
19652 		lpfc_nlp_put(act_mbx_ndlp);
19653 	}
19654 }
19655 
19656 /**
19657  * lpfc_drain_txq - Drain the txq
19658  * @phba: Pointer to HBA context object.
19659  *
19660  * This function attempt to submit IOCBs on the txq
19661  * to the adapter.  For SLI4 adapters, the txq contains
19662  * ELS IOCBs that have been deferred because the there
19663  * are no SGLs.  This congestion can occur with large
19664  * vport counts during node discovery.
19665  **/
19666 
19667 uint32_t
19668 lpfc_drain_txq(struct lpfc_hba *phba)
19669 {
19670 	LIST_HEAD(completions);
19671 	struct lpfc_sli_ring *pring;
19672 	struct lpfc_iocbq *piocbq = NULL;
19673 	unsigned long iflags = 0;
19674 	char *fail_msg = NULL;
19675 	struct lpfc_sglq *sglq;
19676 	union lpfc_wqe128 wqe;
19677 	uint32_t txq_cnt = 0;
19678 	struct lpfc_queue *wq;
19679 
19680 	if (phba->link_flag & LS_MDS_LOOPBACK) {
19681 		/* MDS WQE are posted only to first WQ*/
19682 		wq = phba->sli4_hba.hdwq[0].io_wq;
19683 		if (unlikely(!wq))
19684 			return 0;
19685 		pring = wq->pring;
19686 	} else {
19687 		wq = phba->sli4_hba.els_wq;
19688 		if (unlikely(!wq))
19689 			return 0;
19690 		pring = lpfc_phba_elsring(phba);
19691 	}
19692 
19693 	if (unlikely(!pring) || list_empty(&pring->txq))
19694 		return 0;
19695 
19696 	spin_lock_irqsave(&pring->ring_lock, iflags);
19697 	list_for_each_entry(piocbq, &pring->txq, list) {
19698 		txq_cnt++;
19699 	}
19700 
19701 	if (txq_cnt > pring->txq_max)
19702 		pring->txq_max = txq_cnt;
19703 
19704 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
19705 
19706 	while (!list_empty(&pring->txq)) {
19707 		spin_lock_irqsave(&pring->ring_lock, iflags);
19708 
19709 		piocbq = lpfc_sli_ringtx_get(phba, pring);
19710 		if (!piocbq) {
19711 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19712 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
19713 				"2823 txq empty and txq_cnt is %d\n ",
19714 				txq_cnt);
19715 			break;
19716 		}
19717 		sglq = __lpfc_sli_get_els_sglq(phba, piocbq);
19718 		if (!sglq) {
19719 			__lpfc_sli_ringtx_put(phba, pring, piocbq);
19720 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19721 			break;
19722 		}
19723 		txq_cnt--;
19724 
19725 		/* The xri and iocb resources secured,
19726 		 * attempt to issue request
19727 		 */
19728 		piocbq->sli4_lxritag = sglq->sli4_lxritag;
19729 		piocbq->sli4_xritag = sglq->sli4_xritag;
19730 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
19731 			fail_msg = "to convert bpl to sgl";
19732 		else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
19733 			fail_msg = "to convert iocb to wqe";
19734 		else if (lpfc_sli4_wq_put(wq, &wqe))
19735 			fail_msg = " - Wq is full";
19736 		else
19737 			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
19738 
19739 		if (fail_msg) {
19740 			/* Failed means we can't issue and need to cancel */
19741 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
19742 					"2822 IOCB failed %s iotag 0x%x "
19743 					"xri 0x%x\n",
19744 					fail_msg,
19745 					piocbq->iotag, piocbq->sli4_xritag);
19746 			list_add_tail(&piocbq->list, &completions);
19747 		}
19748 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
19749 	}
19750 
19751 	/* Cancel all the IOCBs that cannot be issued */
19752 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
19753 				IOERR_SLI_ABORTED);
19754 
19755 	return txq_cnt;
19756 }
19757 
19758 /**
19759  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
19760  * @phba: Pointer to HBA context object.
19761  * @pwqe: Pointer to command WQE.
19762  * @sglq: Pointer to the scatter gather queue object.
19763  *
19764  * This routine converts the bpl or bde that is in the WQE
19765  * to a sgl list for the sli4 hardware. The physical address
19766  * of the bpl/bde is converted back to a virtual address.
19767  * If the WQE contains a BPL then the list of BDE's is
19768  * converted to sli4_sge's. If the WQE contains a single
19769  * BDE then it is converted to a single sli_sge.
19770  * The WQE is still in cpu endianness so the contents of
19771  * the bpl can be used without byte swapping.
19772  *
19773  * Returns valid XRI = Success, NO_XRI = Failure.
19774  */
19775 static uint16_t
19776 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
19777 		 struct lpfc_sglq *sglq)
19778 {
19779 	uint16_t xritag = NO_XRI;
19780 	struct ulp_bde64 *bpl = NULL;
19781 	struct ulp_bde64 bde;
19782 	struct sli4_sge *sgl  = NULL;
19783 	struct lpfc_dmabuf *dmabuf;
19784 	union lpfc_wqe128 *wqe;
19785 	int numBdes = 0;
19786 	int i = 0;
19787 	uint32_t offset = 0; /* accumulated offset in the sg request list */
19788 	int inbound = 0; /* number of sg reply entries inbound from firmware */
19789 	uint32_t cmd;
19790 
19791 	if (!pwqeq || !sglq)
19792 		return xritag;
19793 
19794 	sgl  = (struct sli4_sge *)sglq->sgl;
19795 	wqe = &pwqeq->wqe;
19796 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
19797 
19798 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
19799 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
19800 		return sglq->sli4_xritag;
19801 	numBdes = pwqeq->rsvd2;
19802 	if (numBdes) {
19803 		/* The addrHigh and addrLow fields within the WQE
19804 		 * have not been byteswapped yet so there is no
19805 		 * need to swap them back.
19806 		 */
19807 		if (pwqeq->context3)
19808 			dmabuf = (struct lpfc_dmabuf *)pwqeq->context3;
19809 		else
19810 			return xritag;
19811 
19812 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
19813 		if (!bpl)
19814 			return xritag;
19815 
19816 		for (i = 0; i < numBdes; i++) {
19817 			/* Should already be byte swapped. */
19818 			sgl->addr_hi = bpl->addrHigh;
19819 			sgl->addr_lo = bpl->addrLow;
19820 
19821 			sgl->word2 = le32_to_cpu(sgl->word2);
19822 			if ((i+1) == numBdes)
19823 				bf_set(lpfc_sli4_sge_last, sgl, 1);
19824 			else
19825 				bf_set(lpfc_sli4_sge_last, sgl, 0);
19826 			/* swap the size field back to the cpu so we
19827 			 * can assign it to the sgl.
19828 			 */
19829 			bde.tus.w = le32_to_cpu(bpl->tus.w);
19830 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
19831 			/* The offsets in the sgl need to be accumulated
19832 			 * separately for the request and reply lists.
19833 			 * The request is always first, the reply follows.
19834 			 */
19835 			switch (cmd) {
19836 			case CMD_GEN_REQUEST64_WQE:
19837 				/* add up the reply sg entries */
19838 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
19839 					inbound++;
19840 				/* first inbound? reset the offset */
19841 				if (inbound == 1)
19842 					offset = 0;
19843 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
19844 				bf_set(lpfc_sli4_sge_type, sgl,
19845 					LPFC_SGE_TYPE_DATA);
19846 				offset += bde.tus.f.bdeSize;
19847 				break;
19848 			case CMD_FCP_TRSP64_WQE:
19849 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
19850 				bf_set(lpfc_sli4_sge_type, sgl,
19851 					LPFC_SGE_TYPE_DATA);
19852 				break;
19853 			case CMD_FCP_TSEND64_WQE:
19854 			case CMD_FCP_TRECEIVE64_WQE:
19855 				bf_set(lpfc_sli4_sge_type, sgl,
19856 					bpl->tus.f.bdeFlags);
19857 				if (i < 3)
19858 					offset = 0;
19859 				else
19860 					offset += bde.tus.f.bdeSize;
19861 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
19862 				break;
19863 			}
19864 			sgl->word2 = cpu_to_le32(sgl->word2);
19865 			bpl++;
19866 			sgl++;
19867 		}
19868 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
19869 		/* The addrHigh and addrLow fields of the BDE have not
19870 		 * been byteswapped yet so they need to be swapped
19871 		 * before putting them in the sgl.
19872 		 */
19873 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
19874 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
19875 		sgl->word2 = le32_to_cpu(sgl->word2);
19876 		bf_set(lpfc_sli4_sge_last, sgl, 1);
19877 		sgl->word2 = cpu_to_le32(sgl->word2);
19878 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
19879 	}
19880 	return sglq->sli4_xritag;
19881 }
19882 
19883 /**
19884  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
19885  * @phba: Pointer to HBA context object.
19886  * @ring_number: Base sli ring number
19887  * @pwqe: Pointer to command WQE.
19888  **/
19889 int
19890 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
19891 		    struct lpfc_iocbq *pwqe)
19892 {
19893 	union lpfc_wqe128 *wqe = &pwqe->wqe;
19894 	struct lpfc_nvmet_rcv_ctx *ctxp;
19895 	struct lpfc_queue *wq;
19896 	struct lpfc_sglq *sglq;
19897 	struct lpfc_sli_ring *pring;
19898 	unsigned long iflags;
19899 	uint32_t ret = 0;
19900 
19901 	/* NVME_LS and NVME_LS ABTS requests. */
19902 	if (pwqe->iocb_flag & LPFC_IO_NVME_LS) {
19903 		pring =  phba->sli4_hba.nvmels_wq->pring;
19904 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
19905 					  qp, wq_access);
19906 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
19907 		if (!sglq) {
19908 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19909 			return WQE_BUSY;
19910 		}
19911 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
19912 		pwqe->sli4_xritag = sglq->sli4_xritag;
19913 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
19914 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19915 			return WQE_ERROR;
19916 		}
19917 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
19918 		       pwqe->sli4_xritag);
19919 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
19920 		if (ret) {
19921 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19922 			return ret;
19923 		}
19924 
19925 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
19926 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
19927 
19928 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
19929 		return 0;
19930 	}
19931 
19932 	/* NVME_FCREQ and NVME_ABTS requests */
19933 	if (pwqe->iocb_flag & LPFC_IO_NVME) {
19934 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
19935 		wq = qp->io_wq;
19936 		pring = wq->pring;
19937 
19938 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
19939 
19940 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
19941 					  qp, wq_access);
19942 		ret = lpfc_sli4_wq_put(wq, wqe);
19943 		if (ret) {
19944 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19945 			return ret;
19946 		}
19947 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
19948 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
19949 
19950 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
19951 		return 0;
19952 	}
19953 
19954 	/* NVMET requests */
19955 	if (pwqe->iocb_flag & LPFC_IO_NVMET) {
19956 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
19957 		wq = qp->io_wq;
19958 		pring = wq->pring;
19959 
19960 		ctxp = pwqe->context2;
19961 		sglq = ctxp->ctxbuf->sglq;
19962 		if (pwqe->sli4_xritag ==  NO_XRI) {
19963 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
19964 			pwqe->sli4_xritag = sglq->sli4_xritag;
19965 		}
19966 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
19967 		       pwqe->sli4_xritag);
19968 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
19969 
19970 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
19971 					  qp, wq_access);
19972 		ret = lpfc_sli4_wq_put(wq, wqe);
19973 		if (ret) {
19974 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19975 			return ret;
19976 		}
19977 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
19978 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
19979 
19980 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
19981 		return 0;
19982 	}
19983 	return WQE_ERROR;
19984 }
19985 
19986 #ifdef LPFC_MXP_STAT
19987 /**
19988  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
19989  * @phba: pointer to lpfc hba data structure.
19990  * @hwqid: belong to which HWQ.
19991  *
19992  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
19993  * 15 seconds after a test case is running.
19994  *
19995  * The user should call lpfc_debugfs_multixripools_write before running a test
19996  * case to clear stat_snapshot_taken. Then the user starts a test case. During
19997  * test case is running, stat_snapshot_taken is incremented by 1 every time when
19998  * this routine is called from heartbeat timer. When stat_snapshot_taken is
19999  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
20000  **/
20001 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
20002 {
20003 	struct lpfc_sli4_hdw_queue *qp;
20004 	struct lpfc_multixri_pool *multixri_pool;
20005 	struct lpfc_pvt_pool *pvt_pool;
20006 	struct lpfc_pbl_pool *pbl_pool;
20007 	u32 txcmplq_cnt;
20008 
20009 	qp = &phba->sli4_hba.hdwq[hwqid];
20010 	multixri_pool = qp->p_multixri_pool;
20011 	if (!multixri_pool)
20012 		return;
20013 
20014 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
20015 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
20016 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
20017 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20018 
20019 		multixri_pool->stat_pbl_count = pbl_pool->count;
20020 		multixri_pool->stat_pvt_count = pvt_pool->count;
20021 		multixri_pool->stat_busy_count = txcmplq_cnt;
20022 	}
20023 
20024 	multixri_pool->stat_snapshot_taken++;
20025 }
20026 #endif
20027 
20028 /**
20029  * lpfc_adjust_pvt_pool_count - Adjust private pool count
20030  * @phba: pointer to lpfc hba data structure.
20031  * @hwqid: belong to which HWQ.
20032  *
20033  * This routine moves some XRIs from private to public pool when private pool
20034  * is not busy.
20035  **/
20036 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
20037 {
20038 	struct lpfc_multixri_pool *multixri_pool;
20039 	u32 io_req_count;
20040 	u32 prev_io_req_count;
20041 
20042 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
20043 	if (!multixri_pool)
20044 		return;
20045 	io_req_count = multixri_pool->io_req_count;
20046 	prev_io_req_count = multixri_pool->prev_io_req_count;
20047 
20048 	if (prev_io_req_count != io_req_count) {
20049 		/* Private pool is busy */
20050 		multixri_pool->prev_io_req_count = io_req_count;
20051 	} else {
20052 		/* Private pool is not busy.
20053 		 * Move XRIs from private to public pool.
20054 		 */
20055 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
20056 	}
20057 }
20058 
20059 /**
20060  * lpfc_adjust_high_watermark - Adjust high watermark
20061  * @phba: pointer to lpfc hba data structure.
20062  * @hwqid: belong to which HWQ.
20063  *
20064  * This routine sets high watermark as number of outstanding XRIs,
20065  * but make sure the new value is between xri_limit/2 and xri_limit.
20066  **/
20067 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
20068 {
20069 	u32 new_watermark;
20070 	u32 watermark_max;
20071 	u32 watermark_min;
20072 	u32 xri_limit;
20073 	u32 txcmplq_cnt;
20074 	u32 abts_io_bufs;
20075 	struct lpfc_multixri_pool *multixri_pool;
20076 	struct lpfc_sli4_hdw_queue *qp;
20077 
20078 	qp = &phba->sli4_hba.hdwq[hwqid];
20079 	multixri_pool = qp->p_multixri_pool;
20080 	if (!multixri_pool)
20081 		return;
20082 	xri_limit = multixri_pool->xri_limit;
20083 
20084 	watermark_max = xri_limit;
20085 	watermark_min = xri_limit / 2;
20086 
20087 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20088 	abts_io_bufs = qp->abts_scsi_io_bufs;
20089 	abts_io_bufs += qp->abts_nvme_io_bufs;
20090 
20091 	new_watermark = txcmplq_cnt + abts_io_bufs;
20092 	new_watermark = min(watermark_max, new_watermark);
20093 	new_watermark = max(watermark_min, new_watermark);
20094 	multixri_pool->pvt_pool.high_watermark = new_watermark;
20095 
20096 #ifdef LPFC_MXP_STAT
20097 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
20098 					  new_watermark);
20099 #endif
20100 }
20101 
20102 /**
20103  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
20104  * @phba: pointer to lpfc hba data structure.
20105  * @hwqid: belong to which HWQ.
20106  *
20107  * This routine is called from hearbeat timer when pvt_pool is idle.
20108  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
20109  * The first step moves (all - low_watermark) amount of XRIs.
20110  * The second step moves the rest of XRIs.
20111  **/
20112 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
20113 {
20114 	struct lpfc_pbl_pool *pbl_pool;
20115 	struct lpfc_pvt_pool *pvt_pool;
20116 	struct lpfc_sli4_hdw_queue *qp;
20117 	struct lpfc_io_buf *lpfc_ncmd;
20118 	struct lpfc_io_buf *lpfc_ncmd_next;
20119 	unsigned long iflag;
20120 	struct list_head tmp_list;
20121 	u32 tmp_count;
20122 
20123 	qp = &phba->sli4_hba.hdwq[hwqid];
20124 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
20125 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
20126 	tmp_count = 0;
20127 
20128 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
20129 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
20130 
20131 	if (pvt_pool->count > pvt_pool->low_watermark) {
20132 		/* Step 1: move (all - low_watermark) from pvt_pool
20133 		 * to pbl_pool
20134 		 */
20135 
20136 		/* Move low watermark of bufs from pvt_pool to tmp_list */
20137 		INIT_LIST_HEAD(&tmp_list);
20138 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20139 					 &pvt_pool->list, list) {
20140 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
20141 			tmp_count++;
20142 			if (tmp_count >= pvt_pool->low_watermark)
20143 				break;
20144 		}
20145 
20146 		/* Move all bufs from pvt_pool to pbl_pool */
20147 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
20148 
20149 		/* Move all bufs from tmp_list to pvt_pool */
20150 		list_splice(&tmp_list, &pvt_pool->list);
20151 
20152 		pbl_pool->count += (pvt_pool->count - tmp_count);
20153 		pvt_pool->count = tmp_count;
20154 	} else {
20155 		/* Step 2: move the rest from pvt_pool to pbl_pool */
20156 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
20157 		pbl_pool->count += pvt_pool->count;
20158 		pvt_pool->count = 0;
20159 	}
20160 
20161 	spin_unlock(&pvt_pool->lock);
20162 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20163 }
20164 
20165 /**
20166  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
20167  * @phba: pointer to lpfc hba data structure
20168  * @pbl_pool: specified public free XRI pool
20169  * @pvt_pool: specified private free XRI pool
20170  * @count: number of XRIs to move
20171  *
20172  * This routine tries to move some free common bufs from the specified pbl_pool
20173  * to the specified pvt_pool. It might move less than count XRIs if there's not
20174  * enough in public pool.
20175  *
20176  * Return:
20177  *   true - if XRIs are successfully moved from the specified pbl_pool to the
20178  *          specified pvt_pool
20179  *   false - if the specified pbl_pool is empty or locked by someone else
20180  **/
20181 static bool
20182 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
20183 			  struct lpfc_pbl_pool *pbl_pool,
20184 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
20185 {
20186 	struct lpfc_io_buf *lpfc_ncmd;
20187 	struct lpfc_io_buf *lpfc_ncmd_next;
20188 	unsigned long iflag;
20189 	int ret;
20190 
20191 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
20192 	if (ret) {
20193 		if (pbl_pool->count) {
20194 			/* Move a batch of XRIs from public to private pool */
20195 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
20196 			list_for_each_entry_safe(lpfc_ncmd,
20197 						 lpfc_ncmd_next,
20198 						 &pbl_pool->list,
20199 						 list) {
20200 				list_move_tail(&lpfc_ncmd->list,
20201 					       &pvt_pool->list);
20202 				pvt_pool->count++;
20203 				pbl_pool->count--;
20204 				count--;
20205 				if (count == 0)
20206 					break;
20207 			}
20208 
20209 			spin_unlock(&pvt_pool->lock);
20210 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20211 			return true;
20212 		}
20213 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20214 	}
20215 
20216 	return false;
20217 }
20218 
20219 /**
20220  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
20221  * @phba: pointer to lpfc hba data structure.
20222  * @hwqid: belong to which HWQ.
20223  * @count: number of XRIs to move
20224  *
20225  * This routine tries to find some free common bufs in one of public pools with
20226  * Round Robin method. The search always starts from local hwqid, then the next
20227  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
20228  * a batch of free common bufs are moved to private pool on hwqid.
20229  * It might move less than count XRIs if there's not enough in public pool.
20230  **/
20231 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
20232 {
20233 	struct lpfc_multixri_pool *multixri_pool;
20234 	struct lpfc_multixri_pool *next_multixri_pool;
20235 	struct lpfc_pvt_pool *pvt_pool;
20236 	struct lpfc_pbl_pool *pbl_pool;
20237 	struct lpfc_sli4_hdw_queue *qp;
20238 	u32 next_hwqid;
20239 	u32 hwq_count;
20240 	int ret;
20241 
20242 	qp = &phba->sli4_hba.hdwq[hwqid];
20243 	multixri_pool = qp->p_multixri_pool;
20244 	pvt_pool = &multixri_pool->pvt_pool;
20245 	pbl_pool = &multixri_pool->pbl_pool;
20246 
20247 	/* Check if local pbl_pool is available */
20248 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
20249 	if (ret) {
20250 #ifdef LPFC_MXP_STAT
20251 		multixri_pool->local_pbl_hit_count++;
20252 #endif
20253 		return;
20254 	}
20255 
20256 	hwq_count = phba->cfg_hdw_queue;
20257 
20258 	/* Get the next hwqid which was found last time */
20259 	next_hwqid = multixri_pool->rrb_next_hwqid;
20260 
20261 	do {
20262 		/* Go to next hwq */
20263 		next_hwqid = (next_hwqid + 1) % hwq_count;
20264 
20265 		next_multixri_pool =
20266 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
20267 		pbl_pool = &next_multixri_pool->pbl_pool;
20268 
20269 		/* Check if the public free xri pool is available */
20270 		ret = _lpfc_move_xri_pbl_to_pvt(
20271 			phba, qp, pbl_pool, pvt_pool, count);
20272 
20273 		/* Exit while-loop if success or all hwqid are checked */
20274 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
20275 
20276 	/* Starting point for the next time */
20277 	multixri_pool->rrb_next_hwqid = next_hwqid;
20278 
20279 	if (!ret) {
20280 		/* stats: all public pools are empty*/
20281 		multixri_pool->pbl_empty_count++;
20282 	}
20283 
20284 #ifdef LPFC_MXP_STAT
20285 	if (ret) {
20286 		if (next_hwqid == hwqid)
20287 			multixri_pool->local_pbl_hit_count++;
20288 		else
20289 			multixri_pool->other_pbl_hit_count++;
20290 	}
20291 #endif
20292 }
20293 
20294 /**
20295  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
20296  * @phba: pointer to lpfc hba data structure.
20297  * @qp: belong to which HWQ.
20298  *
20299  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
20300  * low watermark.
20301  **/
20302 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
20303 {
20304 	struct lpfc_multixri_pool *multixri_pool;
20305 	struct lpfc_pvt_pool *pvt_pool;
20306 
20307 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
20308 	pvt_pool = &multixri_pool->pvt_pool;
20309 
20310 	if (pvt_pool->count < pvt_pool->low_watermark)
20311 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
20312 }
20313 
20314 /**
20315  * lpfc_release_io_buf - Return one IO buf back to free pool
20316  * @phba: pointer to lpfc hba data structure.
20317  * @lpfc_ncmd: IO buf to be returned.
20318  * @qp: belong to which HWQ.
20319  *
20320  * This routine returns one IO buf back to free pool. If this is an urgent IO,
20321  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
20322  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
20323  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
20324  * lpfc_io_buf_list_put.
20325  **/
20326 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
20327 			 struct lpfc_sli4_hdw_queue *qp)
20328 {
20329 	unsigned long iflag;
20330 	struct lpfc_pbl_pool *pbl_pool;
20331 	struct lpfc_pvt_pool *pvt_pool;
20332 	struct lpfc_epd_pool *epd_pool;
20333 	u32 txcmplq_cnt;
20334 	u32 xri_owned;
20335 	u32 xri_limit;
20336 	u32 abts_io_bufs;
20337 
20338 	/* MUST zero fields if buffer is reused by another protocol */
20339 	lpfc_ncmd->nvmeCmd = NULL;
20340 	lpfc_ncmd->cur_iocbq.wqe_cmpl = NULL;
20341 	lpfc_ncmd->cur_iocbq.iocb_cmpl = NULL;
20342 
20343 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
20344 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
20345 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
20346 
20347 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
20348 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
20349 
20350 	if (phba->cfg_xri_rebalancing) {
20351 		if (lpfc_ncmd->expedite) {
20352 			/* Return to expedite pool */
20353 			epd_pool = &phba->epd_pool;
20354 			spin_lock_irqsave(&epd_pool->lock, iflag);
20355 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
20356 			epd_pool->count++;
20357 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
20358 			return;
20359 		}
20360 
20361 		/* Avoid invalid access if an IO sneaks in and is being rejected
20362 		 * just _after_ xri pools are destroyed in lpfc_offline.
20363 		 * Nothing much can be done at this point.
20364 		 */
20365 		if (!qp->p_multixri_pool)
20366 			return;
20367 
20368 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
20369 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
20370 
20371 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20372 		abts_io_bufs = qp->abts_scsi_io_bufs;
20373 		abts_io_bufs += qp->abts_nvme_io_bufs;
20374 
20375 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
20376 		xri_limit = qp->p_multixri_pool->xri_limit;
20377 
20378 #ifdef LPFC_MXP_STAT
20379 		if (xri_owned <= xri_limit)
20380 			qp->p_multixri_pool->below_limit_count++;
20381 		else
20382 			qp->p_multixri_pool->above_limit_count++;
20383 #endif
20384 
20385 		/* XRI goes to either public or private free xri pool
20386 		 *     based on watermark and xri_limit
20387 		 */
20388 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
20389 		    (xri_owned < xri_limit &&
20390 		     pvt_pool->count < pvt_pool->high_watermark)) {
20391 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
20392 						  qp, free_pvt_pool);
20393 			list_add_tail(&lpfc_ncmd->list,
20394 				      &pvt_pool->list);
20395 			pvt_pool->count++;
20396 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
20397 		} else {
20398 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
20399 						  qp, free_pub_pool);
20400 			list_add_tail(&lpfc_ncmd->list,
20401 				      &pbl_pool->list);
20402 			pbl_pool->count++;
20403 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20404 		}
20405 	} else {
20406 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
20407 					  qp, free_xri);
20408 		list_add_tail(&lpfc_ncmd->list,
20409 			      &qp->lpfc_io_buf_list_put);
20410 		qp->put_io_bufs++;
20411 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
20412 				       iflag);
20413 	}
20414 }
20415 
20416 /**
20417  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
20418  * @phba: pointer to lpfc hba data structure.
20419  * @pvt_pool: pointer to private pool data structure.
20420  * @ndlp: pointer to lpfc nodelist data structure.
20421  *
20422  * This routine tries to get one free IO buf from private pool.
20423  *
20424  * Return:
20425  *   pointer to one free IO buf - if private pool is not empty
20426  *   NULL - if private pool is empty
20427  **/
20428 static struct lpfc_io_buf *
20429 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
20430 				  struct lpfc_sli4_hdw_queue *qp,
20431 				  struct lpfc_pvt_pool *pvt_pool,
20432 				  struct lpfc_nodelist *ndlp)
20433 {
20434 	struct lpfc_io_buf *lpfc_ncmd;
20435 	struct lpfc_io_buf *lpfc_ncmd_next;
20436 	unsigned long iflag;
20437 
20438 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
20439 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20440 				 &pvt_pool->list, list) {
20441 		if (lpfc_test_rrq_active(
20442 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
20443 			continue;
20444 		list_del(&lpfc_ncmd->list);
20445 		pvt_pool->count--;
20446 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
20447 		return lpfc_ncmd;
20448 	}
20449 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
20450 
20451 	return NULL;
20452 }
20453 
20454 /**
20455  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
20456  * @phba: pointer to lpfc hba data structure.
20457  *
20458  * This routine tries to get one free IO buf from expedite pool.
20459  *
20460  * Return:
20461  *   pointer to one free IO buf - if expedite pool is not empty
20462  *   NULL - if expedite pool is empty
20463  **/
20464 static struct lpfc_io_buf *
20465 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
20466 {
20467 	struct lpfc_io_buf *lpfc_ncmd;
20468 	struct lpfc_io_buf *lpfc_ncmd_next;
20469 	unsigned long iflag;
20470 	struct lpfc_epd_pool *epd_pool;
20471 
20472 	epd_pool = &phba->epd_pool;
20473 	lpfc_ncmd = NULL;
20474 
20475 	spin_lock_irqsave(&epd_pool->lock, iflag);
20476 	if (epd_pool->count > 0) {
20477 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20478 					 &epd_pool->list, list) {
20479 			list_del(&lpfc_ncmd->list);
20480 			epd_pool->count--;
20481 			break;
20482 		}
20483 	}
20484 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
20485 
20486 	return lpfc_ncmd;
20487 }
20488 
20489 /**
20490  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
20491  * @phba: pointer to lpfc hba data structure.
20492  * @ndlp: pointer to lpfc nodelist data structure.
20493  * @hwqid: belong to which HWQ
20494  * @expedite: 1 means this request is urgent.
20495  *
20496  * This routine will do the following actions and then return a pointer to
20497  * one free IO buf.
20498  *
20499  * 1. If private free xri count is empty, move some XRIs from public to
20500  *    private pool.
20501  * 2. Get one XRI from private free xri pool.
20502  * 3. If we fail to get one from pvt_pool and this is an expedite request,
20503  *    get one free xri from expedite pool.
20504  *
20505  * Note: ndlp is only used on SCSI side for RRQ testing.
20506  *       The caller should pass NULL for ndlp on NVME side.
20507  *
20508  * Return:
20509  *   pointer to one free IO buf - if private pool is not empty
20510  *   NULL - if private pool is empty
20511  **/
20512 static struct lpfc_io_buf *
20513 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
20514 				    struct lpfc_nodelist *ndlp,
20515 				    int hwqid, int expedite)
20516 {
20517 	struct lpfc_sli4_hdw_queue *qp;
20518 	struct lpfc_multixri_pool *multixri_pool;
20519 	struct lpfc_pvt_pool *pvt_pool;
20520 	struct lpfc_io_buf *lpfc_ncmd;
20521 
20522 	qp = &phba->sli4_hba.hdwq[hwqid];
20523 	lpfc_ncmd = NULL;
20524 	multixri_pool = qp->p_multixri_pool;
20525 	pvt_pool = &multixri_pool->pvt_pool;
20526 	multixri_pool->io_req_count++;
20527 
20528 	/* If pvt_pool is empty, move some XRIs from public to private pool */
20529 	if (pvt_pool->count == 0)
20530 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
20531 
20532 	/* Get one XRI from private free xri pool */
20533 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
20534 
20535 	if (lpfc_ncmd) {
20536 		lpfc_ncmd->hdwq = qp;
20537 		lpfc_ncmd->hdwq_no = hwqid;
20538 	} else if (expedite) {
20539 		/* If we fail to get one from pvt_pool and this is an expedite
20540 		 * request, get one free xri from expedite pool.
20541 		 */
20542 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
20543 	}
20544 
20545 	return lpfc_ncmd;
20546 }
20547 
20548 static inline struct lpfc_io_buf *
20549 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
20550 {
20551 	struct lpfc_sli4_hdw_queue *qp;
20552 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
20553 
20554 	qp = &phba->sli4_hba.hdwq[idx];
20555 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
20556 				 &qp->lpfc_io_buf_list_get, list) {
20557 		if (lpfc_test_rrq_active(phba, ndlp,
20558 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
20559 			continue;
20560 
20561 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
20562 			continue;
20563 
20564 		list_del_init(&lpfc_cmd->list);
20565 		qp->get_io_bufs--;
20566 		lpfc_cmd->hdwq = qp;
20567 		lpfc_cmd->hdwq_no = idx;
20568 		return lpfc_cmd;
20569 	}
20570 	return NULL;
20571 }
20572 
20573 /**
20574  * lpfc_get_io_buf - Get one IO buffer from free pool
20575  * @phba: The HBA for which this call is being executed.
20576  * @ndlp: pointer to lpfc nodelist data structure.
20577  * @hwqid: belong to which HWQ
20578  * @expedite: 1 means this request is urgent.
20579  *
20580  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
20581  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
20582  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
20583  *
20584  * Note: ndlp is only used on SCSI side for RRQ testing.
20585  *       The caller should pass NULL for ndlp on NVME side.
20586  *
20587  * Return codes:
20588  *   NULL - Error
20589  *   Pointer to lpfc_io_buf - Success
20590  **/
20591 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
20592 				    struct lpfc_nodelist *ndlp,
20593 				    u32 hwqid, int expedite)
20594 {
20595 	struct lpfc_sli4_hdw_queue *qp;
20596 	unsigned long iflag;
20597 	struct lpfc_io_buf *lpfc_cmd;
20598 
20599 	qp = &phba->sli4_hba.hdwq[hwqid];
20600 	lpfc_cmd = NULL;
20601 
20602 	if (phba->cfg_xri_rebalancing)
20603 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
20604 			phba, ndlp, hwqid, expedite);
20605 	else {
20606 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
20607 					  qp, alloc_xri_get);
20608 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
20609 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
20610 		if (!lpfc_cmd) {
20611 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
20612 					  qp, alloc_xri_put);
20613 			list_splice(&qp->lpfc_io_buf_list_put,
20614 				    &qp->lpfc_io_buf_list_get);
20615 			qp->get_io_bufs += qp->put_io_bufs;
20616 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
20617 			qp->put_io_bufs = 0;
20618 			spin_unlock(&qp->io_buf_list_put_lock);
20619 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
20620 			    expedite)
20621 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
20622 		}
20623 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
20624 	}
20625 
20626 	return lpfc_cmd;
20627 }
20628 
20629 /**
20630  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
20631  * @phba: The HBA for which this call is being executed.
20632  * @lpfc_buf: IO buf structure to append the SGL chunk
20633  *
20634  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
20635  * and will allocate an SGL chunk if the pool is empty.
20636  *
20637  * Return codes:
20638  *   NULL - Error
20639  *   Pointer to sli4_hybrid_sgl - Success
20640  **/
20641 struct sli4_hybrid_sgl *
20642 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
20643 {
20644 	struct sli4_hybrid_sgl *list_entry = NULL;
20645 	struct sli4_hybrid_sgl *tmp = NULL;
20646 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
20647 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20648 	struct list_head *buf_list = &hdwq->sgl_list;
20649 	unsigned long iflags;
20650 
20651 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20652 
20653 	if (likely(!list_empty(buf_list))) {
20654 		/* break off 1 chunk from the sgl_list */
20655 		list_for_each_entry_safe(list_entry, tmp,
20656 					 buf_list, list_node) {
20657 			list_move_tail(&list_entry->list_node,
20658 				       &lpfc_buf->dma_sgl_xtra_list);
20659 			break;
20660 		}
20661 	} else {
20662 		/* allocate more */
20663 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20664 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
20665 				   cpu_to_node(hdwq->io_wq->chann));
20666 		if (!tmp) {
20667 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20668 					"8353 error kmalloc memory for HDWQ "
20669 					"%d %s\n",
20670 					lpfc_buf->hdwq_no, __func__);
20671 			return NULL;
20672 		}
20673 
20674 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
20675 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
20676 		if (!tmp->dma_sgl) {
20677 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20678 					"8354 error pool_alloc memory for HDWQ "
20679 					"%d %s\n",
20680 					lpfc_buf->hdwq_no, __func__);
20681 			kfree(tmp);
20682 			return NULL;
20683 		}
20684 
20685 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20686 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
20687 	}
20688 
20689 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
20690 					struct sli4_hybrid_sgl,
20691 					list_node);
20692 
20693 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20694 
20695 	return allocated_sgl;
20696 }
20697 
20698 /**
20699  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
20700  * @phba: The HBA for which this call is being executed.
20701  * @lpfc_buf: IO buf structure with the SGL chunk
20702  *
20703  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
20704  *
20705  * Return codes:
20706  *   0 - Success
20707  *   -EINVAL - Error
20708  **/
20709 int
20710 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
20711 {
20712 	int rc = 0;
20713 	struct sli4_hybrid_sgl *list_entry = NULL;
20714 	struct sli4_hybrid_sgl *tmp = NULL;
20715 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20716 	struct list_head *buf_list = &hdwq->sgl_list;
20717 	unsigned long iflags;
20718 
20719 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20720 
20721 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
20722 		list_for_each_entry_safe(list_entry, tmp,
20723 					 &lpfc_buf->dma_sgl_xtra_list,
20724 					 list_node) {
20725 			list_move_tail(&list_entry->list_node,
20726 				       buf_list);
20727 		}
20728 	} else {
20729 		rc = -EINVAL;
20730 	}
20731 
20732 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20733 	return rc;
20734 }
20735 
20736 /**
20737  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
20738  * @phba: phba object
20739  * @hdwq: hdwq to cleanup sgl buff resources on
20740  *
20741  * This routine frees all SGL chunks of hdwq SGL chunk pool.
20742  *
20743  * Return codes:
20744  *   None
20745  **/
20746 void
20747 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
20748 		       struct lpfc_sli4_hdw_queue *hdwq)
20749 {
20750 	struct list_head *buf_list = &hdwq->sgl_list;
20751 	struct sli4_hybrid_sgl *list_entry = NULL;
20752 	struct sli4_hybrid_sgl *tmp = NULL;
20753 	unsigned long iflags;
20754 
20755 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20756 
20757 	/* Free sgl pool */
20758 	list_for_each_entry_safe(list_entry, tmp,
20759 				 buf_list, list_node) {
20760 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
20761 			      list_entry->dma_sgl,
20762 			      list_entry->dma_phys_sgl);
20763 		list_del(&list_entry->list_node);
20764 		kfree(list_entry);
20765 	}
20766 
20767 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20768 }
20769 
20770 /**
20771  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
20772  * @phba: The HBA for which this call is being executed.
20773  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
20774  *
20775  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
20776  * and will allocate an CMD/RSP buffer if the pool is empty.
20777  *
20778  * Return codes:
20779  *   NULL - Error
20780  *   Pointer to fcp_cmd_rsp_buf - Success
20781  **/
20782 struct fcp_cmd_rsp_buf *
20783 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
20784 			      struct lpfc_io_buf *lpfc_buf)
20785 {
20786 	struct fcp_cmd_rsp_buf *list_entry = NULL;
20787 	struct fcp_cmd_rsp_buf *tmp = NULL;
20788 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
20789 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20790 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
20791 	unsigned long iflags;
20792 
20793 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20794 
20795 	if (likely(!list_empty(buf_list))) {
20796 		/* break off 1 chunk from the list */
20797 		list_for_each_entry_safe(list_entry, tmp,
20798 					 buf_list,
20799 					 list_node) {
20800 			list_move_tail(&list_entry->list_node,
20801 				       &lpfc_buf->dma_cmd_rsp_list);
20802 			break;
20803 		}
20804 	} else {
20805 		/* allocate more */
20806 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20807 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
20808 				   cpu_to_node(hdwq->io_wq->chann));
20809 		if (!tmp) {
20810 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20811 					"8355 error kmalloc memory for HDWQ "
20812 					"%d %s\n",
20813 					lpfc_buf->hdwq_no, __func__);
20814 			return NULL;
20815 		}
20816 
20817 		tmp->fcp_cmnd = dma_pool_alloc(phba->lpfc_cmd_rsp_buf_pool,
20818 						GFP_ATOMIC,
20819 						&tmp->fcp_cmd_rsp_dma_handle);
20820 
20821 		if (!tmp->fcp_cmnd) {
20822 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20823 					"8356 error pool_alloc memory for HDWQ "
20824 					"%d %s\n",
20825 					lpfc_buf->hdwq_no, __func__);
20826 			kfree(tmp);
20827 			return NULL;
20828 		}
20829 
20830 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
20831 				sizeof(struct fcp_cmnd));
20832 
20833 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20834 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
20835 	}
20836 
20837 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
20838 					struct fcp_cmd_rsp_buf,
20839 					list_node);
20840 
20841 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20842 
20843 	return allocated_buf;
20844 }
20845 
20846 /**
20847  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
20848  * @phba: The HBA for which this call is being executed.
20849  * @lpfc_buf: IO buf structure with the CMD/RSP buf
20850  *
20851  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
20852  *
20853  * Return codes:
20854  *   0 - Success
20855  *   -EINVAL - Error
20856  **/
20857 int
20858 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
20859 			      struct lpfc_io_buf *lpfc_buf)
20860 {
20861 	int rc = 0;
20862 	struct fcp_cmd_rsp_buf *list_entry = NULL;
20863 	struct fcp_cmd_rsp_buf *tmp = NULL;
20864 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20865 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
20866 	unsigned long iflags;
20867 
20868 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20869 
20870 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
20871 		list_for_each_entry_safe(list_entry, tmp,
20872 					 &lpfc_buf->dma_cmd_rsp_list,
20873 					 list_node) {
20874 			list_move_tail(&list_entry->list_node,
20875 				       buf_list);
20876 		}
20877 	} else {
20878 		rc = -EINVAL;
20879 	}
20880 
20881 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20882 	return rc;
20883 }
20884 
20885 /**
20886  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
20887  * @phba: phba object
20888  * @hdwq: hdwq to cleanup cmd rsp buff resources on
20889  *
20890  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
20891  *
20892  * Return codes:
20893  *   None
20894  **/
20895 void
20896 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
20897 			       struct lpfc_sli4_hdw_queue *hdwq)
20898 {
20899 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
20900 	struct fcp_cmd_rsp_buf *list_entry = NULL;
20901 	struct fcp_cmd_rsp_buf *tmp = NULL;
20902 	unsigned long iflags;
20903 
20904 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20905 
20906 	/* Free cmd_rsp buf pool */
20907 	list_for_each_entry_safe(list_entry, tmp,
20908 				 buf_list,
20909 				 list_node) {
20910 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
20911 			      list_entry->fcp_cmnd,
20912 			      list_entry->fcp_cmd_rsp_dma_handle);
20913 		list_del(&list_entry->list_node);
20914 		kfree(list_entry);
20915 	}
20916 
20917 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20918 }
20919