xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision 4ed91d48259d9ddd378424d008f2e6559f7e78f8)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017 Broadcom. All Rights Reserved. The term      *
5  * “Broadcom” refers to Broadcom Limited 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 
39 #include <linux/nvme-fc-driver.h>
40 
41 #include "lpfc_hw4.h"
42 #include "lpfc_hw.h"
43 #include "lpfc_sli.h"
44 #include "lpfc_sli4.h"
45 #include "lpfc_nl.h"
46 #include "lpfc_disc.h"
47 #include "lpfc.h"
48 #include "lpfc_scsi.h"
49 #include "lpfc_nvme.h"
50 #include "lpfc_nvmet.h"
51 #include "lpfc_crtn.h"
52 #include "lpfc_logmsg.h"
53 #include "lpfc_compat.h"
54 #include "lpfc_debugfs.h"
55 #include "lpfc_vport.h"
56 #include "lpfc_version.h"
57 
58 /* There are only four IOCB completion types. */
59 typedef enum _lpfc_iocb_type {
60 	LPFC_UNKNOWN_IOCB,
61 	LPFC_UNSOL_IOCB,
62 	LPFC_SOL_IOCB,
63 	LPFC_ABORT_IOCB
64 } lpfc_iocb_type;
65 
66 
67 /* Provide function prototypes local to this module. */
68 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
69 				  uint32_t);
70 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
71 			      uint8_t *, uint32_t *);
72 static struct lpfc_iocbq *lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *,
73 							 struct lpfc_iocbq *);
74 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
75 				      struct hbq_dmabuf *);
76 static int lpfc_sli4_fp_handle_cqe(struct lpfc_hba *, struct lpfc_queue *,
77 				    struct lpfc_cqe *);
78 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
79 				       int);
80 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *, struct lpfc_eqe *,
81 			uint32_t);
82 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
83 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
84 static int lpfc_sli4_abort_nvme_io(struct lpfc_hba *phba,
85 				   struct lpfc_sli_ring *pring,
86 				   struct lpfc_iocbq *cmdiocb);
87 
88 static IOCB_t *
89 lpfc_get_iocb_from_iocbq(struct lpfc_iocbq *iocbq)
90 {
91 	return &iocbq->iocb;
92 }
93 
94 /**
95  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
96  * @q: The Work Queue to operate on.
97  * @wqe: The work Queue Entry to put on the Work queue.
98  *
99  * This routine will copy the contents of @wqe to the next available entry on
100  * the @q. This function will then ring the Work Queue Doorbell to signal the
101  * HBA to start processing the Work Queue Entry. This function returns 0 if
102  * successful. If no entries are available on @q then this function will return
103  * -ENOMEM.
104  * The caller is expected to hold the hbalock when calling this routine.
105  **/
106 static uint32_t
107 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe *wqe)
108 {
109 	union lpfc_wqe *temp_wqe;
110 	struct lpfc_register doorbell;
111 	uint32_t host_index;
112 	uint32_t idx;
113 
114 	/* sanity check on queue memory */
115 	if (unlikely(!q))
116 		return -ENOMEM;
117 	temp_wqe = q->qe[q->host_index].wqe;
118 
119 	/* If the host has not yet processed the next entry then we are done */
120 	idx = ((q->host_index + 1) % q->entry_count);
121 	if (idx == q->hba_index) {
122 		q->WQ_overflow++;
123 		return -ENOMEM;
124 	}
125 	q->WQ_posted++;
126 	/* set consumption flag every once in a while */
127 	if (!((q->host_index + 1) % q->entry_repost))
128 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
129 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
130 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
131 	lpfc_sli_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
132 	/* ensure WQE bcopy flushed before doorbell write */
133 	wmb();
134 
135 	/* Update the host index before invoking device */
136 	host_index = q->host_index;
137 
138 	q->host_index = idx;
139 
140 	/* Ring Doorbell */
141 	doorbell.word0 = 0;
142 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
143 		bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
144 		bf_set(lpfc_wq_db_list_fm_index, &doorbell, host_index);
145 		bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
146 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
147 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
148 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
149 	} else {
150 		return -EINVAL;
151 	}
152 	writel(doorbell.word0, q->db_regaddr);
153 
154 	return 0;
155 }
156 
157 /**
158  * lpfc_sli4_wq_release - Updates internal hba index for WQ
159  * @q: The Work Queue to operate on.
160  * @index: The index to advance the hba index to.
161  *
162  * This routine will update the HBA index of a queue to reflect consumption of
163  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
164  * an entry the host calls this function to update the queue's internal
165  * pointers. This routine returns the number of entries that were consumed by
166  * the HBA.
167  **/
168 static uint32_t
169 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
170 {
171 	uint32_t released = 0;
172 
173 	/* sanity check on queue memory */
174 	if (unlikely(!q))
175 		return 0;
176 
177 	if (q->hba_index == index)
178 		return 0;
179 	do {
180 		q->hba_index = ((q->hba_index + 1) % q->entry_count);
181 		released++;
182 	} while (q->hba_index != index);
183 	return released;
184 }
185 
186 /**
187  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
188  * @q: The Mailbox Queue to operate on.
189  * @wqe: The Mailbox Queue Entry to put on the Work queue.
190  *
191  * This routine will copy the contents of @mqe to the next available entry on
192  * the @q. This function will then ring the Work Queue Doorbell to signal the
193  * HBA to start processing the Work Queue Entry. This function returns 0 if
194  * successful. If no entries are available on @q then this function will return
195  * -ENOMEM.
196  * The caller is expected to hold the hbalock when calling this routine.
197  **/
198 static uint32_t
199 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
200 {
201 	struct lpfc_mqe *temp_mqe;
202 	struct lpfc_register doorbell;
203 
204 	/* sanity check on queue memory */
205 	if (unlikely(!q))
206 		return -ENOMEM;
207 	temp_mqe = q->qe[q->host_index].mqe;
208 
209 	/* If the host has not yet processed the next entry then we are done */
210 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
211 		return -ENOMEM;
212 	lpfc_sli_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
213 	/* Save off the mailbox pointer for completion */
214 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
215 
216 	/* Update the host index before invoking device */
217 	q->host_index = ((q->host_index + 1) % q->entry_count);
218 
219 	/* Ring Doorbell */
220 	doorbell.word0 = 0;
221 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
222 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
223 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
224 	return 0;
225 }
226 
227 /**
228  * lpfc_sli4_mq_release - Updates internal hba index for MQ
229  * @q: The Mailbox Queue to operate on.
230  *
231  * This routine will update the HBA index of a queue to reflect consumption of
232  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
233  * an entry the host calls this function to update the queue's internal
234  * pointers. This routine returns the number of entries that were consumed by
235  * the HBA.
236  **/
237 static uint32_t
238 lpfc_sli4_mq_release(struct lpfc_queue *q)
239 {
240 	/* sanity check on queue memory */
241 	if (unlikely(!q))
242 		return 0;
243 
244 	/* Clear the mailbox pointer for completion */
245 	q->phba->mbox = NULL;
246 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
247 	return 1;
248 }
249 
250 /**
251  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
252  * @q: The Event Queue to get the first valid EQE from
253  *
254  * This routine will get the first valid Event Queue Entry from @q, update
255  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
256  * the Queue (no more work to do), or the Queue is full of EQEs that have been
257  * processed, but not popped back to the HBA then this routine will return NULL.
258  **/
259 static struct lpfc_eqe *
260 lpfc_sli4_eq_get(struct lpfc_queue *q)
261 {
262 	struct lpfc_eqe *eqe;
263 	uint32_t idx;
264 
265 	/* sanity check on queue memory */
266 	if (unlikely(!q))
267 		return NULL;
268 	eqe = q->qe[q->hba_index].eqe;
269 
270 	/* If the next EQE is not valid then we are done */
271 	if (!bf_get_le32(lpfc_eqe_valid, eqe))
272 		return NULL;
273 	/* If the host has not yet processed the next entry then we are done */
274 	idx = ((q->hba_index + 1) % q->entry_count);
275 	if (idx == q->host_index)
276 		return NULL;
277 
278 	q->hba_index = idx;
279 
280 	/*
281 	 * insert barrier for instruction interlock : data from the hardware
282 	 * must have the valid bit checked before it can be copied and acted
283 	 * upon. Speculative instructions were allowing a bcopy at the start
284 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
285 	 * after our return, to copy data before the valid bit check above
286 	 * was done. As such, some of the copied data was stale. The barrier
287 	 * ensures the check is before any data is copied.
288 	 */
289 	mb();
290 	return eqe;
291 }
292 
293 /**
294  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
295  * @q: The Event Queue to disable interrupts
296  *
297  **/
298 static inline void
299 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
300 {
301 	struct lpfc_register doorbell;
302 
303 	doorbell.word0 = 0;
304 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
305 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
306 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
307 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
308 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
309 	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
310 }
311 
312 /**
313  * lpfc_sli4_eq_release - Indicates the host has finished processing an EQ
314  * @q: The Event Queue that the host has completed processing for.
315  * @arm: Indicates whether the host wants to arms this CQ.
316  *
317  * This routine will mark all Event Queue Entries on @q, from the last
318  * known completed entry to the last entry that was processed, as completed
319  * by clearing the valid bit for each completion queue entry. Then it will
320  * notify the HBA, by ringing the doorbell, that the EQEs have been processed.
321  * The internal host index in the @q will be updated by this routine to indicate
322  * that the host has finished processing the entries. The @arm parameter
323  * indicates that the queue should be rearmed when ringing the doorbell.
324  *
325  * This function will return the number of EQEs that were popped.
326  **/
327 uint32_t
328 lpfc_sli4_eq_release(struct lpfc_queue *q, bool arm)
329 {
330 	uint32_t released = 0;
331 	struct lpfc_eqe *temp_eqe;
332 	struct lpfc_register doorbell;
333 
334 	/* sanity check on queue memory */
335 	if (unlikely(!q))
336 		return 0;
337 
338 	/* while there are valid entries */
339 	while (q->hba_index != q->host_index) {
340 		temp_eqe = q->qe[q->host_index].eqe;
341 		bf_set_le32(lpfc_eqe_valid, temp_eqe, 0);
342 		released++;
343 		q->host_index = ((q->host_index + 1) % q->entry_count);
344 	}
345 	if (unlikely(released == 0 && !arm))
346 		return 0;
347 
348 	/* ring doorbell for number popped */
349 	doorbell.word0 = 0;
350 	if (arm) {
351 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
352 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
353 	}
354 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, released);
355 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
356 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
357 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
358 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
359 	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
360 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
361 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
362 		readl(q->phba->sli4_hba.EQCQDBregaddr);
363 	return released;
364 }
365 
366 /**
367  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
368  * @q: The Completion Queue to get the first valid CQE from
369  *
370  * This routine will get the first valid Completion Queue Entry from @q, update
371  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
372  * the Queue (no more work to do), or the Queue is full of CQEs that have been
373  * processed, but not popped back to the HBA then this routine will return NULL.
374  **/
375 static struct lpfc_cqe *
376 lpfc_sli4_cq_get(struct lpfc_queue *q)
377 {
378 	struct lpfc_cqe *cqe;
379 	uint32_t idx;
380 
381 	/* sanity check on queue memory */
382 	if (unlikely(!q))
383 		return NULL;
384 
385 	/* If the next CQE is not valid then we are done */
386 	if (!bf_get_le32(lpfc_cqe_valid, q->qe[q->hba_index].cqe))
387 		return NULL;
388 	/* If the host has not yet processed the next entry then we are done */
389 	idx = ((q->hba_index + 1) % q->entry_count);
390 	if (idx == q->host_index)
391 		return NULL;
392 
393 	cqe = q->qe[q->hba_index].cqe;
394 	q->hba_index = idx;
395 
396 	/*
397 	 * insert barrier for instruction interlock : data from the hardware
398 	 * must have the valid bit checked before it can be copied and acted
399 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
400 	 * instructions allowing action on content before valid bit checked,
401 	 * add barrier here as well. May not be needed as "content" is a
402 	 * single 32-bit entity here (vs multi word structure for cq's).
403 	 */
404 	mb();
405 	return cqe;
406 }
407 
408 /**
409  * lpfc_sli4_cq_release - Indicates the host has finished processing a CQ
410  * @q: The Completion Queue that the host has completed processing for.
411  * @arm: Indicates whether the host wants to arms this CQ.
412  *
413  * This routine will mark all Completion queue entries on @q, from the last
414  * known completed entry to the last entry that was processed, as completed
415  * by clearing the valid bit for each completion queue entry. Then it will
416  * notify the HBA, by ringing the doorbell, that the CQEs have been processed.
417  * The internal host index in the @q will be updated by this routine to indicate
418  * that the host has finished processing the entries. The @arm parameter
419  * indicates that the queue should be rearmed when ringing the doorbell.
420  *
421  * This function will return the number of CQEs that were released.
422  **/
423 uint32_t
424 lpfc_sli4_cq_release(struct lpfc_queue *q, bool arm)
425 {
426 	uint32_t released = 0;
427 	struct lpfc_cqe *temp_qe;
428 	struct lpfc_register doorbell;
429 
430 	/* sanity check on queue memory */
431 	if (unlikely(!q))
432 		return 0;
433 	/* while there are valid entries */
434 	while (q->hba_index != q->host_index) {
435 		temp_qe = q->qe[q->host_index].cqe;
436 		bf_set_le32(lpfc_cqe_valid, temp_qe, 0);
437 		released++;
438 		q->host_index = ((q->host_index + 1) % q->entry_count);
439 	}
440 	if (unlikely(released == 0 && !arm))
441 		return 0;
442 
443 	/* ring doorbell for number popped */
444 	doorbell.word0 = 0;
445 	if (arm)
446 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
447 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, released);
448 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
449 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
450 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
451 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
452 	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
453 	return released;
454 }
455 
456 /**
457  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
458  * @q: The Header Receive Queue to operate on.
459  * @wqe: The Receive Queue Entry to put on the Receive queue.
460  *
461  * This routine will copy the contents of @wqe to the next available entry on
462  * the @q. This function will then ring the Receive Queue Doorbell to signal the
463  * HBA to start processing the Receive Queue Entry. This function returns the
464  * index that the rqe was copied to if successful. If no entries are available
465  * on @q then this function will return -ENOMEM.
466  * The caller is expected to hold the hbalock when calling this routine.
467  **/
468 int
469 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
470 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
471 {
472 	struct lpfc_rqe *temp_hrqe;
473 	struct lpfc_rqe *temp_drqe;
474 	struct lpfc_register doorbell;
475 	int put_index;
476 
477 	/* sanity check on queue memory */
478 	if (unlikely(!hq) || unlikely(!dq))
479 		return -ENOMEM;
480 	put_index = hq->host_index;
481 	temp_hrqe = hq->qe[hq->host_index].rqe;
482 	temp_drqe = dq->qe[dq->host_index].rqe;
483 
484 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
485 		return -EINVAL;
486 	if (hq->host_index != dq->host_index)
487 		return -EINVAL;
488 	/* If the host has not yet processed the next entry then we are done */
489 	if (((hq->host_index + 1) % hq->entry_count) == hq->hba_index)
490 		return -EBUSY;
491 	lpfc_sli_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
492 	lpfc_sli_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
493 
494 	/* Update the host index to point to the next slot */
495 	hq->host_index = ((hq->host_index + 1) % hq->entry_count);
496 	dq->host_index = ((dq->host_index + 1) % dq->entry_count);
497 
498 	/* Ring The Header Receive Queue Doorbell */
499 	if (!(hq->host_index % hq->entry_repost)) {
500 		doorbell.word0 = 0;
501 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
502 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
503 			       hq->entry_repost);
504 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
505 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
506 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
507 			       hq->entry_repost);
508 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
509 			       hq->host_index);
510 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
511 		} else {
512 			return -EINVAL;
513 		}
514 		writel(doorbell.word0, hq->db_regaddr);
515 	}
516 	return put_index;
517 }
518 
519 /**
520  * lpfc_sli4_rq_release - Updates internal hba index for RQ
521  * @q: The Header Receive Queue to operate on.
522  *
523  * This routine will update the HBA index of a queue to reflect consumption of
524  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
525  * consumed an entry the host calls this function to update the queue's
526  * internal pointers. This routine returns the number of entries that were
527  * consumed by the HBA.
528  **/
529 static uint32_t
530 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
531 {
532 	/* sanity check on queue memory */
533 	if (unlikely(!hq) || unlikely(!dq))
534 		return 0;
535 
536 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
537 		return 0;
538 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
539 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
540 	return 1;
541 }
542 
543 /**
544  * lpfc_cmd_iocb - Get next command iocb entry in the ring
545  * @phba: Pointer to HBA context object.
546  * @pring: Pointer to driver SLI ring object.
547  *
548  * This function returns pointer to next command iocb entry
549  * in the command ring. The caller must hold hbalock to prevent
550  * other threads consume the next command iocb.
551  * SLI-2/SLI-3 provide different sized iocbs.
552  **/
553 static inline IOCB_t *
554 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
555 {
556 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
557 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
558 }
559 
560 /**
561  * lpfc_resp_iocb - Get next response iocb entry in the ring
562  * @phba: Pointer to HBA context object.
563  * @pring: Pointer to driver SLI ring object.
564  *
565  * This function returns pointer to next response iocb entry
566  * in the response ring. The caller must hold hbalock to make sure
567  * that no other thread consume the next response iocb.
568  * SLI-2/SLI-3 provide different sized iocbs.
569  **/
570 static inline IOCB_t *
571 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
572 {
573 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
574 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
575 }
576 
577 /**
578  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
579  * @phba: Pointer to HBA context object.
580  *
581  * This function is called with hbalock held. This function
582  * allocates a new driver iocb object from the iocb pool. If the
583  * allocation is successful, it returns pointer to the newly
584  * allocated iocb object else it returns NULL.
585  **/
586 struct lpfc_iocbq *
587 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
588 {
589 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
590 	struct lpfc_iocbq * iocbq = NULL;
591 
592 	lockdep_assert_held(&phba->hbalock);
593 
594 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
595 	if (iocbq)
596 		phba->iocb_cnt++;
597 	if (phba->iocb_cnt > phba->iocb_max)
598 		phba->iocb_max = phba->iocb_cnt;
599 	return iocbq;
600 }
601 
602 /**
603  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
604  * @phba: Pointer to HBA context object.
605  * @xritag: XRI value.
606  *
607  * This function clears the sglq pointer from the array of acive
608  * sglq's. The xritag that is passed in is used to index into the
609  * array. Before the xritag can be used it needs to be adjusted
610  * by subtracting the xribase.
611  *
612  * Returns sglq ponter = success, NULL = Failure.
613  **/
614 struct lpfc_sglq *
615 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
616 {
617 	struct lpfc_sglq *sglq;
618 
619 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
620 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
621 	return sglq;
622 }
623 
624 /**
625  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
626  * @phba: Pointer to HBA context object.
627  * @xritag: XRI value.
628  *
629  * This function returns the sglq pointer from the array of acive
630  * sglq's. The xritag that is passed in is used to index into the
631  * array. Before the xritag can be used it needs to be adjusted
632  * by subtracting the xribase.
633  *
634  * Returns sglq ponter = success, NULL = Failure.
635  **/
636 struct lpfc_sglq *
637 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
638 {
639 	struct lpfc_sglq *sglq;
640 
641 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
642 	return sglq;
643 }
644 
645 /**
646  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
647  * @phba: Pointer to HBA context object.
648  * @xritag: xri used in this exchange.
649  * @rrq: The RRQ to be cleared.
650  *
651  **/
652 void
653 lpfc_clr_rrq_active(struct lpfc_hba *phba,
654 		    uint16_t xritag,
655 		    struct lpfc_node_rrq *rrq)
656 {
657 	struct lpfc_nodelist *ndlp = NULL;
658 
659 	if ((rrq->vport) && NLP_CHK_NODE_ACT(rrq->ndlp))
660 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
661 
662 	/* The target DID could have been swapped (cable swap)
663 	 * we should use the ndlp from the findnode if it is
664 	 * available.
665 	 */
666 	if ((!ndlp) && rrq->ndlp)
667 		ndlp = rrq->ndlp;
668 
669 	if (!ndlp)
670 		goto out;
671 
672 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
673 		rrq->send_rrq = 0;
674 		rrq->xritag = 0;
675 		rrq->rrq_stop_time = 0;
676 	}
677 out:
678 	mempool_free(rrq, phba->rrq_pool);
679 }
680 
681 /**
682  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
683  * @phba: Pointer to HBA context object.
684  *
685  * This function is called with hbalock held. This function
686  * Checks if stop_time (ratov from setting rrq active) has
687  * been reached, if it has and the send_rrq flag is set then
688  * it will call lpfc_send_rrq. If the send_rrq flag is not set
689  * then it will just call the routine to clear the rrq and
690  * free the rrq resource.
691  * The timer is set to the next rrq that is going to expire before
692  * leaving the routine.
693  *
694  **/
695 void
696 lpfc_handle_rrq_active(struct lpfc_hba *phba)
697 {
698 	struct lpfc_node_rrq *rrq;
699 	struct lpfc_node_rrq *nextrrq;
700 	unsigned long next_time;
701 	unsigned long iflags;
702 	LIST_HEAD(send_rrq);
703 
704 	spin_lock_irqsave(&phba->hbalock, iflags);
705 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
706 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
707 	list_for_each_entry_safe(rrq, nextrrq,
708 				 &phba->active_rrq_list, list) {
709 		if (time_after(jiffies, rrq->rrq_stop_time))
710 			list_move(&rrq->list, &send_rrq);
711 		else if (time_before(rrq->rrq_stop_time, next_time))
712 			next_time = rrq->rrq_stop_time;
713 	}
714 	spin_unlock_irqrestore(&phba->hbalock, iflags);
715 	if ((!list_empty(&phba->active_rrq_list)) &&
716 	    (!(phba->pport->load_flag & FC_UNLOADING)))
717 		mod_timer(&phba->rrq_tmr, next_time);
718 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
719 		list_del(&rrq->list);
720 		if (!rrq->send_rrq)
721 			/* this call will free the rrq */
722 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
723 		else if (lpfc_send_rrq(phba, rrq)) {
724 			/* if we send the rrq then the completion handler
725 			*  will clear the bit in the xribitmap.
726 			*/
727 			lpfc_clr_rrq_active(phba, rrq->xritag,
728 					    rrq);
729 		}
730 	}
731 }
732 
733 /**
734  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
735  * @vport: Pointer to vport context object.
736  * @xri: The xri used in the exchange.
737  * @did: The targets DID for this exchange.
738  *
739  * returns NULL = rrq not found in the phba->active_rrq_list.
740  *         rrq = rrq for this xri and target.
741  **/
742 struct lpfc_node_rrq *
743 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
744 {
745 	struct lpfc_hba *phba = vport->phba;
746 	struct lpfc_node_rrq *rrq;
747 	struct lpfc_node_rrq *nextrrq;
748 	unsigned long iflags;
749 
750 	if (phba->sli_rev != LPFC_SLI_REV4)
751 		return NULL;
752 	spin_lock_irqsave(&phba->hbalock, iflags);
753 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
754 		if (rrq->vport == vport && rrq->xritag == xri &&
755 				rrq->nlp_DID == did){
756 			list_del(&rrq->list);
757 			spin_unlock_irqrestore(&phba->hbalock, iflags);
758 			return rrq;
759 		}
760 	}
761 	spin_unlock_irqrestore(&phba->hbalock, iflags);
762 	return NULL;
763 }
764 
765 /**
766  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
767  * @vport: Pointer to vport context object.
768  * @ndlp: Pointer to the lpfc_node_list structure.
769  * If ndlp is NULL Remove all active RRQs for this vport from the
770  * phba->active_rrq_list and clear the rrq.
771  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
772  **/
773 void
774 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
775 
776 {
777 	struct lpfc_hba *phba = vport->phba;
778 	struct lpfc_node_rrq *rrq;
779 	struct lpfc_node_rrq *nextrrq;
780 	unsigned long iflags;
781 	LIST_HEAD(rrq_list);
782 
783 	if (phba->sli_rev != LPFC_SLI_REV4)
784 		return;
785 	if (!ndlp) {
786 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
787 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
788 	}
789 	spin_lock_irqsave(&phba->hbalock, iflags);
790 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list)
791 		if ((rrq->vport == vport) && (!ndlp  || rrq->ndlp == ndlp))
792 			list_move(&rrq->list, &rrq_list);
793 	spin_unlock_irqrestore(&phba->hbalock, iflags);
794 
795 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
796 		list_del(&rrq->list);
797 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
798 	}
799 }
800 
801 /**
802  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
803  * @phba: Pointer to HBA context object.
804  * @ndlp: Targets nodelist pointer for this exchange.
805  * @xritag the xri in the bitmap to test.
806  *
807  * This function is called with hbalock held. This function
808  * returns 0 = rrq not active for this xri
809  *         1 = rrq is valid for this xri.
810  **/
811 int
812 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
813 			uint16_t  xritag)
814 {
815 	lockdep_assert_held(&phba->hbalock);
816 	if (!ndlp)
817 		return 0;
818 	if (!ndlp->active_rrqs_xri_bitmap)
819 		return 0;
820 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
821 			return 1;
822 	else
823 		return 0;
824 }
825 
826 /**
827  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
828  * @phba: Pointer to HBA context object.
829  * @ndlp: nodelist pointer for this target.
830  * @xritag: xri used in this exchange.
831  * @rxid: Remote Exchange ID.
832  * @send_rrq: Flag used to determine if we should send rrq els cmd.
833  *
834  * This function takes the hbalock.
835  * The active bit is always set in the active rrq xri_bitmap even
836  * if there is no slot avaiable for the other rrq information.
837  *
838  * returns 0 rrq actived for this xri
839  *         < 0 No memory or invalid ndlp.
840  **/
841 int
842 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
843 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
844 {
845 	unsigned long iflags;
846 	struct lpfc_node_rrq *rrq;
847 	int empty;
848 
849 	if (!ndlp)
850 		return -EINVAL;
851 
852 	if (!phba->cfg_enable_rrq)
853 		return -EINVAL;
854 
855 	spin_lock_irqsave(&phba->hbalock, iflags);
856 	if (phba->pport->load_flag & FC_UNLOADING) {
857 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
858 		goto out;
859 	}
860 
861 	/*
862 	 * set the active bit even if there is no mem available.
863 	 */
864 	if (NLP_CHK_FREE_REQ(ndlp))
865 		goto out;
866 
867 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
868 		goto out;
869 
870 	if (!ndlp->active_rrqs_xri_bitmap)
871 		goto out;
872 
873 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
874 		goto out;
875 
876 	spin_unlock_irqrestore(&phba->hbalock, iflags);
877 	rrq = mempool_alloc(phba->rrq_pool, GFP_KERNEL);
878 	if (!rrq) {
879 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
880 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
881 				" DID:0x%x Send:%d\n",
882 				xritag, rxid, ndlp->nlp_DID, send_rrq);
883 		return -EINVAL;
884 	}
885 	if (phba->cfg_enable_rrq == 1)
886 		rrq->send_rrq = send_rrq;
887 	else
888 		rrq->send_rrq = 0;
889 	rrq->xritag = xritag;
890 	rrq->rrq_stop_time = jiffies +
891 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
892 	rrq->ndlp = ndlp;
893 	rrq->nlp_DID = ndlp->nlp_DID;
894 	rrq->vport = ndlp->vport;
895 	rrq->rxid = rxid;
896 	spin_lock_irqsave(&phba->hbalock, iflags);
897 	empty = list_empty(&phba->active_rrq_list);
898 	list_add_tail(&rrq->list, &phba->active_rrq_list);
899 	phba->hba_flag |= HBA_RRQ_ACTIVE;
900 	if (empty)
901 		lpfc_worker_wake_up(phba);
902 	spin_unlock_irqrestore(&phba->hbalock, iflags);
903 	return 0;
904 out:
905 	spin_unlock_irqrestore(&phba->hbalock, iflags);
906 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
907 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
908 			" DID:0x%x Send:%d\n",
909 			xritag, rxid, ndlp->nlp_DID, send_rrq);
910 	return -EINVAL;
911 }
912 
913 /**
914  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
915  * @phba: Pointer to HBA context object.
916  * @piocb: Pointer to the iocbq.
917  *
918  * This function is called with the ring lock held. This function
919  * gets a new driver sglq object from the sglq list. If the
920  * list is not empty then it is successful, it returns pointer to the newly
921  * allocated sglq object else it returns NULL.
922  **/
923 static struct lpfc_sglq *
924 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
925 {
926 	struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
927 	struct lpfc_sglq *sglq = NULL;
928 	struct lpfc_sglq *start_sglq = NULL;
929 	struct lpfc_scsi_buf *lpfc_cmd;
930 	struct lpfc_nodelist *ndlp;
931 	int found = 0;
932 
933 	lockdep_assert_held(&phba->hbalock);
934 
935 	if (piocbq->iocb_flag &  LPFC_IO_FCP) {
936 		lpfc_cmd = (struct lpfc_scsi_buf *) piocbq->context1;
937 		ndlp = lpfc_cmd->rdata->pnode;
938 	} else  if ((piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) &&
939 			!(piocbq->iocb_flag & LPFC_IO_LIBDFC)) {
940 		ndlp = piocbq->context_un.ndlp;
941 	} else  if (piocbq->iocb_flag & LPFC_IO_LIBDFC) {
942 		if (piocbq->iocb_flag & LPFC_IO_LOOPBACK)
943 			ndlp = NULL;
944 		else
945 			ndlp = piocbq->context_un.ndlp;
946 	} else {
947 		ndlp = piocbq->context1;
948 	}
949 
950 	spin_lock(&phba->sli4_hba.sgl_list_lock);
951 	list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
952 	start_sglq = sglq;
953 	while (!found) {
954 		if (!sglq)
955 			return NULL;
956 		if (ndlp && ndlp->active_rrqs_xri_bitmap &&
957 		    test_bit(sglq->sli4_lxritag,
958 		    ndlp->active_rrqs_xri_bitmap)) {
959 			/* This xri has an rrq outstanding for this DID.
960 			 * put it back in the list and get another xri.
961 			 */
962 			list_add_tail(&sglq->list, lpfc_els_sgl_list);
963 			sglq = NULL;
964 			list_remove_head(lpfc_els_sgl_list, sglq,
965 						struct lpfc_sglq, list);
966 			if (sglq == start_sglq) {
967 				sglq = NULL;
968 				break;
969 			} else
970 				continue;
971 		}
972 		sglq->ndlp = ndlp;
973 		found = 1;
974 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
975 		sglq->state = SGL_ALLOCATED;
976 	}
977 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
978 	return sglq;
979 }
980 
981 /**
982  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
983  * @phba: Pointer to HBA context object.
984  * @piocb: Pointer to the iocbq.
985  *
986  * This function is called with the sgl_list lock held. This function
987  * gets a new driver sglq object from the sglq list. If the
988  * list is not empty then it is successful, it returns pointer to the newly
989  * allocated sglq object else it returns NULL.
990  **/
991 struct lpfc_sglq *
992 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
993 {
994 	struct list_head *lpfc_nvmet_sgl_list;
995 	struct lpfc_sglq *sglq = NULL;
996 
997 	lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
998 
999 	lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1000 
1001 	list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1002 	if (!sglq)
1003 		return NULL;
1004 	phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1005 	sglq->state = SGL_ALLOCATED;
1006 	return sglq;
1007 }
1008 
1009 /**
1010  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1011  * @phba: Pointer to HBA context object.
1012  *
1013  * This function is called with no lock held. This function
1014  * allocates a new driver iocb object from the iocb pool. If the
1015  * allocation is successful, it returns pointer to the newly
1016  * allocated iocb object else it returns NULL.
1017  **/
1018 struct lpfc_iocbq *
1019 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1020 {
1021 	struct lpfc_iocbq * iocbq = NULL;
1022 	unsigned long iflags;
1023 
1024 	spin_lock_irqsave(&phba->hbalock, iflags);
1025 	iocbq = __lpfc_sli_get_iocbq(phba);
1026 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1027 	return iocbq;
1028 }
1029 
1030 /**
1031  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1032  * @phba: Pointer to HBA context object.
1033  * @iocbq: Pointer to driver iocb object.
1034  *
1035  * This function is called with hbalock held to release driver
1036  * iocb object to the iocb pool. The iotag in the iocb object
1037  * does not change for each use of the iocb object. This function
1038  * clears all other fields of the iocb object when it is freed.
1039  * The sqlq structure that holds the xritag and phys and virtual
1040  * mappings for the scatter gather list is retrieved from the
1041  * active array of sglq. The get of the sglq pointer also clears
1042  * the entry in the array. If the status of the IO indiactes that
1043  * this IO was aborted then the sglq entry it put on the
1044  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1045  * IO has good status or fails for any other reason then the sglq
1046  * entry is added to the free list (lpfc_els_sgl_list).
1047  **/
1048 static void
1049 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1050 {
1051 	struct lpfc_sglq *sglq;
1052 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1053 	unsigned long iflag = 0;
1054 	struct lpfc_sli_ring *pring;
1055 
1056 	lockdep_assert_held(&phba->hbalock);
1057 
1058 	if (iocbq->sli4_xritag == NO_XRI)
1059 		sglq = NULL;
1060 	else
1061 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1062 
1063 
1064 	if (sglq)  {
1065 		if (iocbq->iocb_flag & LPFC_IO_NVMET) {
1066 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1067 					  iflag);
1068 			sglq->state = SGL_FREED;
1069 			sglq->ndlp = NULL;
1070 			list_add_tail(&sglq->list,
1071 				      &phba->sli4_hba.lpfc_nvmet_sgl_list);
1072 			spin_unlock_irqrestore(
1073 				&phba->sli4_hba.sgl_list_lock, iflag);
1074 			goto out;
1075 		}
1076 
1077 		pring = phba->sli4_hba.els_wq->pring;
1078 		if ((iocbq->iocb_flag & LPFC_EXCHANGE_BUSY) &&
1079 			(sglq->state != SGL_XRI_ABORTED)) {
1080 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1081 					  iflag);
1082 			list_add(&sglq->list,
1083 				 &phba->sli4_hba.lpfc_abts_els_sgl_list);
1084 			spin_unlock_irqrestore(
1085 				&phba->sli4_hba.sgl_list_lock, iflag);
1086 		} else {
1087 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1088 					  iflag);
1089 			sglq->state = SGL_FREED;
1090 			sglq->ndlp = NULL;
1091 			list_add_tail(&sglq->list,
1092 				      &phba->sli4_hba.lpfc_els_sgl_list);
1093 			spin_unlock_irqrestore(
1094 				&phba->sli4_hba.sgl_list_lock, iflag);
1095 
1096 			/* Check if TXQ queue needs to be serviced */
1097 			if (!list_empty(&pring->txq))
1098 				lpfc_worker_wake_up(phba);
1099 		}
1100 	}
1101 
1102 out:
1103 	/*
1104 	 * Clean all volatile data fields, preserve iotag and node struct.
1105 	 */
1106 	memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1107 	iocbq->sli4_lxritag = NO_XRI;
1108 	iocbq->sli4_xritag = NO_XRI;
1109 	iocbq->iocb_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET |
1110 			      LPFC_IO_NVME_LS);
1111 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1112 }
1113 
1114 
1115 /**
1116  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1117  * @phba: Pointer to HBA context object.
1118  * @iocbq: Pointer to driver iocb object.
1119  *
1120  * This function is called with hbalock held to release driver
1121  * iocb object to the iocb pool. The iotag in the iocb object
1122  * does not change for each use of the iocb object. This function
1123  * clears all other fields of the iocb object when it is freed.
1124  **/
1125 static void
1126 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1127 {
1128 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1129 
1130 	lockdep_assert_held(&phba->hbalock);
1131 
1132 	/*
1133 	 * Clean all volatile data fields, preserve iotag and node struct.
1134 	 */
1135 	memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1136 	iocbq->sli4_xritag = NO_XRI;
1137 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1138 }
1139 
1140 /**
1141  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1142  * @phba: Pointer to HBA context object.
1143  * @iocbq: Pointer to driver iocb object.
1144  *
1145  * This function is called with hbalock held to release driver
1146  * iocb object to the iocb pool. The iotag in the iocb object
1147  * does not change for each use of the iocb object. This function
1148  * clears all other fields of the iocb object when it is freed.
1149  **/
1150 static void
1151 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1152 {
1153 	lockdep_assert_held(&phba->hbalock);
1154 
1155 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1156 	phba->iocb_cnt--;
1157 }
1158 
1159 /**
1160  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1161  * @phba: Pointer to HBA context object.
1162  * @iocbq: Pointer to driver iocb object.
1163  *
1164  * This function is called with no lock held to release the iocb to
1165  * iocb pool.
1166  **/
1167 void
1168 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1169 {
1170 	unsigned long iflags;
1171 
1172 	/*
1173 	 * Clean all volatile data fields, preserve iotag and node struct.
1174 	 */
1175 	spin_lock_irqsave(&phba->hbalock, iflags);
1176 	__lpfc_sli_release_iocbq(phba, iocbq);
1177 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1178 }
1179 
1180 /**
1181  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1182  * @phba: Pointer to HBA context object.
1183  * @iocblist: List of IOCBs.
1184  * @ulpstatus: ULP status in IOCB command field.
1185  * @ulpWord4: ULP word-4 in IOCB command field.
1186  *
1187  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1188  * on the list by invoking the complete callback function associated with the
1189  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1190  * fields.
1191  **/
1192 void
1193 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1194 		      uint32_t ulpstatus, uint32_t ulpWord4)
1195 {
1196 	struct lpfc_iocbq *piocb;
1197 
1198 	while (!list_empty(iocblist)) {
1199 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1200 		if (!piocb->iocb_cmpl)
1201 			lpfc_sli_release_iocbq(phba, piocb);
1202 		else {
1203 			piocb->iocb.ulpStatus = ulpstatus;
1204 			piocb->iocb.un.ulpWord[4] = ulpWord4;
1205 			(piocb->iocb_cmpl) (phba, piocb, piocb);
1206 		}
1207 	}
1208 	return;
1209 }
1210 
1211 /**
1212  * lpfc_sli_iocb_cmd_type - Get the iocb type
1213  * @iocb_cmnd: iocb command code.
1214  *
1215  * This function is called by ring event handler function to get the iocb type.
1216  * This function translates the iocb command to an iocb command type used to
1217  * decide the final disposition of each completed IOCB.
1218  * The function returns
1219  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1220  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1221  * LPFC_ABORT_IOCB   if it is an abort iocb
1222  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1223  *
1224  * The caller is not required to hold any lock.
1225  **/
1226 static lpfc_iocb_type
1227 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1228 {
1229 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1230 
1231 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1232 		return 0;
1233 
1234 	switch (iocb_cmnd) {
1235 	case CMD_XMIT_SEQUENCE_CR:
1236 	case CMD_XMIT_SEQUENCE_CX:
1237 	case CMD_XMIT_BCAST_CN:
1238 	case CMD_XMIT_BCAST_CX:
1239 	case CMD_ELS_REQUEST_CR:
1240 	case CMD_ELS_REQUEST_CX:
1241 	case CMD_CREATE_XRI_CR:
1242 	case CMD_CREATE_XRI_CX:
1243 	case CMD_GET_RPI_CN:
1244 	case CMD_XMIT_ELS_RSP_CX:
1245 	case CMD_GET_RPI_CR:
1246 	case CMD_FCP_IWRITE_CR:
1247 	case CMD_FCP_IWRITE_CX:
1248 	case CMD_FCP_IREAD_CR:
1249 	case CMD_FCP_IREAD_CX:
1250 	case CMD_FCP_ICMND_CR:
1251 	case CMD_FCP_ICMND_CX:
1252 	case CMD_FCP_TSEND_CX:
1253 	case CMD_FCP_TRSP_CX:
1254 	case CMD_FCP_TRECEIVE_CX:
1255 	case CMD_FCP_AUTO_TRSP_CX:
1256 	case CMD_ADAPTER_MSG:
1257 	case CMD_ADAPTER_DUMP:
1258 	case CMD_XMIT_SEQUENCE64_CR:
1259 	case CMD_XMIT_SEQUENCE64_CX:
1260 	case CMD_XMIT_BCAST64_CN:
1261 	case CMD_XMIT_BCAST64_CX:
1262 	case CMD_ELS_REQUEST64_CR:
1263 	case CMD_ELS_REQUEST64_CX:
1264 	case CMD_FCP_IWRITE64_CR:
1265 	case CMD_FCP_IWRITE64_CX:
1266 	case CMD_FCP_IREAD64_CR:
1267 	case CMD_FCP_IREAD64_CX:
1268 	case CMD_FCP_ICMND64_CR:
1269 	case CMD_FCP_ICMND64_CX:
1270 	case CMD_FCP_TSEND64_CX:
1271 	case CMD_FCP_TRSP64_CX:
1272 	case CMD_FCP_TRECEIVE64_CX:
1273 	case CMD_GEN_REQUEST64_CR:
1274 	case CMD_GEN_REQUEST64_CX:
1275 	case CMD_XMIT_ELS_RSP64_CX:
1276 	case DSSCMD_IWRITE64_CR:
1277 	case DSSCMD_IWRITE64_CX:
1278 	case DSSCMD_IREAD64_CR:
1279 	case DSSCMD_IREAD64_CX:
1280 		type = LPFC_SOL_IOCB;
1281 		break;
1282 	case CMD_ABORT_XRI_CN:
1283 	case CMD_ABORT_XRI_CX:
1284 	case CMD_CLOSE_XRI_CN:
1285 	case CMD_CLOSE_XRI_CX:
1286 	case CMD_XRI_ABORTED_CX:
1287 	case CMD_ABORT_MXRI64_CN:
1288 	case CMD_XMIT_BLS_RSP64_CX:
1289 		type = LPFC_ABORT_IOCB;
1290 		break;
1291 	case CMD_RCV_SEQUENCE_CX:
1292 	case CMD_RCV_ELS_REQ_CX:
1293 	case CMD_RCV_SEQUENCE64_CX:
1294 	case CMD_RCV_ELS_REQ64_CX:
1295 	case CMD_ASYNC_STATUS:
1296 	case CMD_IOCB_RCV_SEQ64_CX:
1297 	case CMD_IOCB_RCV_ELS64_CX:
1298 	case CMD_IOCB_RCV_CONT64_CX:
1299 	case CMD_IOCB_RET_XRI64_CX:
1300 		type = LPFC_UNSOL_IOCB;
1301 		break;
1302 	case CMD_IOCB_XMIT_MSEQ64_CR:
1303 	case CMD_IOCB_XMIT_MSEQ64_CX:
1304 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1305 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1306 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1307 	case CMD_IOCB_ABORT_EXTENDED_CN:
1308 	case CMD_IOCB_RET_HBQE64_CN:
1309 	case CMD_IOCB_FCP_IBIDIR64_CR:
1310 	case CMD_IOCB_FCP_IBIDIR64_CX:
1311 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1312 	case CMD_IOCB_LOGENTRY_CN:
1313 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1314 		printk("%s - Unhandled SLI-3 Command x%x\n",
1315 				__func__, iocb_cmnd);
1316 		type = LPFC_UNKNOWN_IOCB;
1317 		break;
1318 	default:
1319 		type = LPFC_UNKNOWN_IOCB;
1320 		break;
1321 	}
1322 
1323 	return type;
1324 }
1325 
1326 /**
1327  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1328  * @phba: Pointer to HBA context object.
1329  *
1330  * This function is called from SLI initialization code
1331  * to configure every ring of the HBA's SLI interface. The
1332  * caller is not required to hold any lock. This function issues
1333  * a config_ring mailbox command for each ring.
1334  * This function returns zero if successful else returns a negative
1335  * error code.
1336  **/
1337 static int
1338 lpfc_sli_ring_map(struct lpfc_hba *phba)
1339 {
1340 	struct lpfc_sli *psli = &phba->sli;
1341 	LPFC_MBOXQ_t *pmb;
1342 	MAILBOX_t *pmbox;
1343 	int i, rc, ret = 0;
1344 
1345 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1346 	if (!pmb)
1347 		return -ENOMEM;
1348 	pmbox = &pmb->u.mb;
1349 	phba->link_state = LPFC_INIT_MBX_CMDS;
1350 	for (i = 0; i < psli->num_rings; i++) {
1351 		lpfc_config_ring(phba, i, pmb);
1352 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1353 		if (rc != MBX_SUCCESS) {
1354 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1355 					"0446 Adapter failed to init (%d), "
1356 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1357 					"ring %d\n",
1358 					rc, pmbox->mbxCommand,
1359 					pmbox->mbxStatus, i);
1360 			phba->link_state = LPFC_HBA_ERROR;
1361 			ret = -ENXIO;
1362 			break;
1363 		}
1364 	}
1365 	mempool_free(pmb, phba->mbox_mem_pool);
1366 	return ret;
1367 }
1368 
1369 /**
1370  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1371  * @phba: Pointer to HBA context object.
1372  * @pring: Pointer to driver SLI ring object.
1373  * @piocb: Pointer to the driver iocb object.
1374  *
1375  * This function is called with hbalock held. The function adds the
1376  * new iocb to txcmplq of the given ring. This function always returns
1377  * 0. If this function is called for ELS ring, this function checks if
1378  * there is a vport associated with the ELS command. This function also
1379  * starts els_tmofunc timer if this is an ELS command.
1380  **/
1381 static int
1382 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1383 			struct lpfc_iocbq *piocb)
1384 {
1385 	lockdep_assert_held(&phba->hbalock);
1386 
1387 	BUG_ON(!piocb);
1388 
1389 	list_add_tail(&piocb->list, &pring->txcmplq);
1390 	piocb->iocb_flag |= LPFC_IO_ON_TXCMPLQ;
1391 
1392 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1393 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
1394 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
1395 		BUG_ON(!piocb->vport);
1396 		if (!(piocb->vport->load_flag & FC_UNLOADING))
1397 			mod_timer(&piocb->vport->els_tmofunc,
1398 				  jiffies +
1399 				  msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1400 	}
1401 
1402 	return 0;
1403 }
1404 
1405 /**
1406  * lpfc_sli_ringtx_get - Get first element of the txq
1407  * @phba: Pointer to HBA context object.
1408  * @pring: Pointer to driver SLI ring object.
1409  *
1410  * This function is called with hbalock held to get next
1411  * iocb in txq of the given ring. If there is any iocb in
1412  * the txq, the function returns first iocb in the list after
1413  * removing the iocb from the list, else it returns NULL.
1414  **/
1415 struct lpfc_iocbq *
1416 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1417 {
1418 	struct lpfc_iocbq *cmd_iocb;
1419 
1420 	lockdep_assert_held(&phba->hbalock);
1421 
1422 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1423 	return cmd_iocb;
1424 }
1425 
1426 /**
1427  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
1428  * @phba: Pointer to HBA context object.
1429  * @pring: Pointer to driver SLI ring object.
1430  *
1431  * This function is called with hbalock held and the caller must post the
1432  * iocb without releasing the lock. If the caller releases the lock,
1433  * iocb slot returned by the function is not guaranteed to be available.
1434  * The function returns pointer to the next available iocb slot if there
1435  * is available slot in the ring, else it returns NULL.
1436  * If the get index of the ring is ahead of the put index, the function
1437  * will post an error attention event to the worker thread to take the
1438  * HBA to offline state.
1439  **/
1440 static IOCB_t *
1441 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1442 {
1443 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
1444 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
1445 
1446 	lockdep_assert_held(&phba->hbalock);
1447 
1448 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
1449 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
1450 		pring->sli.sli3.next_cmdidx = 0;
1451 
1452 	if (unlikely(pring->sli.sli3.local_getidx ==
1453 		pring->sli.sli3.next_cmdidx)) {
1454 
1455 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
1456 
1457 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
1458 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1459 					"0315 Ring %d issue: portCmdGet %d "
1460 					"is bigger than cmd ring %d\n",
1461 					pring->ringno,
1462 					pring->sli.sli3.local_getidx,
1463 					max_cmd_idx);
1464 
1465 			phba->link_state = LPFC_HBA_ERROR;
1466 			/*
1467 			 * All error attention handlers are posted to
1468 			 * worker thread
1469 			 */
1470 			phba->work_ha |= HA_ERATT;
1471 			phba->work_hs = HS_FFER3;
1472 
1473 			lpfc_worker_wake_up(phba);
1474 
1475 			return NULL;
1476 		}
1477 
1478 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
1479 			return NULL;
1480 	}
1481 
1482 	return lpfc_cmd_iocb(phba, pring);
1483 }
1484 
1485 /**
1486  * lpfc_sli_next_iotag - Get an iotag for the iocb
1487  * @phba: Pointer to HBA context object.
1488  * @iocbq: Pointer to driver iocb object.
1489  *
1490  * This function gets an iotag for the iocb. If there is no unused iotag and
1491  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
1492  * array and assigns a new iotag.
1493  * The function returns the allocated iotag if successful, else returns zero.
1494  * Zero is not a valid iotag.
1495  * The caller is not required to hold any lock.
1496  **/
1497 uint16_t
1498 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1499 {
1500 	struct lpfc_iocbq **new_arr;
1501 	struct lpfc_iocbq **old_arr;
1502 	size_t new_len;
1503 	struct lpfc_sli *psli = &phba->sli;
1504 	uint16_t iotag;
1505 
1506 	spin_lock_irq(&phba->hbalock);
1507 	iotag = psli->last_iotag;
1508 	if(++iotag < psli->iocbq_lookup_len) {
1509 		psli->last_iotag = iotag;
1510 		psli->iocbq_lookup[iotag] = iocbq;
1511 		spin_unlock_irq(&phba->hbalock);
1512 		iocbq->iotag = iotag;
1513 		return iotag;
1514 	} else if (psli->iocbq_lookup_len < (0xffff
1515 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
1516 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
1517 		spin_unlock_irq(&phba->hbalock);
1518 		new_arr = kzalloc(new_len * sizeof (struct lpfc_iocbq *),
1519 				  GFP_KERNEL);
1520 		if (new_arr) {
1521 			spin_lock_irq(&phba->hbalock);
1522 			old_arr = psli->iocbq_lookup;
1523 			if (new_len <= psli->iocbq_lookup_len) {
1524 				/* highly unprobable case */
1525 				kfree(new_arr);
1526 				iotag = psli->last_iotag;
1527 				if(++iotag < psli->iocbq_lookup_len) {
1528 					psli->last_iotag = iotag;
1529 					psli->iocbq_lookup[iotag] = iocbq;
1530 					spin_unlock_irq(&phba->hbalock);
1531 					iocbq->iotag = iotag;
1532 					return iotag;
1533 				}
1534 				spin_unlock_irq(&phba->hbalock);
1535 				return 0;
1536 			}
1537 			if (psli->iocbq_lookup)
1538 				memcpy(new_arr, old_arr,
1539 				       ((psli->last_iotag  + 1) *
1540 					sizeof (struct lpfc_iocbq *)));
1541 			psli->iocbq_lookup = new_arr;
1542 			psli->iocbq_lookup_len = new_len;
1543 			psli->last_iotag = iotag;
1544 			psli->iocbq_lookup[iotag] = iocbq;
1545 			spin_unlock_irq(&phba->hbalock);
1546 			iocbq->iotag = iotag;
1547 			kfree(old_arr);
1548 			return iotag;
1549 		}
1550 	} else
1551 		spin_unlock_irq(&phba->hbalock);
1552 
1553 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
1554 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
1555 			psli->last_iotag);
1556 
1557 	return 0;
1558 }
1559 
1560 /**
1561  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
1562  * @phba: Pointer to HBA context object.
1563  * @pring: Pointer to driver SLI ring object.
1564  * @iocb: Pointer to iocb slot in the ring.
1565  * @nextiocb: Pointer to driver iocb object which need to be
1566  *            posted to firmware.
1567  *
1568  * This function is called with hbalock held to post a new iocb to
1569  * the firmware. This function copies the new iocb to ring iocb slot and
1570  * updates the ring pointers. It adds the new iocb to txcmplq if there is
1571  * a completion call back for this iocb else the function will free the
1572  * iocb object.
1573  **/
1574 static void
1575 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1576 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
1577 {
1578 	lockdep_assert_held(&phba->hbalock);
1579 	/*
1580 	 * Set up an iotag
1581 	 */
1582 	nextiocb->iocb.ulpIoTag = (nextiocb->iocb_cmpl) ? nextiocb->iotag : 0;
1583 
1584 
1585 	if (pring->ringno == LPFC_ELS_RING) {
1586 		lpfc_debugfs_slow_ring_trc(phba,
1587 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
1588 			*(((uint32_t *) &nextiocb->iocb) + 4),
1589 			*(((uint32_t *) &nextiocb->iocb) + 6),
1590 			*(((uint32_t *) &nextiocb->iocb) + 7));
1591 	}
1592 
1593 	/*
1594 	 * Issue iocb command to adapter
1595 	 */
1596 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
1597 	wmb();
1598 	pring->stats.iocb_cmd++;
1599 
1600 	/*
1601 	 * If there is no completion routine to call, we can release the
1602 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
1603 	 * that have no rsp ring completion, iocb_cmpl MUST be NULL.
1604 	 */
1605 	if (nextiocb->iocb_cmpl)
1606 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
1607 	else
1608 		__lpfc_sli_release_iocbq(phba, nextiocb);
1609 
1610 	/*
1611 	 * Let the HBA know what IOCB slot will be the next one the
1612 	 * driver will put a command into.
1613 	 */
1614 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
1615 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
1616 }
1617 
1618 /**
1619  * lpfc_sli_update_full_ring - Update the chip attention register
1620  * @phba: Pointer to HBA context object.
1621  * @pring: Pointer to driver SLI ring object.
1622  *
1623  * The caller is not required to hold any lock for calling this function.
1624  * This function updates the chip attention bits for the ring to inform firmware
1625  * that there are pending work to be done for this ring and requests an
1626  * interrupt when there is space available in the ring. This function is
1627  * called when the driver is unable to post more iocbs to the ring due
1628  * to unavailability of space in the ring.
1629  **/
1630 static void
1631 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1632 {
1633 	int ringno = pring->ringno;
1634 
1635 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
1636 
1637 	wmb();
1638 
1639 	/*
1640 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
1641 	 * The HBA will tell us when an IOCB entry is available.
1642 	 */
1643 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
1644 	readl(phba->CAregaddr); /* flush */
1645 
1646 	pring->stats.iocb_cmd_full++;
1647 }
1648 
1649 /**
1650  * lpfc_sli_update_ring - Update chip attention register
1651  * @phba: Pointer to HBA context object.
1652  * @pring: Pointer to driver SLI ring object.
1653  *
1654  * This function updates the chip attention register bit for the
1655  * given ring to inform HBA that there is more work to be done
1656  * in this ring. The caller is not required to hold any lock.
1657  **/
1658 static void
1659 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1660 {
1661 	int ringno = pring->ringno;
1662 
1663 	/*
1664 	 * Tell the HBA that there is work to do in this ring.
1665 	 */
1666 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
1667 		wmb();
1668 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
1669 		readl(phba->CAregaddr); /* flush */
1670 	}
1671 }
1672 
1673 /**
1674  * lpfc_sli_resume_iocb - Process iocbs in the txq
1675  * @phba: Pointer to HBA context object.
1676  * @pring: Pointer to driver SLI ring object.
1677  *
1678  * This function is called with hbalock held to post pending iocbs
1679  * in the txq to the firmware. This function is called when driver
1680  * detects space available in the ring.
1681  **/
1682 static void
1683 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1684 {
1685 	IOCB_t *iocb;
1686 	struct lpfc_iocbq *nextiocb;
1687 
1688 	lockdep_assert_held(&phba->hbalock);
1689 
1690 	/*
1691 	 * Check to see if:
1692 	 *  (a) there is anything on the txq to send
1693 	 *  (b) link is up
1694 	 *  (c) link attention events can be processed (fcp ring only)
1695 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
1696 	 */
1697 
1698 	if (lpfc_is_link_up(phba) &&
1699 	    (!list_empty(&pring->txq)) &&
1700 	    (pring->ringno != LPFC_FCP_RING ||
1701 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
1702 
1703 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
1704 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
1705 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
1706 
1707 		if (iocb)
1708 			lpfc_sli_update_ring(phba, pring);
1709 		else
1710 			lpfc_sli_update_full_ring(phba, pring);
1711 	}
1712 
1713 	return;
1714 }
1715 
1716 /**
1717  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
1718  * @phba: Pointer to HBA context object.
1719  * @hbqno: HBQ number.
1720  *
1721  * This function is called with hbalock held to get the next
1722  * available slot for the given HBQ. If there is free slot
1723  * available for the HBQ it will return pointer to the next available
1724  * HBQ entry else it will return NULL.
1725  **/
1726 static struct lpfc_hbq_entry *
1727 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
1728 {
1729 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
1730 
1731 	lockdep_assert_held(&phba->hbalock);
1732 
1733 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
1734 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
1735 		hbqp->next_hbqPutIdx = 0;
1736 
1737 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
1738 		uint32_t raw_index = phba->hbq_get[hbqno];
1739 		uint32_t getidx = le32_to_cpu(raw_index);
1740 
1741 		hbqp->local_hbqGetIdx = getidx;
1742 
1743 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
1744 			lpfc_printf_log(phba, KERN_ERR,
1745 					LOG_SLI | LOG_VPORT,
1746 					"1802 HBQ %d: local_hbqGetIdx "
1747 					"%u is > than hbqp->entry_count %u\n",
1748 					hbqno, hbqp->local_hbqGetIdx,
1749 					hbqp->entry_count);
1750 
1751 			phba->link_state = LPFC_HBA_ERROR;
1752 			return NULL;
1753 		}
1754 
1755 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
1756 			return NULL;
1757 	}
1758 
1759 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
1760 			hbqp->hbqPutIdx;
1761 }
1762 
1763 /**
1764  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
1765  * @phba: Pointer to HBA context object.
1766  *
1767  * This function is called with no lock held to free all the
1768  * hbq buffers while uninitializing the SLI interface. It also
1769  * frees the HBQ buffers returned by the firmware but not yet
1770  * processed by the upper layers.
1771  **/
1772 void
1773 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
1774 {
1775 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
1776 	struct hbq_dmabuf *hbq_buf;
1777 	unsigned long flags;
1778 	int i, hbq_count;
1779 
1780 	hbq_count = lpfc_sli_hbq_count();
1781 	/* Return all memory used by all HBQs */
1782 	spin_lock_irqsave(&phba->hbalock, flags);
1783 	for (i = 0; i < hbq_count; ++i) {
1784 		list_for_each_entry_safe(dmabuf, next_dmabuf,
1785 				&phba->hbqs[i].hbq_buffer_list, list) {
1786 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
1787 			list_del(&hbq_buf->dbuf.list);
1788 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
1789 		}
1790 		phba->hbqs[i].buffer_count = 0;
1791 	}
1792 
1793 	/* Mark the HBQs not in use */
1794 	phba->hbq_in_use = 0;
1795 	spin_unlock_irqrestore(&phba->hbalock, flags);
1796 }
1797 
1798 /**
1799  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
1800  * @phba: Pointer to HBA context object.
1801  * @hbqno: HBQ number.
1802  * @hbq_buf: Pointer to HBQ buffer.
1803  *
1804  * This function is called with the hbalock held to post a
1805  * hbq buffer to the firmware. If the function finds an empty
1806  * slot in the HBQ, it will post the buffer. The function will return
1807  * pointer to the hbq entry if it successfully post the buffer
1808  * else it will return NULL.
1809  **/
1810 static int
1811 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
1812 			 struct hbq_dmabuf *hbq_buf)
1813 {
1814 	lockdep_assert_held(&phba->hbalock);
1815 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
1816 }
1817 
1818 /**
1819  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
1820  * @phba: Pointer to HBA context object.
1821  * @hbqno: HBQ number.
1822  * @hbq_buf: Pointer to HBQ buffer.
1823  *
1824  * This function is called with the hbalock held to post a hbq buffer to the
1825  * firmware. If the function finds an empty slot in the HBQ, it will post the
1826  * buffer and place it on the hbq_buffer_list. The function will return zero if
1827  * it successfully post the buffer else it will return an error.
1828  **/
1829 static int
1830 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
1831 			    struct hbq_dmabuf *hbq_buf)
1832 {
1833 	struct lpfc_hbq_entry *hbqe;
1834 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
1835 
1836 	lockdep_assert_held(&phba->hbalock);
1837 	/* Get next HBQ entry slot to use */
1838 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
1839 	if (hbqe) {
1840 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
1841 
1842 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
1843 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
1844 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
1845 		hbqe->bde.tus.f.bdeFlags = 0;
1846 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
1847 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
1848 				/* Sync SLIM */
1849 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
1850 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
1851 				/* flush */
1852 		readl(phba->hbq_put + hbqno);
1853 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
1854 		return 0;
1855 	} else
1856 		return -ENOMEM;
1857 }
1858 
1859 /**
1860  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
1861  * @phba: Pointer to HBA context object.
1862  * @hbqno: HBQ number.
1863  * @hbq_buf: Pointer to HBQ buffer.
1864  *
1865  * This function is called with the hbalock held to post an RQE to the SLI4
1866  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
1867  * the hbq_buffer_list and return zero, otherwise it will return an error.
1868  **/
1869 static int
1870 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
1871 			    struct hbq_dmabuf *hbq_buf)
1872 {
1873 	int rc;
1874 	struct lpfc_rqe hrqe;
1875 	struct lpfc_rqe drqe;
1876 	struct lpfc_queue *hrq;
1877 	struct lpfc_queue *drq;
1878 
1879 	if (hbqno != LPFC_ELS_HBQ)
1880 		return 1;
1881 	hrq = phba->sli4_hba.hdr_rq;
1882 	drq = phba->sli4_hba.dat_rq;
1883 
1884 	lockdep_assert_held(&phba->hbalock);
1885 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
1886 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
1887 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
1888 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
1889 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
1890 	if (rc < 0)
1891 		return rc;
1892 	hbq_buf->tag = (rc | (hbqno << 16));
1893 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
1894 	return 0;
1895 }
1896 
1897 /* HBQ for ELS and CT traffic. */
1898 static struct lpfc_hbq_init lpfc_els_hbq = {
1899 	.rn = 1,
1900 	.entry_count = 256,
1901 	.mask_count = 0,
1902 	.profile = 0,
1903 	.ring_mask = (1 << LPFC_ELS_RING),
1904 	.buffer_count = 0,
1905 	.init_count = 40,
1906 	.add_count = 40,
1907 };
1908 
1909 /* Array of HBQs */
1910 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
1911 	&lpfc_els_hbq,
1912 };
1913 
1914 /**
1915  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
1916  * @phba: Pointer to HBA context object.
1917  * @hbqno: HBQ number.
1918  * @count: Number of HBQ buffers to be posted.
1919  *
1920  * This function is called with no lock held to post more hbq buffers to the
1921  * given HBQ. The function returns the number of HBQ buffers successfully
1922  * posted.
1923  **/
1924 static int
1925 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
1926 {
1927 	uint32_t i, posted = 0;
1928 	unsigned long flags;
1929 	struct hbq_dmabuf *hbq_buffer;
1930 	LIST_HEAD(hbq_buf_list);
1931 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
1932 		return 0;
1933 
1934 	if ((phba->hbqs[hbqno].buffer_count + count) >
1935 	    lpfc_hbq_defs[hbqno]->entry_count)
1936 		count = lpfc_hbq_defs[hbqno]->entry_count -
1937 					phba->hbqs[hbqno].buffer_count;
1938 	if (!count)
1939 		return 0;
1940 	/* Allocate HBQ entries */
1941 	for (i = 0; i < count; i++) {
1942 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
1943 		if (!hbq_buffer)
1944 			break;
1945 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
1946 	}
1947 	/* Check whether HBQ is still in use */
1948 	spin_lock_irqsave(&phba->hbalock, flags);
1949 	if (!phba->hbq_in_use)
1950 		goto err;
1951 	while (!list_empty(&hbq_buf_list)) {
1952 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
1953 				 dbuf.list);
1954 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
1955 				      (hbqno << 16));
1956 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
1957 			phba->hbqs[hbqno].buffer_count++;
1958 			posted++;
1959 		} else
1960 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
1961 	}
1962 	spin_unlock_irqrestore(&phba->hbalock, flags);
1963 	return posted;
1964 err:
1965 	spin_unlock_irqrestore(&phba->hbalock, flags);
1966 	while (!list_empty(&hbq_buf_list)) {
1967 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
1968 				 dbuf.list);
1969 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
1970 	}
1971 	return 0;
1972 }
1973 
1974 /**
1975  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
1976  * @phba: Pointer to HBA context object.
1977  * @qno: HBQ number.
1978  *
1979  * This function posts more buffers to the HBQ. This function
1980  * is called with no lock held. The function returns the number of HBQ entries
1981  * successfully allocated.
1982  **/
1983 int
1984 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
1985 {
1986 	if (phba->sli_rev == LPFC_SLI_REV4)
1987 		return 0;
1988 	else
1989 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
1990 					 lpfc_hbq_defs[qno]->add_count);
1991 }
1992 
1993 /**
1994  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
1995  * @phba: Pointer to HBA context object.
1996  * @qno:  HBQ queue number.
1997  *
1998  * This function is called from SLI initialization code path with
1999  * no lock held to post initial HBQ buffers to firmware. The
2000  * function returns the number of HBQ entries successfully allocated.
2001  **/
2002 static int
2003 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2004 {
2005 	if (phba->sli_rev == LPFC_SLI_REV4)
2006 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2007 					lpfc_hbq_defs[qno]->entry_count);
2008 	else
2009 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2010 					 lpfc_hbq_defs[qno]->init_count);
2011 }
2012 
2013 /**
2014  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2015  * @phba: Pointer to HBA context object.
2016  * @hbqno: HBQ number.
2017  *
2018  * This function removes the first hbq buffer on an hbq list and returns a
2019  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2020  **/
2021 static struct hbq_dmabuf *
2022 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2023 {
2024 	struct lpfc_dmabuf *d_buf;
2025 
2026 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2027 	if (!d_buf)
2028 		return NULL;
2029 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2030 }
2031 
2032 /**
2033  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2034  * @phba: Pointer to HBA context object.
2035  * @hbqno: HBQ number.
2036  *
2037  * This function removes the first RQ buffer on an RQ buffer list and returns a
2038  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2039  **/
2040 static struct rqb_dmabuf *
2041 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2042 {
2043 	struct lpfc_dmabuf *h_buf;
2044 	struct lpfc_rqb *rqbp;
2045 
2046 	rqbp = hrq->rqbp;
2047 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2048 			 struct lpfc_dmabuf, list);
2049 	if (!h_buf)
2050 		return NULL;
2051 	rqbp->buffer_count--;
2052 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2053 }
2054 
2055 /**
2056  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2057  * @phba: Pointer to HBA context object.
2058  * @tag: Tag of the hbq buffer.
2059  *
2060  * This function searches for the hbq buffer associated with the given tag in
2061  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2062  * otherwise it returns NULL.
2063  **/
2064 static struct hbq_dmabuf *
2065 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2066 {
2067 	struct lpfc_dmabuf *d_buf;
2068 	struct hbq_dmabuf *hbq_buf;
2069 	uint32_t hbqno;
2070 
2071 	hbqno = tag >> 16;
2072 	if (hbqno >= LPFC_MAX_HBQS)
2073 		return NULL;
2074 
2075 	spin_lock_irq(&phba->hbalock);
2076 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2077 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2078 		if (hbq_buf->tag == tag) {
2079 			spin_unlock_irq(&phba->hbalock);
2080 			return hbq_buf;
2081 		}
2082 	}
2083 	spin_unlock_irq(&phba->hbalock);
2084 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_VPORT,
2085 			"1803 Bad hbq tag. Data: x%x x%x\n",
2086 			tag, phba->hbqs[tag >> 16].buffer_count);
2087 	return NULL;
2088 }
2089 
2090 /**
2091  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2092  * @phba: Pointer to HBA context object.
2093  * @hbq_buffer: Pointer to HBQ buffer.
2094  *
2095  * This function is called with hbalock. This function gives back
2096  * the hbq buffer to firmware. If the HBQ does not have space to
2097  * post the buffer, it will free the buffer.
2098  **/
2099 void
2100 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2101 {
2102 	uint32_t hbqno;
2103 
2104 	if (hbq_buffer) {
2105 		hbqno = hbq_buffer->tag >> 16;
2106 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2107 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2108 	}
2109 }
2110 
2111 /**
2112  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2113  * @mbxCommand: mailbox command code.
2114  *
2115  * This function is called by the mailbox event handler function to verify
2116  * that the completed mailbox command is a legitimate mailbox command. If the
2117  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2118  * and the mailbox event handler will take the HBA offline.
2119  **/
2120 static int
2121 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2122 {
2123 	uint8_t ret;
2124 
2125 	switch (mbxCommand) {
2126 	case MBX_LOAD_SM:
2127 	case MBX_READ_NV:
2128 	case MBX_WRITE_NV:
2129 	case MBX_WRITE_VPARMS:
2130 	case MBX_RUN_BIU_DIAG:
2131 	case MBX_INIT_LINK:
2132 	case MBX_DOWN_LINK:
2133 	case MBX_CONFIG_LINK:
2134 	case MBX_CONFIG_RING:
2135 	case MBX_RESET_RING:
2136 	case MBX_READ_CONFIG:
2137 	case MBX_READ_RCONFIG:
2138 	case MBX_READ_SPARM:
2139 	case MBX_READ_STATUS:
2140 	case MBX_READ_RPI:
2141 	case MBX_READ_XRI:
2142 	case MBX_READ_REV:
2143 	case MBX_READ_LNK_STAT:
2144 	case MBX_REG_LOGIN:
2145 	case MBX_UNREG_LOGIN:
2146 	case MBX_CLEAR_LA:
2147 	case MBX_DUMP_MEMORY:
2148 	case MBX_DUMP_CONTEXT:
2149 	case MBX_RUN_DIAGS:
2150 	case MBX_RESTART:
2151 	case MBX_UPDATE_CFG:
2152 	case MBX_DOWN_LOAD:
2153 	case MBX_DEL_LD_ENTRY:
2154 	case MBX_RUN_PROGRAM:
2155 	case MBX_SET_MASK:
2156 	case MBX_SET_VARIABLE:
2157 	case MBX_UNREG_D_ID:
2158 	case MBX_KILL_BOARD:
2159 	case MBX_CONFIG_FARP:
2160 	case MBX_BEACON:
2161 	case MBX_LOAD_AREA:
2162 	case MBX_RUN_BIU_DIAG64:
2163 	case MBX_CONFIG_PORT:
2164 	case MBX_READ_SPARM64:
2165 	case MBX_READ_RPI64:
2166 	case MBX_REG_LOGIN64:
2167 	case MBX_READ_TOPOLOGY:
2168 	case MBX_WRITE_WWN:
2169 	case MBX_SET_DEBUG:
2170 	case MBX_LOAD_EXP_ROM:
2171 	case MBX_ASYNCEVT_ENABLE:
2172 	case MBX_REG_VPI:
2173 	case MBX_UNREG_VPI:
2174 	case MBX_HEARTBEAT:
2175 	case MBX_PORT_CAPABILITIES:
2176 	case MBX_PORT_IOV_CONTROL:
2177 	case MBX_SLI4_CONFIG:
2178 	case MBX_SLI4_REQ_FTRS:
2179 	case MBX_REG_FCFI:
2180 	case MBX_UNREG_FCFI:
2181 	case MBX_REG_VFI:
2182 	case MBX_UNREG_VFI:
2183 	case MBX_INIT_VPI:
2184 	case MBX_INIT_VFI:
2185 	case MBX_RESUME_RPI:
2186 	case MBX_READ_EVENT_LOG_STATUS:
2187 	case MBX_READ_EVENT_LOG:
2188 	case MBX_SECURITY_MGMT:
2189 	case MBX_AUTH_PORT:
2190 	case MBX_ACCESS_VDATA:
2191 		ret = mbxCommand;
2192 		break;
2193 	default:
2194 		ret = MBX_SHUTDOWN;
2195 		break;
2196 	}
2197 	return ret;
2198 }
2199 
2200 /**
2201  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2202  * @phba: Pointer to HBA context object.
2203  * @pmboxq: Pointer to mailbox command.
2204  *
2205  * This is completion handler function for mailbox commands issued from
2206  * lpfc_sli_issue_mbox_wait function. This function is called by the
2207  * mailbox event handler function with no lock held. This function
2208  * will wake up thread waiting on the wait queue pointed by context1
2209  * of the mailbox.
2210  **/
2211 void
2212 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2213 {
2214 	wait_queue_head_t *pdone_q;
2215 	unsigned long drvr_flag;
2216 
2217 	/*
2218 	 * If pdone_q is empty, the driver thread gave up waiting and
2219 	 * continued running.
2220 	 */
2221 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2222 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2223 	pdone_q = (wait_queue_head_t *) pmboxq->context1;
2224 	if (pdone_q)
2225 		wake_up_interruptible(pdone_q);
2226 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2227 	return;
2228 }
2229 
2230 
2231 /**
2232  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2233  * @phba: Pointer to HBA context object.
2234  * @pmb: Pointer to mailbox object.
2235  *
2236  * This function is the default mailbox completion handler. It
2237  * frees the memory resources associated with the completed mailbox
2238  * command. If the completed command is a REG_LOGIN mailbox command,
2239  * this function will issue a UREG_LOGIN to re-claim the RPI.
2240  **/
2241 void
2242 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2243 {
2244 	struct lpfc_vport  *vport = pmb->vport;
2245 	struct lpfc_dmabuf *mp;
2246 	struct lpfc_nodelist *ndlp;
2247 	struct Scsi_Host *shost;
2248 	uint16_t rpi, vpi;
2249 	int rc;
2250 
2251 	mp = (struct lpfc_dmabuf *) (pmb->context1);
2252 
2253 	if (mp) {
2254 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
2255 		kfree(mp);
2256 	}
2257 
2258 	/*
2259 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2260 	 * is in re-discovery driver need to cleanup the RPI.
2261 	 */
2262 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2263 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2264 	    !pmb->u.mb.mbxStatus) {
2265 		rpi = pmb->u.mb.un.varWords[0];
2266 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2267 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2268 		pmb->vport = vport;
2269 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2270 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2271 		if (rc != MBX_NOT_FINISHED)
2272 			return;
2273 	}
2274 
2275 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2276 		!(phba->pport->load_flag & FC_UNLOADING) &&
2277 		!pmb->u.mb.mbxStatus) {
2278 		shost = lpfc_shost_from_vport(vport);
2279 		spin_lock_irq(shost->host_lock);
2280 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2281 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2282 		spin_unlock_irq(shost->host_lock);
2283 	}
2284 
2285 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2286 		ndlp = (struct lpfc_nodelist *)pmb->context2;
2287 		lpfc_nlp_put(ndlp);
2288 		pmb->context2 = NULL;
2289 	}
2290 
2291 	/* Check security permission status on INIT_LINK mailbox command */
2292 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2293 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2294 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2295 				"2860 SLI authentication is required "
2296 				"for INIT_LINK but has not done yet\n");
2297 
2298 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2299 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2300 	else
2301 		mempool_free(pmb, phba->mbox_mem_pool);
2302 }
2303  /**
2304  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2305  * @phba: Pointer to HBA context object.
2306  * @pmb: Pointer to mailbox object.
2307  *
2308  * This function is the unreg rpi mailbox completion handler. It
2309  * frees the memory resources associated with the completed mailbox
2310  * command. An additional refrenece is put on the ndlp to prevent
2311  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2312  * the unreg mailbox command completes, this routine puts the
2313  * reference back.
2314  *
2315  **/
2316 void
2317 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2318 {
2319 	struct lpfc_vport  *vport = pmb->vport;
2320 	struct lpfc_nodelist *ndlp;
2321 
2322 	ndlp = pmb->context1;
2323 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2324 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2325 		    (bf_get(lpfc_sli_intf_if_type,
2326 		     &phba->sli4_hba.sli_intf) ==
2327 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2328 			if (ndlp) {
2329 				lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
2330 						 "0010 UNREG_LOGIN vpi:%x "
2331 						 "rpi:%x DID:%x map:%x %p\n",
2332 						 vport->vpi, ndlp->nlp_rpi,
2333 						 ndlp->nlp_DID,
2334 						 ndlp->nlp_usg_map, ndlp);
2335 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2336 				lpfc_nlp_put(ndlp);
2337 			}
2338 		}
2339 	}
2340 
2341 	mempool_free(pmb, phba->mbox_mem_pool);
2342 }
2343 
2344 /**
2345  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
2346  * @phba: Pointer to HBA context object.
2347  *
2348  * This function is called with no lock held. This function processes all
2349  * the completed mailbox commands and gives it to upper layers. The interrupt
2350  * service routine processes mailbox completion interrupt and adds completed
2351  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
2352  * Worker thread call lpfc_sli_handle_mb_event, which will return the
2353  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
2354  * function returns the mailbox commands to the upper layer by calling the
2355  * completion handler function of each mailbox.
2356  **/
2357 int
2358 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
2359 {
2360 	MAILBOX_t *pmbox;
2361 	LPFC_MBOXQ_t *pmb;
2362 	int rc;
2363 	LIST_HEAD(cmplq);
2364 
2365 	phba->sli.slistat.mbox_event++;
2366 
2367 	/* Get all completed mailboxe buffers into the cmplq */
2368 	spin_lock_irq(&phba->hbalock);
2369 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
2370 	spin_unlock_irq(&phba->hbalock);
2371 
2372 	/* Get a Mailbox buffer to setup mailbox commands for callback */
2373 	do {
2374 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
2375 		if (pmb == NULL)
2376 			break;
2377 
2378 		pmbox = &pmb->u.mb;
2379 
2380 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
2381 			if (pmb->vport) {
2382 				lpfc_debugfs_disc_trc(pmb->vport,
2383 					LPFC_DISC_TRC_MBOX_VPORT,
2384 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
2385 					(uint32_t)pmbox->mbxCommand,
2386 					pmbox->un.varWords[0],
2387 					pmbox->un.varWords[1]);
2388 			}
2389 			else {
2390 				lpfc_debugfs_disc_trc(phba->pport,
2391 					LPFC_DISC_TRC_MBOX,
2392 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
2393 					(uint32_t)pmbox->mbxCommand,
2394 					pmbox->un.varWords[0],
2395 					pmbox->un.varWords[1]);
2396 			}
2397 		}
2398 
2399 		/*
2400 		 * It is a fatal error if unknown mbox command completion.
2401 		 */
2402 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
2403 		    MBX_SHUTDOWN) {
2404 			/* Unknown mailbox command compl */
2405 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2406 					"(%d):0323 Unknown Mailbox command "
2407 					"x%x (x%x/x%x) Cmpl\n",
2408 					pmb->vport ? pmb->vport->vpi : 0,
2409 					pmbox->mbxCommand,
2410 					lpfc_sli_config_mbox_subsys_get(phba,
2411 									pmb),
2412 					lpfc_sli_config_mbox_opcode_get(phba,
2413 									pmb));
2414 			phba->link_state = LPFC_HBA_ERROR;
2415 			phba->work_hs = HS_FFER3;
2416 			lpfc_handle_eratt(phba);
2417 			continue;
2418 		}
2419 
2420 		if (pmbox->mbxStatus) {
2421 			phba->sli.slistat.mbox_stat_err++;
2422 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
2423 				/* Mbox cmd cmpl error - RETRYing */
2424 				lpfc_printf_log(phba, KERN_INFO,
2425 					LOG_MBOX | LOG_SLI,
2426 					"(%d):0305 Mbox cmd cmpl "
2427 					"error - RETRYing Data: x%x "
2428 					"(x%x/x%x) x%x x%x x%x\n",
2429 					pmb->vport ? pmb->vport->vpi : 0,
2430 					pmbox->mbxCommand,
2431 					lpfc_sli_config_mbox_subsys_get(phba,
2432 									pmb),
2433 					lpfc_sli_config_mbox_opcode_get(phba,
2434 									pmb),
2435 					pmbox->mbxStatus,
2436 					pmbox->un.varWords[0],
2437 					pmb->vport->port_state);
2438 				pmbox->mbxStatus = 0;
2439 				pmbox->mbxOwner = OWN_HOST;
2440 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2441 				if (rc != MBX_NOT_FINISHED)
2442 					continue;
2443 			}
2444 		}
2445 
2446 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
2447 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
2448 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl x%p "
2449 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
2450 				"x%x x%x x%x\n",
2451 				pmb->vport ? pmb->vport->vpi : 0,
2452 				pmbox->mbxCommand,
2453 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
2454 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
2455 				pmb->mbox_cmpl,
2456 				*((uint32_t *) pmbox),
2457 				pmbox->un.varWords[0],
2458 				pmbox->un.varWords[1],
2459 				pmbox->un.varWords[2],
2460 				pmbox->un.varWords[3],
2461 				pmbox->un.varWords[4],
2462 				pmbox->un.varWords[5],
2463 				pmbox->un.varWords[6],
2464 				pmbox->un.varWords[7],
2465 				pmbox->un.varWords[8],
2466 				pmbox->un.varWords[9],
2467 				pmbox->un.varWords[10]);
2468 
2469 		if (pmb->mbox_cmpl)
2470 			pmb->mbox_cmpl(phba,pmb);
2471 	} while (1);
2472 	return 0;
2473 }
2474 
2475 /**
2476  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
2477  * @phba: Pointer to HBA context object.
2478  * @pring: Pointer to driver SLI ring object.
2479  * @tag: buffer tag.
2480  *
2481  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
2482  * is set in the tag the buffer is posted for a particular exchange,
2483  * the function will return the buffer without replacing the buffer.
2484  * If the buffer is for unsolicited ELS or CT traffic, this function
2485  * returns the buffer and also posts another buffer to the firmware.
2486  **/
2487 static struct lpfc_dmabuf *
2488 lpfc_sli_get_buff(struct lpfc_hba *phba,
2489 		  struct lpfc_sli_ring *pring,
2490 		  uint32_t tag)
2491 {
2492 	struct hbq_dmabuf *hbq_entry;
2493 
2494 	if (tag & QUE_BUFTAG_BIT)
2495 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
2496 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
2497 	if (!hbq_entry)
2498 		return NULL;
2499 	return &hbq_entry->dbuf;
2500 }
2501 
2502 /**
2503  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
2504  * @phba: Pointer to HBA context object.
2505  * @pring: Pointer to driver SLI ring object.
2506  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
2507  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
2508  * @fch_type: the type for the first frame of the sequence.
2509  *
2510  * This function is called with no lock held. This function uses the r_ctl and
2511  * type of the received sequence to find the correct callback function to call
2512  * to process the sequence.
2513  **/
2514 static int
2515 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2516 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
2517 			 uint32_t fch_type)
2518 {
2519 	int i;
2520 
2521 	switch (fch_type) {
2522 	case FC_TYPE_NVME:
2523 		lpfc_nvmet_unsol_ls_event(phba, pring, saveq);
2524 		return 1;
2525 	default:
2526 		break;
2527 	}
2528 
2529 	/* unSolicited Responses */
2530 	if (pring->prt[0].profile) {
2531 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
2532 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
2533 									saveq);
2534 		return 1;
2535 	}
2536 	/* We must search, based on rctl / type
2537 	   for the right routine */
2538 	for (i = 0; i < pring->num_mask; i++) {
2539 		if ((pring->prt[i].rctl == fch_r_ctl) &&
2540 		    (pring->prt[i].type == fch_type)) {
2541 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
2542 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
2543 						(phba, pring, saveq);
2544 			return 1;
2545 		}
2546 	}
2547 	return 0;
2548 }
2549 
2550 /**
2551  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
2552  * @phba: Pointer to HBA context object.
2553  * @pring: Pointer to driver SLI ring object.
2554  * @saveq: Pointer to the unsolicited iocb.
2555  *
2556  * This function is called with no lock held by the ring event handler
2557  * when there is an unsolicited iocb posted to the response ring by the
2558  * firmware. This function gets the buffer associated with the iocbs
2559  * and calls the event handler for the ring. This function handles both
2560  * qring buffers and hbq buffers.
2561  * When the function returns 1 the caller can free the iocb object otherwise
2562  * upper layer functions will free the iocb objects.
2563  **/
2564 static int
2565 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2566 			    struct lpfc_iocbq *saveq)
2567 {
2568 	IOCB_t           * irsp;
2569 	WORD5            * w5p;
2570 	uint32_t           Rctl, Type;
2571 	struct lpfc_iocbq *iocbq;
2572 	struct lpfc_dmabuf *dmzbuf;
2573 
2574 	irsp = &(saveq->iocb);
2575 
2576 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
2577 		if (pring->lpfc_sli_rcv_async_status)
2578 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
2579 		else
2580 			lpfc_printf_log(phba,
2581 					KERN_WARNING,
2582 					LOG_SLI,
2583 					"0316 Ring %d handler: unexpected "
2584 					"ASYNC_STATUS iocb received evt_code "
2585 					"0x%x\n",
2586 					pring->ringno,
2587 					irsp->un.asyncstat.evt_code);
2588 		return 1;
2589 	}
2590 
2591 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
2592 		(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
2593 		if (irsp->ulpBdeCount > 0) {
2594 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2595 					irsp->un.ulpWord[3]);
2596 			lpfc_in_buf_free(phba, dmzbuf);
2597 		}
2598 
2599 		if (irsp->ulpBdeCount > 1) {
2600 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2601 					irsp->unsli3.sli3Words[3]);
2602 			lpfc_in_buf_free(phba, dmzbuf);
2603 		}
2604 
2605 		if (irsp->ulpBdeCount > 2) {
2606 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2607 				irsp->unsli3.sli3Words[7]);
2608 			lpfc_in_buf_free(phba, dmzbuf);
2609 		}
2610 
2611 		return 1;
2612 	}
2613 
2614 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
2615 		if (irsp->ulpBdeCount != 0) {
2616 			saveq->context2 = lpfc_sli_get_buff(phba, pring,
2617 						irsp->un.ulpWord[3]);
2618 			if (!saveq->context2)
2619 				lpfc_printf_log(phba,
2620 					KERN_ERR,
2621 					LOG_SLI,
2622 					"0341 Ring %d Cannot find buffer for "
2623 					"an unsolicited iocb. tag 0x%x\n",
2624 					pring->ringno,
2625 					irsp->un.ulpWord[3]);
2626 		}
2627 		if (irsp->ulpBdeCount == 2) {
2628 			saveq->context3 = lpfc_sli_get_buff(phba, pring,
2629 						irsp->unsli3.sli3Words[7]);
2630 			if (!saveq->context3)
2631 				lpfc_printf_log(phba,
2632 					KERN_ERR,
2633 					LOG_SLI,
2634 					"0342 Ring %d Cannot find buffer for an"
2635 					" unsolicited iocb. tag 0x%x\n",
2636 					pring->ringno,
2637 					irsp->unsli3.sli3Words[7]);
2638 		}
2639 		list_for_each_entry(iocbq, &saveq->list, list) {
2640 			irsp = &(iocbq->iocb);
2641 			if (irsp->ulpBdeCount != 0) {
2642 				iocbq->context2 = lpfc_sli_get_buff(phba, pring,
2643 							irsp->un.ulpWord[3]);
2644 				if (!iocbq->context2)
2645 					lpfc_printf_log(phba,
2646 						KERN_ERR,
2647 						LOG_SLI,
2648 						"0343 Ring %d Cannot find "
2649 						"buffer for an unsolicited iocb"
2650 						". tag 0x%x\n", pring->ringno,
2651 						irsp->un.ulpWord[3]);
2652 			}
2653 			if (irsp->ulpBdeCount == 2) {
2654 				iocbq->context3 = lpfc_sli_get_buff(phba, pring,
2655 						irsp->unsli3.sli3Words[7]);
2656 				if (!iocbq->context3)
2657 					lpfc_printf_log(phba,
2658 						KERN_ERR,
2659 						LOG_SLI,
2660 						"0344 Ring %d Cannot find "
2661 						"buffer for an unsolicited "
2662 						"iocb. tag 0x%x\n",
2663 						pring->ringno,
2664 						irsp->unsli3.sli3Words[7]);
2665 			}
2666 		}
2667 	}
2668 	if (irsp->ulpBdeCount != 0 &&
2669 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
2670 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
2671 		int found = 0;
2672 
2673 		/* search continue save q for same XRI */
2674 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
2675 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
2676 				saveq->iocb.unsli3.rcvsli3.ox_id) {
2677 				list_add_tail(&saveq->list, &iocbq->list);
2678 				found = 1;
2679 				break;
2680 			}
2681 		}
2682 		if (!found)
2683 			list_add_tail(&saveq->clist,
2684 				      &pring->iocb_continue_saveq);
2685 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
2686 			list_del_init(&iocbq->clist);
2687 			saveq = iocbq;
2688 			irsp = &(saveq->iocb);
2689 		} else
2690 			return 0;
2691 	}
2692 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
2693 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
2694 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
2695 		Rctl = FC_RCTL_ELS_REQ;
2696 		Type = FC_TYPE_ELS;
2697 	} else {
2698 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
2699 		Rctl = w5p->hcsw.Rctl;
2700 		Type = w5p->hcsw.Type;
2701 
2702 		/* Firmware Workaround */
2703 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
2704 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
2705 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
2706 			Rctl = FC_RCTL_ELS_REQ;
2707 			Type = FC_TYPE_ELS;
2708 			w5p->hcsw.Rctl = Rctl;
2709 			w5p->hcsw.Type = Type;
2710 		}
2711 	}
2712 
2713 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
2714 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2715 				"0313 Ring %d handler: unexpected Rctl x%x "
2716 				"Type x%x received\n",
2717 				pring->ringno, Rctl, Type);
2718 
2719 	return 1;
2720 }
2721 
2722 /**
2723  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
2724  * @phba: Pointer to HBA context object.
2725  * @pring: Pointer to driver SLI ring object.
2726  * @prspiocb: Pointer to response iocb object.
2727  *
2728  * This function looks up the iocb_lookup table to get the command iocb
2729  * corresponding to the given response iocb using the iotag of the
2730  * response iocb. This function is called with the hbalock held.
2731  * This function returns the command iocb object if it finds the command
2732  * iocb else returns NULL.
2733  **/
2734 static struct lpfc_iocbq *
2735 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
2736 		      struct lpfc_sli_ring *pring,
2737 		      struct lpfc_iocbq *prspiocb)
2738 {
2739 	struct lpfc_iocbq *cmd_iocb = NULL;
2740 	uint16_t iotag;
2741 	lockdep_assert_held(&phba->hbalock);
2742 
2743 	iotag = prspiocb->iocb.ulpIoTag;
2744 
2745 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
2746 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
2747 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
2748 			/* remove from txcmpl queue list */
2749 			list_del_init(&cmd_iocb->list);
2750 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
2751 			return cmd_iocb;
2752 		}
2753 	}
2754 
2755 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2756 			"0317 iotag x%x is out of "
2757 			"range: max iotag x%x wd0 x%x\n",
2758 			iotag, phba->sli.last_iotag,
2759 			*(((uint32_t *) &prspiocb->iocb) + 7));
2760 	return NULL;
2761 }
2762 
2763 /**
2764  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
2765  * @phba: Pointer to HBA context object.
2766  * @pring: Pointer to driver SLI ring object.
2767  * @iotag: IOCB tag.
2768  *
2769  * This function looks up the iocb_lookup table to get the command iocb
2770  * corresponding to the given iotag. This function is called with the
2771  * hbalock held.
2772  * This function returns the command iocb object if it finds the command
2773  * iocb else returns NULL.
2774  **/
2775 static struct lpfc_iocbq *
2776 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
2777 			     struct lpfc_sli_ring *pring, uint16_t iotag)
2778 {
2779 	struct lpfc_iocbq *cmd_iocb = NULL;
2780 
2781 	lockdep_assert_held(&phba->hbalock);
2782 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
2783 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
2784 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
2785 			/* remove from txcmpl queue list */
2786 			list_del_init(&cmd_iocb->list);
2787 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
2788 			return cmd_iocb;
2789 		}
2790 	}
2791 
2792 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2793 			"0372 iotag x%x lookup error: max iotag (x%x) "
2794 			"iocb_flag x%x\n",
2795 			iotag, phba->sli.last_iotag,
2796 			cmd_iocb ? cmd_iocb->iocb_flag : 0xffff);
2797 	return NULL;
2798 }
2799 
2800 /**
2801  * lpfc_sli_process_sol_iocb - process solicited iocb completion
2802  * @phba: Pointer to HBA context object.
2803  * @pring: Pointer to driver SLI ring object.
2804  * @saveq: Pointer to the response iocb to be processed.
2805  *
2806  * This function is called by the ring event handler for non-fcp
2807  * rings when there is a new response iocb in the response ring.
2808  * The caller is not required to hold any locks. This function
2809  * gets the command iocb associated with the response iocb and
2810  * calls the completion handler for the command iocb. If there
2811  * is no completion handler, the function will free the resources
2812  * associated with command iocb. If the response iocb is for
2813  * an already aborted command iocb, the status of the completion
2814  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
2815  * This function always returns 1.
2816  **/
2817 static int
2818 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2819 			  struct lpfc_iocbq *saveq)
2820 {
2821 	struct lpfc_iocbq *cmdiocbp;
2822 	int rc = 1;
2823 	unsigned long iflag;
2824 
2825 	/* Based on the iotag field, get the cmd IOCB from the txcmplq */
2826 	spin_lock_irqsave(&phba->hbalock, iflag);
2827 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
2828 	spin_unlock_irqrestore(&phba->hbalock, iflag);
2829 
2830 	if (cmdiocbp) {
2831 		if (cmdiocbp->iocb_cmpl) {
2832 			/*
2833 			 * If an ELS command failed send an event to mgmt
2834 			 * application.
2835 			 */
2836 			if (saveq->iocb.ulpStatus &&
2837 			     (pring->ringno == LPFC_ELS_RING) &&
2838 			     (cmdiocbp->iocb.ulpCommand ==
2839 				CMD_ELS_REQUEST64_CR))
2840 				lpfc_send_els_failure_event(phba,
2841 					cmdiocbp, saveq);
2842 
2843 			/*
2844 			 * Post all ELS completions to the worker thread.
2845 			 * All other are passed to the completion callback.
2846 			 */
2847 			if (pring->ringno == LPFC_ELS_RING) {
2848 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
2849 				    (cmdiocbp->iocb_flag &
2850 							LPFC_DRIVER_ABORTED)) {
2851 					spin_lock_irqsave(&phba->hbalock,
2852 							  iflag);
2853 					cmdiocbp->iocb_flag &=
2854 						~LPFC_DRIVER_ABORTED;
2855 					spin_unlock_irqrestore(&phba->hbalock,
2856 							       iflag);
2857 					saveq->iocb.ulpStatus =
2858 						IOSTAT_LOCAL_REJECT;
2859 					saveq->iocb.un.ulpWord[4] =
2860 						IOERR_SLI_ABORTED;
2861 
2862 					/* Firmware could still be in progress
2863 					 * of DMAing payload, so don't free data
2864 					 * buffer till after a hbeat.
2865 					 */
2866 					spin_lock_irqsave(&phba->hbalock,
2867 							  iflag);
2868 					saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
2869 					spin_unlock_irqrestore(&phba->hbalock,
2870 							       iflag);
2871 				}
2872 				if (phba->sli_rev == LPFC_SLI_REV4) {
2873 					if (saveq->iocb_flag &
2874 					    LPFC_EXCHANGE_BUSY) {
2875 						/* Set cmdiocb flag for the
2876 						 * exchange busy so sgl (xri)
2877 						 * will not be released until
2878 						 * the abort xri is received
2879 						 * from hba.
2880 						 */
2881 						spin_lock_irqsave(
2882 							&phba->hbalock, iflag);
2883 						cmdiocbp->iocb_flag |=
2884 							LPFC_EXCHANGE_BUSY;
2885 						spin_unlock_irqrestore(
2886 							&phba->hbalock, iflag);
2887 					}
2888 					if (cmdiocbp->iocb_flag &
2889 					    LPFC_DRIVER_ABORTED) {
2890 						/*
2891 						 * Clear LPFC_DRIVER_ABORTED
2892 						 * bit in case it was driver
2893 						 * initiated abort.
2894 						 */
2895 						spin_lock_irqsave(
2896 							&phba->hbalock, iflag);
2897 						cmdiocbp->iocb_flag &=
2898 							~LPFC_DRIVER_ABORTED;
2899 						spin_unlock_irqrestore(
2900 							&phba->hbalock, iflag);
2901 						cmdiocbp->iocb.ulpStatus =
2902 							IOSTAT_LOCAL_REJECT;
2903 						cmdiocbp->iocb.un.ulpWord[4] =
2904 							IOERR_ABORT_REQUESTED;
2905 						/*
2906 						 * For SLI4, irsiocb contains
2907 						 * NO_XRI in sli_xritag, it
2908 						 * shall not affect releasing
2909 						 * sgl (xri) process.
2910 						 */
2911 						saveq->iocb.ulpStatus =
2912 							IOSTAT_LOCAL_REJECT;
2913 						saveq->iocb.un.ulpWord[4] =
2914 							IOERR_SLI_ABORTED;
2915 						spin_lock_irqsave(
2916 							&phba->hbalock, iflag);
2917 						saveq->iocb_flag |=
2918 							LPFC_DELAY_MEM_FREE;
2919 						spin_unlock_irqrestore(
2920 							&phba->hbalock, iflag);
2921 					}
2922 				}
2923 			}
2924 			(cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
2925 		} else
2926 			lpfc_sli_release_iocbq(phba, cmdiocbp);
2927 	} else {
2928 		/*
2929 		 * Unknown initiating command based on the response iotag.
2930 		 * This could be the case on the ELS ring because of
2931 		 * lpfc_els_abort().
2932 		 */
2933 		if (pring->ringno != LPFC_ELS_RING) {
2934 			/*
2935 			 * Ring <ringno> handler: unexpected completion IoTag
2936 			 * <IoTag>
2937 			 */
2938 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2939 					 "0322 Ring %d handler: "
2940 					 "unexpected completion IoTag x%x "
2941 					 "Data: x%x x%x x%x x%x\n",
2942 					 pring->ringno,
2943 					 saveq->iocb.ulpIoTag,
2944 					 saveq->iocb.ulpStatus,
2945 					 saveq->iocb.un.ulpWord[4],
2946 					 saveq->iocb.ulpCommand,
2947 					 saveq->iocb.ulpContext);
2948 		}
2949 	}
2950 
2951 	return rc;
2952 }
2953 
2954 /**
2955  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
2956  * @phba: Pointer to HBA context object.
2957  * @pring: Pointer to driver SLI ring object.
2958  *
2959  * This function is called from the iocb ring event handlers when
2960  * put pointer is ahead of the get pointer for a ring. This function signal
2961  * an error attention condition to the worker thread and the worker
2962  * thread will transition the HBA to offline state.
2963  **/
2964 static void
2965 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2966 {
2967 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2968 	/*
2969 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
2970 	 * rsp ring <portRspMax>
2971 	 */
2972 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2973 			"0312 Ring %d handler: portRspPut %d "
2974 			"is bigger than rsp ring %d\n",
2975 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
2976 			pring->sli.sli3.numRiocb);
2977 
2978 	phba->link_state = LPFC_HBA_ERROR;
2979 
2980 	/*
2981 	 * All error attention handlers are posted to
2982 	 * worker thread
2983 	 */
2984 	phba->work_ha |= HA_ERATT;
2985 	phba->work_hs = HS_FFER3;
2986 
2987 	lpfc_worker_wake_up(phba);
2988 
2989 	return;
2990 }
2991 
2992 /**
2993  * lpfc_poll_eratt - Error attention polling timer timeout handler
2994  * @ptr: Pointer to address of HBA context object.
2995  *
2996  * This function is invoked by the Error Attention polling timer when the
2997  * timer times out. It will check the SLI Error Attention register for
2998  * possible attention events. If so, it will post an Error Attention event
2999  * and wake up worker thread to process it. Otherwise, it will set up the
3000  * Error Attention polling timer for the next poll.
3001  **/
3002 void lpfc_poll_eratt(unsigned long ptr)
3003 {
3004 	struct lpfc_hba *phba;
3005 	uint32_t eratt = 0;
3006 	uint64_t sli_intr, cnt;
3007 
3008 	phba = (struct lpfc_hba *)ptr;
3009 
3010 	/* Here we will also keep track of interrupts per sec of the hba */
3011 	sli_intr = phba->sli.slistat.sli_intr;
3012 
3013 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3014 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3015 			sli_intr);
3016 	else
3017 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3018 
3019 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3020 	do_div(cnt, phba->eratt_poll_interval);
3021 	phba->sli.slistat.sli_ips = cnt;
3022 
3023 	phba->sli.slistat.sli_prev_intr = sli_intr;
3024 
3025 	/* Check chip HA register for error event */
3026 	eratt = lpfc_sli_check_eratt(phba);
3027 
3028 	if (eratt)
3029 		/* Tell the worker thread there is work to do */
3030 		lpfc_worker_wake_up(phba);
3031 	else
3032 		/* Restart the timer for next eratt poll */
3033 		mod_timer(&phba->eratt_poll,
3034 			  jiffies +
3035 			  msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3036 	return;
3037 }
3038 
3039 
3040 /**
3041  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3042  * @phba: Pointer to HBA context object.
3043  * @pring: Pointer to driver SLI ring object.
3044  * @mask: Host attention register mask for this ring.
3045  *
3046  * This function is called from the interrupt context when there is a ring
3047  * event for the fcp ring. The caller does not hold any lock.
3048  * The function processes each response iocb in the response ring until it
3049  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3050  * LE bit set. The function will call the completion handler of the command iocb
3051  * if the response iocb indicates a completion for a command iocb or it is
3052  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3053  * function if this is an unsolicited iocb.
3054  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3055  * to check it explicitly.
3056  */
3057 int
3058 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3059 				struct lpfc_sli_ring *pring, uint32_t mask)
3060 {
3061 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3062 	IOCB_t *irsp = NULL;
3063 	IOCB_t *entry = NULL;
3064 	struct lpfc_iocbq *cmdiocbq = NULL;
3065 	struct lpfc_iocbq rspiocbq;
3066 	uint32_t status;
3067 	uint32_t portRspPut, portRspMax;
3068 	int rc = 1;
3069 	lpfc_iocb_type type;
3070 	unsigned long iflag;
3071 	uint32_t rsp_cmpl = 0;
3072 
3073 	spin_lock_irqsave(&phba->hbalock, iflag);
3074 	pring->stats.iocb_event++;
3075 
3076 	/*
3077 	 * The next available response entry should never exceed the maximum
3078 	 * entries.  If it does, treat it as an adapter hardware error.
3079 	 */
3080 	portRspMax = pring->sli.sli3.numRiocb;
3081 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3082 	if (unlikely(portRspPut >= portRspMax)) {
3083 		lpfc_sli_rsp_pointers_error(phba, pring);
3084 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3085 		return 1;
3086 	}
3087 	if (phba->fcp_ring_in_use) {
3088 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3089 		return 1;
3090 	} else
3091 		phba->fcp_ring_in_use = 1;
3092 
3093 	rmb();
3094 	while (pring->sli.sli3.rspidx != portRspPut) {
3095 		/*
3096 		 * Fetch an entry off the ring and copy it into a local data
3097 		 * structure.  The copy involves a byte-swap since the
3098 		 * network byte order and pci byte orders are different.
3099 		 */
3100 		entry = lpfc_resp_iocb(phba, pring);
3101 		phba->last_completion_time = jiffies;
3102 
3103 		if (++pring->sli.sli3.rspidx >= portRspMax)
3104 			pring->sli.sli3.rspidx = 0;
3105 
3106 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3107 				      (uint32_t *) &rspiocbq.iocb,
3108 				      phba->iocb_rsp_size);
3109 		INIT_LIST_HEAD(&(rspiocbq.list));
3110 		irsp = &rspiocbq.iocb;
3111 
3112 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3113 		pring->stats.iocb_rsp++;
3114 		rsp_cmpl++;
3115 
3116 		if (unlikely(irsp->ulpStatus)) {
3117 			/*
3118 			 * If resource errors reported from HBA, reduce
3119 			 * queuedepths of the SCSI device.
3120 			 */
3121 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3122 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3123 			     IOERR_NO_RESOURCES)) {
3124 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3125 				phba->lpfc_rampdown_queue_depth(phba);
3126 				spin_lock_irqsave(&phba->hbalock, iflag);
3127 			}
3128 
3129 			/* Rsp ring <ringno> error: IOCB */
3130 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3131 					"0336 Rsp Ring %d error: IOCB Data: "
3132 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
3133 					pring->ringno,
3134 					irsp->un.ulpWord[0],
3135 					irsp->un.ulpWord[1],
3136 					irsp->un.ulpWord[2],
3137 					irsp->un.ulpWord[3],
3138 					irsp->un.ulpWord[4],
3139 					irsp->un.ulpWord[5],
3140 					*(uint32_t *)&irsp->un1,
3141 					*((uint32_t *)&irsp->un1 + 1));
3142 		}
3143 
3144 		switch (type) {
3145 		case LPFC_ABORT_IOCB:
3146 		case LPFC_SOL_IOCB:
3147 			/*
3148 			 * Idle exchange closed via ABTS from port.  No iocb
3149 			 * resources need to be recovered.
3150 			 */
3151 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3152 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3153 						"0333 IOCB cmd 0x%x"
3154 						" processed. Skipping"
3155 						" completion\n",
3156 						irsp->ulpCommand);
3157 				break;
3158 			}
3159 
3160 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3161 							 &rspiocbq);
3162 			if (unlikely(!cmdiocbq))
3163 				break;
3164 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3165 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3166 			if (cmdiocbq->iocb_cmpl) {
3167 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3168 				(cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
3169 						      &rspiocbq);
3170 				spin_lock_irqsave(&phba->hbalock, iflag);
3171 			}
3172 			break;
3173 		case LPFC_UNSOL_IOCB:
3174 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3175 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
3176 			spin_lock_irqsave(&phba->hbalock, iflag);
3177 			break;
3178 		default:
3179 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3180 				char adaptermsg[LPFC_MAX_ADPTMSG];
3181 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3182 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
3183 				       MAX_MSG_DATA);
3184 				dev_warn(&((phba->pcidev)->dev),
3185 					 "lpfc%d: %s\n",
3186 					 phba->brd_no, adaptermsg);
3187 			} else {
3188 				/* Unknown IOCB command */
3189 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3190 						"0334 Unknown IOCB command "
3191 						"Data: x%x, x%x x%x x%x x%x\n",
3192 						type, irsp->ulpCommand,
3193 						irsp->ulpStatus,
3194 						irsp->ulpIoTag,
3195 						irsp->ulpContext);
3196 			}
3197 			break;
3198 		}
3199 
3200 		/*
3201 		 * The response IOCB has been processed.  Update the ring
3202 		 * pointer in SLIM.  If the port response put pointer has not
3203 		 * been updated, sync the pgp->rspPutInx and fetch the new port
3204 		 * response put pointer.
3205 		 */
3206 		writel(pring->sli.sli3.rspidx,
3207 			&phba->host_gp[pring->ringno].rspGetInx);
3208 
3209 		if (pring->sli.sli3.rspidx == portRspPut)
3210 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3211 	}
3212 
3213 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
3214 		pring->stats.iocb_rsp_full++;
3215 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3216 		writel(status, phba->CAregaddr);
3217 		readl(phba->CAregaddr);
3218 	}
3219 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3220 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3221 		pring->stats.iocb_cmd_empty++;
3222 
3223 		/* Force update of the local copy of cmdGetInx */
3224 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3225 		lpfc_sli_resume_iocb(phba, pring);
3226 
3227 		if ((pring->lpfc_sli_cmd_available))
3228 			(pring->lpfc_sli_cmd_available) (phba, pring);
3229 
3230 	}
3231 
3232 	phba->fcp_ring_in_use = 0;
3233 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3234 	return rc;
3235 }
3236 
3237 /**
3238  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
3239  * @phba: Pointer to HBA context object.
3240  * @pring: Pointer to driver SLI ring object.
3241  * @rspiocbp: Pointer to driver response IOCB object.
3242  *
3243  * This function is called from the worker thread when there is a slow-path
3244  * response IOCB to process. This function chains all the response iocbs until
3245  * seeing the iocb with the LE bit set. The function will call
3246  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
3247  * completion of a command iocb. The function will call the
3248  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
3249  * The function frees the resources or calls the completion handler if this
3250  * iocb is an abort completion. The function returns NULL when the response
3251  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
3252  * this function shall chain the iocb on to the iocb_continueq and return the
3253  * response iocb passed in.
3254  **/
3255 static struct lpfc_iocbq *
3256 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3257 			struct lpfc_iocbq *rspiocbp)
3258 {
3259 	struct lpfc_iocbq *saveq;
3260 	struct lpfc_iocbq *cmdiocbp;
3261 	struct lpfc_iocbq *next_iocb;
3262 	IOCB_t *irsp = NULL;
3263 	uint32_t free_saveq;
3264 	uint8_t iocb_cmd_type;
3265 	lpfc_iocb_type type;
3266 	unsigned long iflag;
3267 	int rc;
3268 
3269 	spin_lock_irqsave(&phba->hbalock, iflag);
3270 	/* First add the response iocb to the countinueq list */
3271 	list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
3272 	pring->iocb_continueq_cnt++;
3273 
3274 	/* Now, determine whether the list is completed for processing */
3275 	irsp = &rspiocbp->iocb;
3276 	if (irsp->ulpLe) {
3277 		/*
3278 		 * By default, the driver expects to free all resources
3279 		 * associated with this iocb completion.
3280 		 */
3281 		free_saveq = 1;
3282 		saveq = list_get_first(&pring->iocb_continueq,
3283 				       struct lpfc_iocbq, list);
3284 		irsp = &(saveq->iocb);
3285 		list_del_init(&pring->iocb_continueq);
3286 		pring->iocb_continueq_cnt = 0;
3287 
3288 		pring->stats.iocb_rsp++;
3289 
3290 		/*
3291 		 * If resource errors reported from HBA, reduce
3292 		 * queuedepths of the SCSI device.
3293 		 */
3294 		if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3295 		    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3296 		     IOERR_NO_RESOURCES)) {
3297 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3298 			phba->lpfc_rampdown_queue_depth(phba);
3299 			spin_lock_irqsave(&phba->hbalock, iflag);
3300 		}
3301 
3302 		if (irsp->ulpStatus) {
3303 			/* Rsp ring <ringno> error: IOCB */
3304 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3305 					"0328 Rsp Ring %d error: "
3306 					"IOCB Data: "
3307 					"x%x x%x x%x x%x "
3308 					"x%x x%x x%x x%x "
3309 					"x%x x%x x%x x%x "
3310 					"x%x x%x x%x x%x\n",
3311 					pring->ringno,
3312 					irsp->un.ulpWord[0],
3313 					irsp->un.ulpWord[1],
3314 					irsp->un.ulpWord[2],
3315 					irsp->un.ulpWord[3],
3316 					irsp->un.ulpWord[4],
3317 					irsp->un.ulpWord[5],
3318 					*(((uint32_t *) irsp) + 6),
3319 					*(((uint32_t *) irsp) + 7),
3320 					*(((uint32_t *) irsp) + 8),
3321 					*(((uint32_t *) irsp) + 9),
3322 					*(((uint32_t *) irsp) + 10),
3323 					*(((uint32_t *) irsp) + 11),
3324 					*(((uint32_t *) irsp) + 12),
3325 					*(((uint32_t *) irsp) + 13),
3326 					*(((uint32_t *) irsp) + 14),
3327 					*(((uint32_t *) irsp) + 15));
3328 		}
3329 
3330 		/*
3331 		 * Fetch the IOCB command type and call the correct completion
3332 		 * routine. Solicited and Unsolicited IOCBs on the ELS ring
3333 		 * get freed back to the lpfc_iocb_list by the discovery
3334 		 * kernel thread.
3335 		 */
3336 		iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
3337 		type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
3338 		switch (type) {
3339 		case LPFC_SOL_IOCB:
3340 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3341 			rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
3342 			spin_lock_irqsave(&phba->hbalock, iflag);
3343 			break;
3344 
3345 		case LPFC_UNSOL_IOCB:
3346 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3347 			rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
3348 			spin_lock_irqsave(&phba->hbalock, iflag);
3349 			if (!rc)
3350 				free_saveq = 0;
3351 			break;
3352 
3353 		case LPFC_ABORT_IOCB:
3354 			cmdiocbp = NULL;
3355 			if (irsp->ulpCommand != CMD_XRI_ABORTED_CX)
3356 				cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
3357 								 saveq);
3358 			if (cmdiocbp) {
3359 				/* Call the specified completion routine */
3360 				if (cmdiocbp->iocb_cmpl) {
3361 					spin_unlock_irqrestore(&phba->hbalock,
3362 							       iflag);
3363 					(cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
3364 							      saveq);
3365 					spin_lock_irqsave(&phba->hbalock,
3366 							  iflag);
3367 				} else
3368 					__lpfc_sli_release_iocbq(phba,
3369 								 cmdiocbp);
3370 			}
3371 			break;
3372 
3373 		case LPFC_UNKNOWN_IOCB:
3374 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3375 				char adaptermsg[LPFC_MAX_ADPTMSG];
3376 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3377 				memcpy(&adaptermsg[0], (uint8_t *)irsp,
3378 				       MAX_MSG_DATA);
3379 				dev_warn(&((phba->pcidev)->dev),
3380 					 "lpfc%d: %s\n",
3381 					 phba->brd_no, adaptermsg);
3382 			} else {
3383 				/* Unknown IOCB command */
3384 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3385 						"0335 Unknown IOCB "
3386 						"command Data: x%x "
3387 						"x%x x%x x%x\n",
3388 						irsp->ulpCommand,
3389 						irsp->ulpStatus,
3390 						irsp->ulpIoTag,
3391 						irsp->ulpContext);
3392 			}
3393 			break;
3394 		}
3395 
3396 		if (free_saveq) {
3397 			list_for_each_entry_safe(rspiocbp, next_iocb,
3398 						 &saveq->list, list) {
3399 				list_del_init(&rspiocbp->list);
3400 				__lpfc_sli_release_iocbq(phba, rspiocbp);
3401 			}
3402 			__lpfc_sli_release_iocbq(phba, saveq);
3403 		}
3404 		rspiocbp = NULL;
3405 	}
3406 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3407 	return rspiocbp;
3408 }
3409 
3410 /**
3411  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
3412  * @phba: Pointer to HBA context object.
3413  * @pring: Pointer to driver SLI ring object.
3414  * @mask: Host attention register mask for this ring.
3415  *
3416  * This routine wraps the actual slow_ring event process routine from the
3417  * API jump table function pointer from the lpfc_hba struct.
3418  **/
3419 void
3420 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
3421 				struct lpfc_sli_ring *pring, uint32_t mask)
3422 {
3423 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
3424 }
3425 
3426 /**
3427  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
3428  * @phba: Pointer to HBA context object.
3429  * @pring: Pointer to driver SLI ring object.
3430  * @mask: Host attention register mask for this ring.
3431  *
3432  * This function is called from the worker thread when there is a ring event
3433  * for non-fcp rings. The caller does not hold any lock. The function will
3434  * remove each response iocb in the response ring and calls the handle
3435  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3436  **/
3437 static void
3438 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
3439 				   struct lpfc_sli_ring *pring, uint32_t mask)
3440 {
3441 	struct lpfc_pgp *pgp;
3442 	IOCB_t *entry;
3443 	IOCB_t *irsp = NULL;
3444 	struct lpfc_iocbq *rspiocbp = NULL;
3445 	uint32_t portRspPut, portRspMax;
3446 	unsigned long iflag;
3447 	uint32_t status;
3448 
3449 	pgp = &phba->port_gp[pring->ringno];
3450 	spin_lock_irqsave(&phba->hbalock, iflag);
3451 	pring->stats.iocb_event++;
3452 
3453 	/*
3454 	 * The next available response entry should never exceed the maximum
3455 	 * entries.  If it does, treat it as an adapter hardware error.
3456 	 */
3457 	portRspMax = pring->sli.sli3.numRiocb;
3458 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3459 	if (portRspPut >= portRspMax) {
3460 		/*
3461 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3462 		 * rsp ring <portRspMax>
3463 		 */
3464 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3465 				"0303 Ring %d handler: portRspPut %d "
3466 				"is bigger than rsp ring %d\n",
3467 				pring->ringno, portRspPut, portRspMax);
3468 
3469 		phba->link_state = LPFC_HBA_ERROR;
3470 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3471 
3472 		phba->work_hs = HS_FFER3;
3473 		lpfc_handle_eratt(phba);
3474 
3475 		return;
3476 	}
3477 
3478 	rmb();
3479 	while (pring->sli.sli3.rspidx != portRspPut) {
3480 		/*
3481 		 * Build a completion list and call the appropriate handler.
3482 		 * The process is to get the next available response iocb, get
3483 		 * a free iocb from the list, copy the response data into the
3484 		 * free iocb, insert to the continuation list, and update the
3485 		 * next response index to slim.  This process makes response
3486 		 * iocb's in the ring available to DMA as fast as possible but
3487 		 * pays a penalty for a copy operation.  Since the iocb is
3488 		 * only 32 bytes, this penalty is considered small relative to
3489 		 * the PCI reads for register values and a slim write.  When
3490 		 * the ulpLe field is set, the entire Command has been
3491 		 * received.
3492 		 */
3493 		entry = lpfc_resp_iocb(phba, pring);
3494 
3495 		phba->last_completion_time = jiffies;
3496 		rspiocbp = __lpfc_sli_get_iocbq(phba);
3497 		if (rspiocbp == NULL) {
3498 			printk(KERN_ERR "%s: out of buffers! Failing "
3499 			       "completion.\n", __func__);
3500 			break;
3501 		}
3502 
3503 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
3504 				      phba->iocb_rsp_size);
3505 		irsp = &rspiocbp->iocb;
3506 
3507 		if (++pring->sli.sli3.rspidx >= portRspMax)
3508 			pring->sli.sli3.rspidx = 0;
3509 
3510 		if (pring->ringno == LPFC_ELS_RING) {
3511 			lpfc_debugfs_slow_ring_trc(phba,
3512 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
3513 				*(((uint32_t *) irsp) + 4),
3514 				*(((uint32_t *) irsp) + 6),
3515 				*(((uint32_t *) irsp) + 7));
3516 		}
3517 
3518 		writel(pring->sli.sli3.rspidx,
3519 			&phba->host_gp[pring->ringno].rspGetInx);
3520 
3521 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3522 		/* Handle the response IOCB */
3523 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
3524 		spin_lock_irqsave(&phba->hbalock, iflag);
3525 
3526 		/*
3527 		 * If the port response put pointer has not been updated, sync
3528 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
3529 		 * response put pointer.
3530 		 */
3531 		if (pring->sli.sli3.rspidx == portRspPut) {
3532 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3533 		}
3534 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
3535 
3536 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
3537 		/* At least one response entry has been freed */
3538 		pring->stats.iocb_rsp_full++;
3539 		/* SET RxRE_RSP in Chip Att register */
3540 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3541 		writel(status, phba->CAregaddr);
3542 		readl(phba->CAregaddr); /* flush */
3543 	}
3544 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3545 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3546 		pring->stats.iocb_cmd_empty++;
3547 
3548 		/* Force update of the local copy of cmdGetInx */
3549 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3550 		lpfc_sli_resume_iocb(phba, pring);
3551 
3552 		if ((pring->lpfc_sli_cmd_available))
3553 			(pring->lpfc_sli_cmd_available) (phba, pring);
3554 
3555 	}
3556 
3557 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3558 	return;
3559 }
3560 
3561 /**
3562  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
3563  * @phba: Pointer to HBA context object.
3564  * @pring: Pointer to driver SLI ring object.
3565  * @mask: Host attention register mask for this ring.
3566  *
3567  * This function is called from the worker thread when there is a pending
3568  * ELS response iocb on the driver internal slow-path response iocb worker
3569  * queue. The caller does not hold any lock. The function will remove each
3570  * response iocb from the response worker queue and calls the handle
3571  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3572  **/
3573 static void
3574 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
3575 				   struct lpfc_sli_ring *pring, uint32_t mask)
3576 {
3577 	struct lpfc_iocbq *irspiocbq;
3578 	struct hbq_dmabuf *dmabuf;
3579 	struct lpfc_cq_event *cq_event;
3580 	unsigned long iflag;
3581 
3582 	spin_lock_irqsave(&phba->hbalock, iflag);
3583 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
3584 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3585 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
3586 		/* Get the response iocb from the head of work queue */
3587 		spin_lock_irqsave(&phba->hbalock, iflag);
3588 		list_remove_head(&phba->sli4_hba.sp_queue_event,
3589 				 cq_event, struct lpfc_cq_event, list);
3590 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3591 
3592 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
3593 		case CQE_CODE_COMPL_WQE:
3594 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
3595 						 cq_event);
3596 			/* Translate ELS WCQE to response IOCBQ */
3597 			irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
3598 								   irspiocbq);
3599 			if (irspiocbq)
3600 				lpfc_sli_sp_handle_rspiocb(phba, pring,
3601 							   irspiocbq);
3602 			break;
3603 		case CQE_CODE_RECEIVE:
3604 		case CQE_CODE_RECEIVE_V1:
3605 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
3606 					      cq_event);
3607 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
3608 			break;
3609 		default:
3610 			break;
3611 		}
3612 	}
3613 }
3614 
3615 /**
3616  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
3617  * @phba: Pointer to HBA context object.
3618  * @pring: Pointer to driver SLI ring object.
3619  *
3620  * This function aborts all iocbs in the given ring and frees all the iocb
3621  * objects in txq. This function issues an abort iocb for all the iocb commands
3622  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3623  * the return of this function. The caller is not required to hold any locks.
3624  **/
3625 void
3626 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3627 {
3628 	LIST_HEAD(completions);
3629 	struct lpfc_iocbq *iocb, *next_iocb;
3630 
3631 	if (pring->ringno == LPFC_ELS_RING) {
3632 		lpfc_fabric_abort_hba(phba);
3633 	}
3634 
3635 	/* Error everything on txq and txcmplq
3636 	 * First do the txq.
3637 	 */
3638 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3639 		spin_lock_irq(&pring->ring_lock);
3640 		list_splice_init(&pring->txq, &completions);
3641 		pring->txq_cnt = 0;
3642 		spin_unlock_irq(&pring->ring_lock);
3643 
3644 		spin_lock_irq(&phba->hbalock);
3645 		/* Next issue ABTS for everything on the txcmplq */
3646 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3647 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3648 		spin_unlock_irq(&phba->hbalock);
3649 	} else {
3650 		spin_lock_irq(&phba->hbalock);
3651 		list_splice_init(&pring->txq, &completions);
3652 		pring->txq_cnt = 0;
3653 
3654 		/* Next issue ABTS for everything on the txcmplq */
3655 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3656 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3657 		spin_unlock_irq(&phba->hbalock);
3658 	}
3659 
3660 	/* Cancel all the IOCBs from the completions list */
3661 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
3662 			      IOERR_SLI_ABORTED);
3663 }
3664 
3665 /**
3666  * lpfc_sli_abort_wqe_ring - Abort all iocbs in the ring
3667  * @phba: Pointer to HBA context object.
3668  * @pring: Pointer to driver SLI ring object.
3669  *
3670  * This function aborts all iocbs in the given ring and frees all the iocb
3671  * objects in txq. This function issues an abort iocb for all the iocb commands
3672  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3673  * the return of this function. The caller is not required to hold any locks.
3674  **/
3675 void
3676 lpfc_sli_abort_wqe_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3677 {
3678 	LIST_HEAD(completions);
3679 	struct lpfc_iocbq *iocb, *next_iocb;
3680 
3681 	if (pring->ringno == LPFC_ELS_RING)
3682 		lpfc_fabric_abort_hba(phba);
3683 
3684 	spin_lock_irq(&phba->hbalock);
3685 	/* Next issue ABTS for everything on the txcmplq */
3686 	list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3687 		lpfc_sli4_abort_nvme_io(phba, pring, iocb);
3688 	spin_unlock_irq(&phba->hbalock);
3689 }
3690 
3691 
3692 /**
3693  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
3694  * @phba: Pointer to HBA context object.
3695  * @pring: Pointer to driver SLI ring object.
3696  *
3697  * This function aborts all iocbs in FCP rings and frees all the iocb
3698  * objects in txq. This function issues an abort iocb for all the iocb commands
3699  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3700  * the return of this function. The caller is not required to hold any locks.
3701  **/
3702 void
3703 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
3704 {
3705 	struct lpfc_sli *psli = &phba->sli;
3706 	struct lpfc_sli_ring  *pring;
3707 	uint32_t i;
3708 
3709 	/* Look on all the FCP Rings for the iotag */
3710 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3711 		for (i = 0; i < phba->cfg_fcp_io_channel; i++) {
3712 			pring = phba->sli4_hba.fcp_wq[i]->pring;
3713 			lpfc_sli_abort_iocb_ring(phba, pring);
3714 		}
3715 	} else {
3716 		pring = &psli->sli3_ring[LPFC_FCP_RING];
3717 		lpfc_sli_abort_iocb_ring(phba, pring);
3718 	}
3719 }
3720 
3721 /**
3722  * lpfc_sli_abort_nvme_rings - Abort all wqes in all NVME rings
3723  * @phba: Pointer to HBA context object.
3724  *
3725  * This function aborts all wqes in NVME rings. This function issues an
3726  * abort wqe for all the outstanding IO commands in txcmplq. The iocbs in
3727  * the txcmplq is not guaranteed to complete before the return of this
3728  * function. The caller is not required to hold any locks.
3729  **/
3730 void
3731 lpfc_sli_abort_nvme_rings(struct lpfc_hba *phba)
3732 {
3733 	struct lpfc_sli_ring  *pring;
3734 	uint32_t i;
3735 
3736 	if (phba->sli_rev < LPFC_SLI_REV4)
3737 		return;
3738 
3739 	/* Abort all IO on each NVME ring. */
3740 	for (i = 0; i < phba->cfg_nvme_io_channel; i++) {
3741 		pring = phba->sli4_hba.nvme_wq[i]->pring;
3742 		lpfc_sli_abort_wqe_ring(phba, pring);
3743 	}
3744 }
3745 
3746 
3747 /**
3748  * lpfc_sli_flush_fcp_rings - flush all iocbs in the fcp ring
3749  * @phba: Pointer to HBA context object.
3750  *
3751  * This function flushes all iocbs in the fcp ring and frees all the iocb
3752  * objects in txq and txcmplq. This function will not issue abort iocbs
3753  * for all the iocb commands in txcmplq, they will just be returned with
3754  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
3755  * slot has been permanently disabled.
3756  **/
3757 void
3758 lpfc_sli_flush_fcp_rings(struct lpfc_hba *phba)
3759 {
3760 	LIST_HEAD(txq);
3761 	LIST_HEAD(txcmplq);
3762 	struct lpfc_sli *psli = &phba->sli;
3763 	struct lpfc_sli_ring  *pring;
3764 	uint32_t i;
3765 
3766 	spin_lock_irq(&phba->hbalock);
3767 	/* Indicate the I/O queues are flushed */
3768 	phba->hba_flag |= HBA_FCP_IOQ_FLUSH;
3769 	spin_unlock_irq(&phba->hbalock);
3770 
3771 	/* Look on all the FCP Rings for the iotag */
3772 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3773 		for (i = 0; i < phba->cfg_fcp_io_channel; i++) {
3774 			pring = phba->sli4_hba.fcp_wq[i]->pring;
3775 
3776 			spin_lock_irq(&pring->ring_lock);
3777 			/* Retrieve everything on txq */
3778 			list_splice_init(&pring->txq, &txq);
3779 			/* Retrieve everything on the txcmplq */
3780 			list_splice_init(&pring->txcmplq, &txcmplq);
3781 			pring->txq_cnt = 0;
3782 			pring->txcmplq_cnt = 0;
3783 			spin_unlock_irq(&pring->ring_lock);
3784 
3785 			/* Flush the txq */
3786 			lpfc_sli_cancel_iocbs(phba, &txq,
3787 					      IOSTAT_LOCAL_REJECT,
3788 					      IOERR_SLI_DOWN);
3789 			/* Flush the txcmpq */
3790 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
3791 					      IOSTAT_LOCAL_REJECT,
3792 					      IOERR_SLI_DOWN);
3793 		}
3794 	} else {
3795 		pring = &psli->sli3_ring[LPFC_FCP_RING];
3796 
3797 		spin_lock_irq(&phba->hbalock);
3798 		/* Retrieve everything on txq */
3799 		list_splice_init(&pring->txq, &txq);
3800 		/* Retrieve everything on the txcmplq */
3801 		list_splice_init(&pring->txcmplq, &txcmplq);
3802 		pring->txq_cnt = 0;
3803 		pring->txcmplq_cnt = 0;
3804 		spin_unlock_irq(&phba->hbalock);
3805 
3806 		/* Flush the txq */
3807 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
3808 				      IOERR_SLI_DOWN);
3809 		/* Flush the txcmpq */
3810 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
3811 				      IOERR_SLI_DOWN);
3812 	}
3813 }
3814 
3815 /**
3816  * lpfc_sli_flush_nvme_rings - flush all wqes in the nvme rings
3817  * @phba: Pointer to HBA context object.
3818  *
3819  * This function flushes all wqes in the nvme rings and frees all resources
3820  * in the txcmplq. This function does not issue abort wqes for the IO
3821  * commands in txcmplq, they will just be returned with
3822  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
3823  * slot has been permanently disabled.
3824  **/
3825 void
3826 lpfc_sli_flush_nvme_rings(struct lpfc_hba *phba)
3827 {
3828 	LIST_HEAD(txcmplq);
3829 	struct lpfc_sli_ring  *pring;
3830 	uint32_t i;
3831 
3832 	if (phba->sli_rev < LPFC_SLI_REV4)
3833 		return;
3834 
3835 	/* Hint to other driver operations that a flush is in progress. */
3836 	spin_lock_irq(&phba->hbalock);
3837 	phba->hba_flag |= HBA_NVME_IOQ_FLUSH;
3838 	spin_unlock_irq(&phba->hbalock);
3839 
3840 	/* Cycle through all NVME rings and complete each IO with
3841 	 * a local driver reason code.  This is a flush so no
3842 	 * abort exchange to FW.
3843 	 */
3844 	for (i = 0; i < phba->cfg_nvme_io_channel; i++) {
3845 		pring = phba->sli4_hba.nvme_wq[i]->pring;
3846 
3847 		/* Retrieve everything on the txcmplq */
3848 		spin_lock_irq(&pring->ring_lock);
3849 		list_splice_init(&pring->txcmplq, &txcmplq);
3850 		pring->txcmplq_cnt = 0;
3851 		spin_unlock_irq(&pring->ring_lock);
3852 
3853 		/* Flush the txcmpq &&&PAE */
3854 		lpfc_sli_cancel_iocbs(phba, &txcmplq,
3855 				      IOSTAT_LOCAL_REJECT,
3856 				      IOERR_SLI_DOWN);
3857 	}
3858 }
3859 
3860 /**
3861  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
3862  * @phba: Pointer to HBA context object.
3863  * @mask: Bit mask to be checked.
3864  *
3865  * This function reads the host status register and compares
3866  * with the provided bit mask to check if HBA completed
3867  * the restart. This function will wait in a loop for the
3868  * HBA to complete restart. If the HBA does not restart within
3869  * 15 iterations, the function will reset the HBA again. The
3870  * function returns 1 when HBA fail to restart otherwise returns
3871  * zero.
3872  **/
3873 static int
3874 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
3875 {
3876 	uint32_t status;
3877 	int i = 0;
3878 	int retval = 0;
3879 
3880 	/* Read the HBA Host Status Register */
3881 	if (lpfc_readl(phba->HSregaddr, &status))
3882 		return 1;
3883 
3884 	/*
3885 	 * Check status register every 100ms for 5 retries, then every
3886 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
3887 	 * every 2.5 sec for 4.
3888 	 * Break our of the loop if errors occurred during init.
3889 	 */
3890 	while (((status & mask) != mask) &&
3891 	       !(status & HS_FFERM) &&
3892 	       i++ < 20) {
3893 
3894 		if (i <= 5)
3895 			msleep(10);
3896 		else if (i <= 10)
3897 			msleep(500);
3898 		else
3899 			msleep(2500);
3900 
3901 		if (i == 15) {
3902 				/* Do post */
3903 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
3904 			lpfc_sli_brdrestart(phba);
3905 		}
3906 		/* Read the HBA Host Status Register */
3907 		if (lpfc_readl(phba->HSregaddr, &status)) {
3908 			retval = 1;
3909 			break;
3910 		}
3911 	}
3912 
3913 	/* Check to see if any errors occurred during init */
3914 	if ((status & HS_FFERM) || (i >= 20)) {
3915 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3916 				"2751 Adapter failed to restart, "
3917 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
3918 				status,
3919 				readl(phba->MBslimaddr + 0xa8),
3920 				readl(phba->MBslimaddr + 0xac));
3921 		phba->link_state = LPFC_HBA_ERROR;
3922 		retval = 1;
3923 	}
3924 
3925 	return retval;
3926 }
3927 
3928 /**
3929  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
3930  * @phba: Pointer to HBA context object.
3931  * @mask: Bit mask to be checked.
3932  *
3933  * This function checks the host status register to check if HBA is
3934  * ready. This function will wait in a loop for the HBA to be ready
3935  * If the HBA is not ready , the function will will reset the HBA PCI
3936  * function again. The function returns 1 when HBA fail to be ready
3937  * otherwise returns zero.
3938  **/
3939 static int
3940 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
3941 {
3942 	uint32_t status;
3943 	int retval = 0;
3944 
3945 	/* Read the HBA Host Status Register */
3946 	status = lpfc_sli4_post_status_check(phba);
3947 
3948 	if (status) {
3949 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
3950 		lpfc_sli_brdrestart(phba);
3951 		status = lpfc_sli4_post_status_check(phba);
3952 	}
3953 
3954 	/* Check to see if any errors occurred during init */
3955 	if (status) {
3956 		phba->link_state = LPFC_HBA_ERROR;
3957 		retval = 1;
3958 	} else
3959 		phba->sli4_hba.intr_enable = 0;
3960 
3961 	return retval;
3962 }
3963 
3964 /**
3965  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
3966  * @phba: Pointer to HBA context object.
3967  * @mask: Bit mask to be checked.
3968  *
3969  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
3970  * from the API jump table function pointer from the lpfc_hba struct.
3971  **/
3972 int
3973 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
3974 {
3975 	return phba->lpfc_sli_brdready(phba, mask);
3976 }
3977 
3978 #define BARRIER_TEST_PATTERN (0xdeadbeef)
3979 
3980 /**
3981  * lpfc_reset_barrier - Make HBA ready for HBA reset
3982  * @phba: Pointer to HBA context object.
3983  *
3984  * This function is called before resetting an HBA. This function is called
3985  * with hbalock held and requests HBA to quiesce DMAs before a reset.
3986  **/
3987 void lpfc_reset_barrier(struct lpfc_hba *phba)
3988 {
3989 	uint32_t __iomem *resp_buf;
3990 	uint32_t __iomem *mbox_buf;
3991 	volatile uint32_t mbox;
3992 	uint32_t hc_copy, ha_copy, resp_data;
3993 	int  i;
3994 	uint8_t hdrtype;
3995 
3996 	lockdep_assert_held(&phba->hbalock);
3997 
3998 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
3999 	if (hdrtype != 0x80 ||
4000 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4001 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4002 		return;
4003 
4004 	/*
4005 	 * Tell the other part of the chip to suspend temporarily all
4006 	 * its DMA activity.
4007 	 */
4008 	resp_buf = phba->MBslimaddr;
4009 
4010 	/* Disable the error attention */
4011 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4012 		return;
4013 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4014 	readl(phba->HCregaddr); /* flush */
4015 	phba->link_flag |= LS_IGNORE_ERATT;
4016 
4017 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4018 		return;
4019 	if (ha_copy & HA_ERATT) {
4020 		/* Clear Chip error bit */
4021 		writel(HA_ERATT, phba->HAregaddr);
4022 		phba->pport->stopped = 1;
4023 	}
4024 
4025 	mbox = 0;
4026 	((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
4027 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
4028 
4029 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4030 	mbox_buf = phba->MBslimaddr;
4031 	writel(mbox, mbox_buf);
4032 
4033 	for (i = 0; i < 50; i++) {
4034 		if (lpfc_readl((resp_buf + 1), &resp_data))
4035 			return;
4036 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4037 			mdelay(1);
4038 		else
4039 			break;
4040 	}
4041 	resp_data = 0;
4042 	if (lpfc_readl((resp_buf + 1), &resp_data))
4043 		return;
4044 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4045 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4046 		    phba->pport->stopped)
4047 			goto restore_hc;
4048 		else
4049 			goto clear_errat;
4050 	}
4051 
4052 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
4053 	resp_data = 0;
4054 	for (i = 0; i < 500; i++) {
4055 		if (lpfc_readl(resp_buf, &resp_data))
4056 			return;
4057 		if (resp_data != mbox)
4058 			mdelay(1);
4059 		else
4060 			break;
4061 	}
4062 
4063 clear_errat:
4064 
4065 	while (++i < 500) {
4066 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4067 			return;
4068 		if (!(ha_copy & HA_ERATT))
4069 			mdelay(1);
4070 		else
4071 			break;
4072 	}
4073 
4074 	if (readl(phba->HAregaddr) & HA_ERATT) {
4075 		writel(HA_ERATT, phba->HAregaddr);
4076 		phba->pport->stopped = 1;
4077 	}
4078 
4079 restore_hc:
4080 	phba->link_flag &= ~LS_IGNORE_ERATT;
4081 	writel(hc_copy, phba->HCregaddr);
4082 	readl(phba->HCregaddr); /* flush */
4083 }
4084 
4085 /**
4086  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4087  * @phba: Pointer to HBA context object.
4088  *
4089  * This function issues a kill_board mailbox command and waits for
4090  * the error attention interrupt. This function is called for stopping
4091  * the firmware processing. The caller is not required to hold any
4092  * locks. This function calls lpfc_hba_down_post function to free
4093  * any pending commands after the kill. The function will return 1 when it
4094  * fails to kill the board else will return 0.
4095  **/
4096 int
4097 lpfc_sli_brdkill(struct lpfc_hba *phba)
4098 {
4099 	struct lpfc_sli *psli;
4100 	LPFC_MBOXQ_t *pmb;
4101 	uint32_t status;
4102 	uint32_t ha_copy;
4103 	int retval;
4104 	int i = 0;
4105 
4106 	psli = &phba->sli;
4107 
4108 	/* Kill HBA */
4109 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4110 			"0329 Kill HBA Data: x%x x%x\n",
4111 			phba->pport->port_state, psli->sli_flag);
4112 
4113 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4114 	if (!pmb)
4115 		return 1;
4116 
4117 	/* Disable the error attention */
4118 	spin_lock_irq(&phba->hbalock);
4119 	if (lpfc_readl(phba->HCregaddr, &status)) {
4120 		spin_unlock_irq(&phba->hbalock);
4121 		mempool_free(pmb, phba->mbox_mem_pool);
4122 		return 1;
4123 	}
4124 	status &= ~HC_ERINT_ENA;
4125 	writel(status, phba->HCregaddr);
4126 	readl(phba->HCregaddr); /* flush */
4127 	phba->link_flag |= LS_IGNORE_ERATT;
4128 	spin_unlock_irq(&phba->hbalock);
4129 
4130 	lpfc_kill_board(phba, pmb);
4131 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4132 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4133 
4134 	if (retval != MBX_SUCCESS) {
4135 		if (retval != MBX_BUSY)
4136 			mempool_free(pmb, phba->mbox_mem_pool);
4137 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4138 				"2752 KILL_BOARD command failed retval %d\n",
4139 				retval);
4140 		spin_lock_irq(&phba->hbalock);
4141 		phba->link_flag &= ~LS_IGNORE_ERATT;
4142 		spin_unlock_irq(&phba->hbalock);
4143 		return 1;
4144 	}
4145 
4146 	spin_lock_irq(&phba->hbalock);
4147 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
4148 	spin_unlock_irq(&phba->hbalock);
4149 
4150 	mempool_free(pmb, phba->mbox_mem_pool);
4151 
4152 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
4153 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
4154 	 * 3 seconds we still set HBA_ERROR state because the status of the
4155 	 * board is now undefined.
4156 	 */
4157 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4158 		return 1;
4159 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
4160 		mdelay(100);
4161 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4162 			return 1;
4163 	}
4164 
4165 	del_timer_sync(&psli->mbox_tmo);
4166 	if (ha_copy & HA_ERATT) {
4167 		writel(HA_ERATT, phba->HAregaddr);
4168 		phba->pport->stopped = 1;
4169 	}
4170 	spin_lock_irq(&phba->hbalock);
4171 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4172 	psli->mbox_active = NULL;
4173 	phba->link_flag &= ~LS_IGNORE_ERATT;
4174 	spin_unlock_irq(&phba->hbalock);
4175 
4176 	lpfc_hba_down_post(phba);
4177 	phba->link_state = LPFC_HBA_ERROR;
4178 
4179 	return ha_copy & HA_ERATT ? 0 : 1;
4180 }
4181 
4182 /**
4183  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
4184  * @phba: Pointer to HBA context object.
4185  *
4186  * This function resets the HBA by writing HC_INITFF to the control
4187  * register. After the HBA resets, this function resets all the iocb ring
4188  * indices. This function disables PCI layer parity checking during
4189  * the reset.
4190  * This function returns 0 always.
4191  * The caller is not required to hold any locks.
4192  **/
4193 int
4194 lpfc_sli_brdreset(struct lpfc_hba *phba)
4195 {
4196 	struct lpfc_sli *psli;
4197 	struct lpfc_sli_ring *pring;
4198 	uint16_t cfg_value;
4199 	int i;
4200 
4201 	psli = &phba->sli;
4202 
4203 	/* Reset HBA */
4204 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4205 			"0325 Reset HBA Data: x%x x%x\n",
4206 			phba->pport->port_state, psli->sli_flag);
4207 
4208 	/* perform board reset */
4209 	phba->fc_eventTag = 0;
4210 	phba->link_events = 0;
4211 	phba->pport->fc_myDID = 0;
4212 	phba->pport->fc_prevDID = 0;
4213 
4214 	/* Turn off parity checking and serr during the physical reset */
4215 	pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value);
4216 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
4217 			      (cfg_value &
4218 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4219 
4220 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4221 
4222 	/* Now toggle INITFF bit in the Host Control Register */
4223 	writel(HC_INITFF, phba->HCregaddr);
4224 	mdelay(1);
4225 	readl(phba->HCregaddr); /* flush */
4226 	writel(0, phba->HCregaddr);
4227 	readl(phba->HCregaddr); /* flush */
4228 
4229 	/* Restore PCI cmd register */
4230 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4231 
4232 	/* Initialize relevant SLI info */
4233 	for (i = 0; i < psli->num_rings; i++) {
4234 		pring = &psli->sli3_ring[i];
4235 		pring->flag = 0;
4236 		pring->sli.sli3.rspidx = 0;
4237 		pring->sli.sli3.next_cmdidx  = 0;
4238 		pring->sli.sli3.local_getidx = 0;
4239 		pring->sli.sli3.cmdidx = 0;
4240 		pring->missbufcnt = 0;
4241 	}
4242 
4243 	phba->link_state = LPFC_WARM_START;
4244 	return 0;
4245 }
4246 
4247 /**
4248  * lpfc_sli4_brdreset - Reset a sli-4 HBA
4249  * @phba: Pointer to HBA context object.
4250  *
4251  * This function resets a SLI4 HBA. This function disables PCI layer parity
4252  * checking during resets the device. The caller is not required to hold
4253  * any locks.
4254  *
4255  * This function returns 0 always.
4256  **/
4257 int
4258 lpfc_sli4_brdreset(struct lpfc_hba *phba)
4259 {
4260 	struct lpfc_sli *psli = &phba->sli;
4261 	uint16_t cfg_value;
4262 	int rc = 0;
4263 
4264 	/* Reset HBA */
4265 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4266 			"0295 Reset HBA Data: x%x x%x x%x\n",
4267 			phba->pport->port_state, psli->sli_flag,
4268 			phba->hba_flag);
4269 
4270 	/* perform board reset */
4271 	phba->fc_eventTag = 0;
4272 	phba->link_events = 0;
4273 	phba->pport->fc_myDID = 0;
4274 	phba->pport->fc_prevDID = 0;
4275 
4276 	spin_lock_irq(&phba->hbalock);
4277 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
4278 	phba->fcf.fcf_flag = 0;
4279 	spin_unlock_irq(&phba->hbalock);
4280 
4281 	/* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
4282 	if (phba->hba_flag & HBA_FW_DUMP_OP) {
4283 		phba->hba_flag &= ~HBA_FW_DUMP_OP;
4284 		return rc;
4285 	}
4286 
4287 	/* Now physically reset the device */
4288 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4289 			"0389 Performing PCI function reset!\n");
4290 
4291 	/* Turn off parity checking and serr during the physical reset */
4292 	pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value);
4293 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
4294 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4295 
4296 	/* Perform FCoE PCI function reset before freeing queue memory */
4297 	rc = lpfc_pci_function_reset(phba);
4298 	lpfc_sli4_queue_destroy(phba);
4299 
4300 	/* Restore PCI cmd register */
4301 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4302 
4303 	return rc;
4304 }
4305 
4306 /**
4307  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
4308  * @phba: Pointer to HBA context object.
4309  *
4310  * This function is called in the SLI initialization code path to
4311  * restart the HBA. The caller is not required to hold any lock.
4312  * This function writes MBX_RESTART mailbox command to the SLIM and
4313  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
4314  * function to free any pending commands. The function enables
4315  * POST only during the first initialization. The function returns zero.
4316  * The function does not guarantee completion of MBX_RESTART mailbox
4317  * command before the return of this function.
4318  **/
4319 static int
4320 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
4321 {
4322 	MAILBOX_t *mb;
4323 	struct lpfc_sli *psli;
4324 	volatile uint32_t word0;
4325 	void __iomem *to_slim;
4326 	uint32_t hba_aer_enabled;
4327 
4328 	spin_lock_irq(&phba->hbalock);
4329 
4330 	/* Take PCIe device Advanced Error Reporting (AER) state */
4331 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4332 
4333 	psli = &phba->sli;
4334 
4335 	/* Restart HBA */
4336 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4337 			"0337 Restart HBA Data: x%x x%x\n",
4338 			phba->pport->port_state, psli->sli_flag);
4339 
4340 	word0 = 0;
4341 	mb = (MAILBOX_t *) &word0;
4342 	mb->mbxCommand = MBX_RESTART;
4343 	mb->mbxHc = 1;
4344 
4345 	lpfc_reset_barrier(phba);
4346 
4347 	to_slim = phba->MBslimaddr;
4348 	writel(*(uint32_t *) mb, to_slim);
4349 	readl(to_slim); /* flush */
4350 
4351 	/* Only skip post after fc_ffinit is completed */
4352 	if (phba->pport->port_state)
4353 		word0 = 1;	/* This is really setting up word1 */
4354 	else
4355 		word0 = 0;	/* This is really setting up word1 */
4356 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
4357 	writel(*(uint32_t *) mb, to_slim);
4358 	readl(to_slim); /* flush */
4359 
4360 	lpfc_sli_brdreset(phba);
4361 	phba->pport->stopped = 0;
4362 	phba->link_state = LPFC_INIT_START;
4363 	phba->hba_flag = 0;
4364 	spin_unlock_irq(&phba->hbalock);
4365 
4366 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4367 	psli->stats_start = get_seconds();
4368 
4369 	/* Give the INITFF and Post time to settle. */
4370 	mdelay(100);
4371 
4372 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4373 	if (hba_aer_enabled)
4374 		pci_disable_pcie_error_reporting(phba->pcidev);
4375 
4376 	lpfc_hba_down_post(phba);
4377 
4378 	return 0;
4379 }
4380 
4381 /**
4382  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
4383  * @phba: Pointer to HBA context object.
4384  *
4385  * This function is called in the SLI initialization code path to restart
4386  * a SLI4 HBA. The caller is not required to hold any lock.
4387  * At the end of the function, it calls lpfc_hba_down_post function to
4388  * free any pending commands.
4389  **/
4390 static int
4391 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
4392 {
4393 	struct lpfc_sli *psli = &phba->sli;
4394 	uint32_t hba_aer_enabled;
4395 	int rc;
4396 
4397 	/* Restart HBA */
4398 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4399 			"0296 Restart HBA Data: x%x x%x\n",
4400 			phba->pport->port_state, psli->sli_flag);
4401 
4402 	/* Take PCIe device Advanced Error Reporting (AER) state */
4403 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4404 
4405 	rc = lpfc_sli4_brdreset(phba);
4406 
4407 	spin_lock_irq(&phba->hbalock);
4408 	phba->pport->stopped = 0;
4409 	phba->link_state = LPFC_INIT_START;
4410 	phba->hba_flag = 0;
4411 	spin_unlock_irq(&phba->hbalock);
4412 
4413 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4414 	psli->stats_start = get_seconds();
4415 
4416 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4417 	if (hba_aer_enabled)
4418 		pci_disable_pcie_error_reporting(phba->pcidev);
4419 
4420 	lpfc_hba_down_post(phba);
4421 
4422 	return rc;
4423 }
4424 
4425 /**
4426  * lpfc_sli_brdrestart - Wrapper func for restarting hba
4427  * @phba: Pointer to HBA context object.
4428  *
4429  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
4430  * API jump table function pointer from the lpfc_hba struct.
4431 **/
4432 int
4433 lpfc_sli_brdrestart(struct lpfc_hba *phba)
4434 {
4435 	return phba->lpfc_sli_brdrestart(phba);
4436 }
4437 
4438 /**
4439  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
4440  * @phba: Pointer to HBA context object.
4441  *
4442  * This function is called after a HBA restart to wait for successful
4443  * restart of the HBA. Successful restart of the HBA is indicated by
4444  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
4445  * iteration, the function will restart the HBA again. The function returns
4446  * zero if HBA successfully restarted else returns negative error code.
4447  **/
4448 static int
4449 lpfc_sli_chipset_init(struct lpfc_hba *phba)
4450 {
4451 	uint32_t status, i = 0;
4452 
4453 	/* Read the HBA Host Status Register */
4454 	if (lpfc_readl(phba->HSregaddr, &status))
4455 		return -EIO;
4456 
4457 	/* Check status register to see what current state is */
4458 	i = 0;
4459 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
4460 
4461 		/* Check every 10ms for 10 retries, then every 100ms for 90
4462 		 * retries, then every 1 sec for 50 retires for a total of
4463 		 * ~60 seconds before reset the board again and check every
4464 		 * 1 sec for 50 retries. The up to 60 seconds before the
4465 		 * board ready is required by the Falcon FIPS zeroization
4466 		 * complete, and any reset the board in between shall cause
4467 		 * restart of zeroization, further delay the board ready.
4468 		 */
4469 		if (i++ >= 200) {
4470 			/* Adapter failed to init, timeout, status reg
4471 			   <status> */
4472 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4473 					"0436 Adapter failed to init, "
4474 					"timeout, status reg x%x, "
4475 					"FW Data: A8 x%x AC x%x\n", status,
4476 					readl(phba->MBslimaddr + 0xa8),
4477 					readl(phba->MBslimaddr + 0xac));
4478 			phba->link_state = LPFC_HBA_ERROR;
4479 			return -ETIMEDOUT;
4480 		}
4481 
4482 		/* Check to see if any errors occurred during init */
4483 		if (status & HS_FFERM) {
4484 			/* ERROR: During chipset initialization */
4485 			/* Adapter failed to init, chipset, status reg
4486 			   <status> */
4487 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4488 					"0437 Adapter failed to init, "
4489 					"chipset, status reg x%x, "
4490 					"FW Data: A8 x%x AC x%x\n", status,
4491 					readl(phba->MBslimaddr + 0xa8),
4492 					readl(phba->MBslimaddr + 0xac));
4493 			phba->link_state = LPFC_HBA_ERROR;
4494 			return -EIO;
4495 		}
4496 
4497 		if (i <= 10)
4498 			msleep(10);
4499 		else if (i <= 100)
4500 			msleep(100);
4501 		else
4502 			msleep(1000);
4503 
4504 		if (i == 150) {
4505 			/* Do post */
4506 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4507 			lpfc_sli_brdrestart(phba);
4508 		}
4509 		/* Read the HBA Host Status Register */
4510 		if (lpfc_readl(phba->HSregaddr, &status))
4511 			return -EIO;
4512 	}
4513 
4514 	/* Check to see if any errors occurred during init */
4515 	if (status & HS_FFERM) {
4516 		/* ERROR: During chipset initialization */
4517 		/* Adapter failed to init, chipset, status reg <status> */
4518 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4519 				"0438 Adapter failed to init, chipset, "
4520 				"status reg x%x, "
4521 				"FW Data: A8 x%x AC x%x\n", status,
4522 				readl(phba->MBslimaddr + 0xa8),
4523 				readl(phba->MBslimaddr + 0xac));
4524 		phba->link_state = LPFC_HBA_ERROR;
4525 		return -EIO;
4526 	}
4527 
4528 	/* Clear all interrupt enable conditions */
4529 	writel(0, phba->HCregaddr);
4530 	readl(phba->HCregaddr); /* flush */
4531 
4532 	/* setup host attn register */
4533 	writel(0xffffffff, phba->HAregaddr);
4534 	readl(phba->HAregaddr); /* flush */
4535 	return 0;
4536 }
4537 
4538 /**
4539  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
4540  *
4541  * This function calculates and returns the number of HBQs required to be
4542  * configured.
4543  **/
4544 int
4545 lpfc_sli_hbq_count(void)
4546 {
4547 	return ARRAY_SIZE(lpfc_hbq_defs);
4548 }
4549 
4550 /**
4551  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
4552  *
4553  * This function adds the number of hbq entries in every HBQ to get
4554  * the total number of hbq entries required for the HBA and returns
4555  * the total count.
4556  **/
4557 static int
4558 lpfc_sli_hbq_entry_count(void)
4559 {
4560 	int  hbq_count = lpfc_sli_hbq_count();
4561 	int  count = 0;
4562 	int  i;
4563 
4564 	for (i = 0; i < hbq_count; ++i)
4565 		count += lpfc_hbq_defs[i]->entry_count;
4566 	return count;
4567 }
4568 
4569 /**
4570  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
4571  *
4572  * This function calculates amount of memory required for all hbq entries
4573  * to be configured and returns the total memory required.
4574  **/
4575 int
4576 lpfc_sli_hbq_size(void)
4577 {
4578 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
4579 }
4580 
4581 /**
4582  * lpfc_sli_hbq_setup - configure and initialize HBQs
4583  * @phba: Pointer to HBA context object.
4584  *
4585  * This function is called during the SLI initialization to configure
4586  * all the HBQs and post buffers to the HBQ. The caller is not
4587  * required to hold any locks. This function will return zero if successful
4588  * else it will return negative error code.
4589  **/
4590 static int
4591 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
4592 {
4593 	int  hbq_count = lpfc_sli_hbq_count();
4594 	LPFC_MBOXQ_t *pmb;
4595 	MAILBOX_t *pmbox;
4596 	uint32_t hbqno;
4597 	uint32_t hbq_entry_index;
4598 
4599 				/* Get a Mailbox buffer to setup mailbox
4600 				 * commands for HBA initialization
4601 				 */
4602 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4603 
4604 	if (!pmb)
4605 		return -ENOMEM;
4606 
4607 	pmbox = &pmb->u.mb;
4608 
4609 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
4610 	phba->link_state = LPFC_INIT_MBX_CMDS;
4611 	phba->hbq_in_use = 1;
4612 
4613 	hbq_entry_index = 0;
4614 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
4615 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
4616 		phba->hbqs[hbqno].hbqPutIdx      = 0;
4617 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
4618 		phba->hbqs[hbqno].entry_count =
4619 			lpfc_hbq_defs[hbqno]->entry_count;
4620 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
4621 			hbq_entry_index, pmb);
4622 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
4623 
4624 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
4625 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
4626 			   mbxStatus <status>, ring <num> */
4627 
4628 			lpfc_printf_log(phba, KERN_ERR,
4629 					LOG_SLI | LOG_VPORT,
4630 					"1805 Adapter failed to init. "
4631 					"Data: x%x x%x x%x\n",
4632 					pmbox->mbxCommand,
4633 					pmbox->mbxStatus, hbqno);
4634 
4635 			phba->link_state = LPFC_HBA_ERROR;
4636 			mempool_free(pmb, phba->mbox_mem_pool);
4637 			return -ENXIO;
4638 		}
4639 	}
4640 	phba->hbq_count = hbq_count;
4641 
4642 	mempool_free(pmb, phba->mbox_mem_pool);
4643 
4644 	/* Initially populate or replenish the HBQs */
4645 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
4646 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
4647 	return 0;
4648 }
4649 
4650 /**
4651  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
4652  * @phba: Pointer to HBA context object.
4653  *
4654  * This function is called during the SLI initialization to configure
4655  * all the HBQs and post buffers to the HBQ. The caller is not
4656  * required to hold any locks. This function will return zero if successful
4657  * else it will return negative error code.
4658  **/
4659 static int
4660 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
4661 {
4662 	phba->hbq_in_use = 1;
4663 	phba->hbqs[LPFC_ELS_HBQ].entry_count =
4664 		lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
4665 	phba->hbq_count = 1;
4666 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
4667 	/* Initially populate or replenish the HBQs */
4668 	return 0;
4669 }
4670 
4671 /**
4672  * lpfc_sli_config_port - Issue config port mailbox command
4673  * @phba: Pointer to HBA context object.
4674  * @sli_mode: sli mode - 2/3
4675  *
4676  * This function is called by the sli initialization code path
4677  * to issue config_port mailbox command. This function restarts the
4678  * HBA firmware and issues a config_port mailbox command to configure
4679  * the SLI interface in the sli mode specified by sli_mode
4680  * variable. The caller is not required to hold any locks.
4681  * The function returns 0 if successful, else returns negative error
4682  * code.
4683  **/
4684 int
4685 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
4686 {
4687 	LPFC_MBOXQ_t *pmb;
4688 	uint32_t resetcount = 0, rc = 0, done = 0;
4689 
4690 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4691 	if (!pmb) {
4692 		phba->link_state = LPFC_HBA_ERROR;
4693 		return -ENOMEM;
4694 	}
4695 
4696 	phba->sli_rev = sli_mode;
4697 	while (resetcount < 2 && !done) {
4698 		spin_lock_irq(&phba->hbalock);
4699 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
4700 		spin_unlock_irq(&phba->hbalock);
4701 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4702 		lpfc_sli_brdrestart(phba);
4703 		rc = lpfc_sli_chipset_init(phba);
4704 		if (rc)
4705 			break;
4706 
4707 		spin_lock_irq(&phba->hbalock);
4708 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4709 		spin_unlock_irq(&phba->hbalock);
4710 		resetcount++;
4711 
4712 		/* Call pre CONFIG_PORT mailbox command initialization.  A
4713 		 * value of 0 means the call was successful.  Any other
4714 		 * nonzero value is a failure, but if ERESTART is returned,
4715 		 * the driver may reset the HBA and try again.
4716 		 */
4717 		rc = lpfc_config_port_prep(phba);
4718 		if (rc == -ERESTART) {
4719 			phba->link_state = LPFC_LINK_UNKNOWN;
4720 			continue;
4721 		} else if (rc)
4722 			break;
4723 
4724 		phba->link_state = LPFC_INIT_MBX_CMDS;
4725 		lpfc_config_port(phba, pmb);
4726 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
4727 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
4728 					LPFC_SLI3_HBQ_ENABLED |
4729 					LPFC_SLI3_CRP_ENABLED |
4730 					LPFC_SLI3_BG_ENABLED |
4731 					LPFC_SLI3_DSS_ENABLED);
4732 		if (rc != MBX_SUCCESS) {
4733 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4734 				"0442 Adapter failed to init, mbxCmd x%x "
4735 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
4736 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
4737 			spin_lock_irq(&phba->hbalock);
4738 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
4739 			spin_unlock_irq(&phba->hbalock);
4740 			rc = -ENXIO;
4741 		} else {
4742 			/* Allow asynchronous mailbox command to go through */
4743 			spin_lock_irq(&phba->hbalock);
4744 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
4745 			spin_unlock_irq(&phba->hbalock);
4746 			done = 1;
4747 
4748 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
4749 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
4750 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
4751 					"3110 Port did not grant ASABT\n");
4752 		}
4753 	}
4754 	if (!done) {
4755 		rc = -EINVAL;
4756 		goto do_prep_failed;
4757 	}
4758 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
4759 		if (!pmb->u.mb.un.varCfgPort.cMA) {
4760 			rc = -ENXIO;
4761 			goto do_prep_failed;
4762 		}
4763 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
4764 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
4765 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
4766 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
4767 				phba->max_vpi : phba->max_vports;
4768 
4769 		} else
4770 			phba->max_vpi = 0;
4771 		phba->fips_level = 0;
4772 		phba->fips_spec_rev = 0;
4773 		if (pmb->u.mb.un.varCfgPort.gdss) {
4774 			phba->sli3_options |= LPFC_SLI3_DSS_ENABLED;
4775 			phba->fips_level = pmb->u.mb.un.varCfgPort.fips_level;
4776 			phba->fips_spec_rev = pmb->u.mb.un.varCfgPort.fips_rev;
4777 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4778 					"2850 Security Crypto Active. FIPS x%d "
4779 					"(Spec Rev: x%d)",
4780 					phba->fips_level, phba->fips_spec_rev);
4781 		}
4782 		if (pmb->u.mb.un.varCfgPort.sec_err) {
4783 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4784 					"2856 Config Port Security Crypto "
4785 					"Error: x%x ",
4786 					pmb->u.mb.un.varCfgPort.sec_err);
4787 		}
4788 		if (pmb->u.mb.un.varCfgPort.gerbm)
4789 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
4790 		if (pmb->u.mb.un.varCfgPort.gcrp)
4791 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
4792 
4793 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
4794 		phba->port_gp = phba->mbox->us.s3_pgp.port;
4795 
4796 		if (phba->cfg_enable_bg) {
4797 			if (pmb->u.mb.un.varCfgPort.gbg)
4798 				phba->sli3_options |= LPFC_SLI3_BG_ENABLED;
4799 			else
4800 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4801 						"0443 Adapter did not grant "
4802 						"BlockGuard\n");
4803 		}
4804 	} else {
4805 		phba->hbq_get = NULL;
4806 		phba->port_gp = phba->mbox->us.s2.port;
4807 		phba->max_vpi = 0;
4808 	}
4809 do_prep_failed:
4810 	mempool_free(pmb, phba->mbox_mem_pool);
4811 	return rc;
4812 }
4813 
4814 
4815 /**
4816  * lpfc_sli_hba_setup - SLI initialization function
4817  * @phba: Pointer to HBA context object.
4818  *
4819  * This function is the main SLI initialization function. This function
4820  * is called by the HBA initialization code, HBA reset code and HBA
4821  * error attention handler code. Caller is not required to hold any
4822  * locks. This function issues config_port mailbox command to configure
4823  * the SLI, setup iocb rings and HBQ rings. In the end the function
4824  * calls the config_port_post function to issue init_link mailbox
4825  * command and to start the discovery. The function will return zero
4826  * if successful, else it will return negative error code.
4827  **/
4828 int
4829 lpfc_sli_hba_setup(struct lpfc_hba *phba)
4830 {
4831 	uint32_t rc;
4832 	int  mode = 3, i;
4833 	int longs;
4834 
4835 	switch (phba->cfg_sli_mode) {
4836 	case 2:
4837 		if (phba->cfg_enable_npiv) {
4838 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4839 				"1824 NPIV enabled: Override sli_mode "
4840 				"parameter (%d) to auto (0).\n",
4841 				phba->cfg_sli_mode);
4842 			break;
4843 		}
4844 		mode = 2;
4845 		break;
4846 	case 0:
4847 	case 3:
4848 		break;
4849 	default:
4850 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4851 				"1819 Unrecognized sli_mode parameter: %d.\n",
4852 				phba->cfg_sli_mode);
4853 
4854 		break;
4855 	}
4856 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
4857 
4858 	rc = lpfc_sli_config_port(phba, mode);
4859 
4860 	if (rc && phba->cfg_sli_mode == 3)
4861 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4862 				"1820 Unable to select SLI-3.  "
4863 				"Not supported by adapter.\n");
4864 	if (rc && mode != 2)
4865 		rc = lpfc_sli_config_port(phba, 2);
4866 	else if (rc && mode == 2)
4867 		rc = lpfc_sli_config_port(phba, 3);
4868 	if (rc)
4869 		goto lpfc_sli_hba_setup_error;
4870 
4871 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
4872 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
4873 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
4874 		if (!rc) {
4875 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4876 					"2709 This device supports "
4877 					"Advanced Error Reporting (AER)\n");
4878 			spin_lock_irq(&phba->hbalock);
4879 			phba->hba_flag |= HBA_AER_ENABLED;
4880 			spin_unlock_irq(&phba->hbalock);
4881 		} else {
4882 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4883 					"2708 This device does not support "
4884 					"Advanced Error Reporting (AER): %d\n",
4885 					rc);
4886 			phba->cfg_aer_support = 0;
4887 		}
4888 	}
4889 
4890 	if (phba->sli_rev == 3) {
4891 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
4892 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
4893 	} else {
4894 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
4895 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
4896 		phba->sli3_options = 0;
4897 	}
4898 
4899 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4900 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
4901 			phba->sli_rev, phba->max_vpi);
4902 	rc = lpfc_sli_ring_map(phba);
4903 
4904 	if (rc)
4905 		goto lpfc_sli_hba_setup_error;
4906 
4907 	/* Initialize VPIs. */
4908 	if (phba->sli_rev == LPFC_SLI_REV3) {
4909 		/*
4910 		 * The VPI bitmask and physical ID array are allocated
4911 		 * and initialized once only - at driver load.  A port
4912 		 * reset doesn't need to reinitialize this memory.
4913 		 */
4914 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
4915 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
4916 			phba->vpi_bmask = kzalloc(longs * sizeof(unsigned long),
4917 						  GFP_KERNEL);
4918 			if (!phba->vpi_bmask) {
4919 				rc = -ENOMEM;
4920 				goto lpfc_sli_hba_setup_error;
4921 			}
4922 
4923 			phba->vpi_ids = kzalloc(
4924 					(phba->max_vpi+1) * sizeof(uint16_t),
4925 					GFP_KERNEL);
4926 			if (!phba->vpi_ids) {
4927 				kfree(phba->vpi_bmask);
4928 				rc = -ENOMEM;
4929 				goto lpfc_sli_hba_setup_error;
4930 			}
4931 			for (i = 0; i < phba->max_vpi; i++)
4932 				phba->vpi_ids[i] = i;
4933 		}
4934 	}
4935 
4936 	/* Init HBQs */
4937 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
4938 		rc = lpfc_sli_hbq_setup(phba);
4939 		if (rc)
4940 			goto lpfc_sli_hba_setup_error;
4941 	}
4942 	spin_lock_irq(&phba->hbalock);
4943 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
4944 	spin_unlock_irq(&phba->hbalock);
4945 
4946 	rc = lpfc_config_port_post(phba);
4947 	if (rc)
4948 		goto lpfc_sli_hba_setup_error;
4949 
4950 	return rc;
4951 
4952 lpfc_sli_hba_setup_error:
4953 	phba->link_state = LPFC_HBA_ERROR;
4954 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4955 			"0445 Firmware initialization failed\n");
4956 	return rc;
4957 }
4958 
4959 /**
4960  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
4961  * @phba: Pointer to HBA context object.
4962  * @mboxq: mailbox pointer.
4963  * This function issue a dump mailbox command to read config region
4964  * 23 and parse the records in the region and populate driver
4965  * data structure.
4966  **/
4967 static int
4968 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
4969 {
4970 	LPFC_MBOXQ_t *mboxq;
4971 	struct lpfc_dmabuf *mp;
4972 	struct lpfc_mqe *mqe;
4973 	uint32_t data_length;
4974 	int rc;
4975 
4976 	/* Program the default value of vlan_id and fc_map */
4977 	phba->valid_vlan = 0;
4978 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
4979 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
4980 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
4981 
4982 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4983 	if (!mboxq)
4984 		return -ENOMEM;
4985 
4986 	mqe = &mboxq->u.mqe;
4987 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
4988 		rc = -ENOMEM;
4989 		goto out_free_mboxq;
4990 	}
4991 
4992 	mp = (struct lpfc_dmabuf *) mboxq->context1;
4993 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4994 
4995 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
4996 			"(%d):2571 Mailbox cmd x%x Status x%x "
4997 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
4998 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
4999 			"CQ: x%x x%x x%x x%x\n",
5000 			mboxq->vport ? mboxq->vport->vpi : 0,
5001 			bf_get(lpfc_mqe_command, mqe),
5002 			bf_get(lpfc_mqe_status, mqe),
5003 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5004 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5005 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5006 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5007 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5008 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5009 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5010 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5011 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5012 			mboxq->mcqe.word0,
5013 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5014 			mboxq->mcqe.trailer);
5015 
5016 	if (rc) {
5017 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5018 		kfree(mp);
5019 		rc = -EIO;
5020 		goto out_free_mboxq;
5021 	}
5022 	data_length = mqe->un.mb_words[5];
5023 	if (data_length > DMP_RGN23_SIZE) {
5024 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5025 		kfree(mp);
5026 		rc = -EIO;
5027 		goto out_free_mboxq;
5028 	}
5029 
5030 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5031 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
5032 	kfree(mp);
5033 	rc = 0;
5034 
5035 out_free_mboxq:
5036 	mempool_free(mboxq, phba->mbox_mem_pool);
5037 	return rc;
5038 }
5039 
5040 /**
5041  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5042  * @phba: pointer to lpfc hba data structure.
5043  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5044  * @vpd: pointer to the memory to hold resulting port vpd data.
5045  * @vpd_size: On input, the number of bytes allocated to @vpd.
5046  *	      On output, the number of data bytes in @vpd.
5047  *
5048  * This routine executes a READ_REV SLI4 mailbox command.  In
5049  * addition, this routine gets the port vpd data.
5050  *
5051  * Return codes
5052  * 	0 - successful
5053  * 	-ENOMEM - could not allocated memory.
5054  **/
5055 static int
5056 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5057 		    uint8_t *vpd, uint32_t *vpd_size)
5058 {
5059 	int rc = 0;
5060 	uint32_t dma_size;
5061 	struct lpfc_dmabuf *dmabuf;
5062 	struct lpfc_mqe *mqe;
5063 
5064 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5065 	if (!dmabuf)
5066 		return -ENOMEM;
5067 
5068 	/*
5069 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5070 	 * mailbox command.
5071 	 */
5072 	dma_size = *vpd_size;
5073 	dmabuf->virt = dma_zalloc_coherent(&phba->pcidev->dev, dma_size,
5074 					   &dmabuf->phys, GFP_KERNEL);
5075 	if (!dmabuf->virt) {
5076 		kfree(dmabuf);
5077 		return -ENOMEM;
5078 	}
5079 
5080 	/*
5081 	 * The SLI4 implementation of READ_REV conflicts at word1,
5082 	 * bits 31:16 and SLI4 adds vpd functionality not present
5083 	 * in SLI3.  This code corrects the conflicts.
5084 	 */
5085 	lpfc_read_rev(phba, mboxq);
5086 	mqe = &mboxq->u.mqe;
5087 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5088 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5089 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5090 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5091 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5092 
5093 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5094 	if (rc) {
5095 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5096 				  dmabuf->virt, dmabuf->phys);
5097 		kfree(dmabuf);
5098 		return -EIO;
5099 	}
5100 
5101 	/*
5102 	 * The available vpd length cannot be bigger than the
5103 	 * DMA buffer passed to the port.  Catch the less than
5104 	 * case and update the caller's size.
5105 	 */
5106 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5107 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5108 
5109 	memcpy(vpd, dmabuf->virt, *vpd_size);
5110 
5111 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5112 			  dmabuf->virt, dmabuf->phys);
5113 	kfree(dmabuf);
5114 	return 0;
5115 }
5116 
5117 /**
5118  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
5119  * @phba: pointer to lpfc hba data structure.
5120  *
5121  * This routine retrieves SLI4 device physical port name this PCI function
5122  * is attached to.
5123  *
5124  * Return codes
5125  *      0 - successful
5126  *      otherwise - failed to retrieve physical port name
5127  **/
5128 static int
5129 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
5130 {
5131 	LPFC_MBOXQ_t *mboxq;
5132 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5133 	struct lpfc_controller_attribute *cntl_attr;
5134 	struct lpfc_mbx_get_port_name *get_port_name;
5135 	void *virtaddr = NULL;
5136 	uint32_t alloclen, reqlen;
5137 	uint32_t shdr_status, shdr_add_status;
5138 	union lpfc_sli4_cfg_shdr *shdr;
5139 	char cport_name = 0;
5140 	int rc;
5141 
5142 	/* We assume nothing at this point */
5143 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5144 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
5145 
5146 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5147 	if (!mboxq)
5148 		return -ENOMEM;
5149 	/* obtain link type and link number via READ_CONFIG */
5150 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5151 	lpfc_sli4_read_config(phba);
5152 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
5153 		goto retrieve_ppname;
5154 
5155 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
5156 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5157 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5158 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5159 			LPFC_SLI4_MBX_NEMBED);
5160 	if (alloclen < reqlen) {
5161 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5162 				"3084 Allocated DMA memory size (%d) is "
5163 				"less than the requested DMA memory size "
5164 				"(%d)\n", alloclen, reqlen);
5165 		rc = -ENOMEM;
5166 		goto out_free_mboxq;
5167 	}
5168 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5169 	virtaddr = mboxq->sge_array->addr[0];
5170 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5171 	shdr = &mbx_cntl_attr->cfg_shdr;
5172 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5173 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5174 	if (shdr_status || shdr_add_status || rc) {
5175 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5176 				"3085 Mailbox x%x (x%x/x%x) failed, "
5177 				"rc:x%x, status:x%x, add_status:x%x\n",
5178 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5179 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5180 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5181 				rc, shdr_status, shdr_add_status);
5182 		rc = -ENXIO;
5183 		goto out_free_mboxq;
5184 	}
5185 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5186 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5187 	phba->sli4_hba.lnk_info.lnk_tp =
5188 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5189 	phba->sli4_hba.lnk_info.lnk_no =
5190 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5191 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5192 			"3086 lnk_type:%d, lnk_numb:%d\n",
5193 			phba->sli4_hba.lnk_info.lnk_tp,
5194 			phba->sli4_hba.lnk_info.lnk_no);
5195 
5196 retrieve_ppname:
5197 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5198 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
5199 		sizeof(struct lpfc_mbx_get_port_name) -
5200 		sizeof(struct lpfc_sli4_cfg_mhdr),
5201 		LPFC_SLI4_MBX_EMBED);
5202 	get_port_name = &mboxq->u.mqe.un.get_port_name;
5203 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5204 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
5205 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
5206 		phba->sli4_hba.lnk_info.lnk_tp);
5207 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5208 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5209 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5210 	if (shdr_status || shdr_add_status || rc) {
5211 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5212 				"3087 Mailbox x%x (x%x/x%x) failed: "
5213 				"rc:x%x, status:x%x, add_status:x%x\n",
5214 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5215 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5216 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5217 				rc, shdr_status, shdr_add_status);
5218 		rc = -ENXIO;
5219 		goto out_free_mboxq;
5220 	}
5221 	switch (phba->sli4_hba.lnk_info.lnk_no) {
5222 	case LPFC_LINK_NUMBER_0:
5223 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
5224 				&get_port_name->u.response);
5225 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5226 		break;
5227 	case LPFC_LINK_NUMBER_1:
5228 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
5229 				&get_port_name->u.response);
5230 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5231 		break;
5232 	case LPFC_LINK_NUMBER_2:
5233 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
5234 				&get_port_name->u.response);
5235 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5236 		break;
5237 	case LPFC_LINK_NUMBER_3:
5238 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
5239 				&get_port_name->u.response);
5240 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5241 		break;
5242 	default:
5243 		break;
5244 	}
5245 
5246 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
5247 		phba->Port[0] = cport_name;
5248 		phba->Port[1] = '\0';
5249 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5250 				"3091 SLI get port name: %s\n", phba->Port);
5251 	}
5252 
5253 out_free_mboxq:
5254 	if (rc != MBX_TIMEOUT) {
5255 		if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5256 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
5257 		else
5258 			mempool_free(mboxq, phba->mbox_mem_pool);
5259 	}
5260 	return rc;
5261 }
5262 
5263 /**
5264  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
5265  * @phba: pointer to lpfc hba data structure.
5266  *
5267  * This routine is called to explicitly arm the SLI4 device's completion and
5268  * event queues
5269  **/
5270 static void
5271 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
5272 {
5273 	int qidx;
5274 
5275 	lpfc_sli4_cq_release(phba->sli4_hba.mbx_cq, LPFC_QUEUE_REARM);
5276 	lpfc_sli4_cq_release(phba->sli4_hba.els_cq, LPFC_QUEUE_REARM);
5277 	if (phba->sli4_hba.nvmels_cq)
5278 		lpfc_sli4_cq_release(phba->sli4_hba.nvmels_cq,
5279 						LPFC_QUEUE_REARM);
5280 
5281 	if (phba->sli4_hba.fcp_cq)
5282 		for (qidx = 0; qidx < phba->cfg_fcp_io_channel; qidx++)
5283 			lpfc_sli4_cq_release(phba->sli4_hba.fcp_cq[qidx],
5284 						LPFC_QUEUE_REARM);
5285 
5286 	if (phba->sli4_hba.nvme_cq)
5287 		for (qidx = 0; qidx < phba->cfg_nvme_io_channel; qidx++)
5288 			lpfc_sli4_cq_release(phba->sli4_hba.nvme_cq[qidx],
5289 						LPFC_QUEUE_REARM);
5290 
5291 	if (phba->cfg_fof)
5292 		lpfc_sli4_cq_release(phba->sli4_hba.oas_cq, LPFC_QUEUE_REARM);
5293 
5294 	if (phba->sli4_hba.hba_eq)
5295 		for (qidx = 0; qidx < phba->io_channel_irqs; qidx++)
5296 			lpfc_sli4_eq_release(phba->sli4_hba.hba_eq[qidx],
5297 						LPFC_QUEUE_REARM);
5298 
5299 	if (phba->nvmet_support) {
5300 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
5301 			lpfc_sli4_cq_release(
5302 				phba->sli4_hba.nvmet_cqset[qidx],
5303 				LPFC_QUEUE_REARM);
5304 		}
5305 	}
5306 
5307 	if (phba->cfg_fof)
5308 		lpfc_sli4_eq_release(phba->sli4_hba.fof_eq, LPFC_QUEUE_REARM);
5309 }
5310 
5311 /**
5312  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
5313  * @phba: Pointer to HBA context object.
5314  * @type: The resource extent type.
5315  * @extnt_count: buffer to hold port available extent count.
5316  * @extnt_size: buffer to hold element count per extent.
5317  *
5318  * This function calls the port and retrievs the number of available
5319  * extents and their size for a particular extent type.
5320  *
5321  * Returns: 0 if successful.  Nonzero otherwise.
5322  **/
5323 int
5324 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
5325 			       uint16_t *extnt_count, uint16_t *extnt_size)
5326 {
5327 	int rc = 0;
5328 	uint32_t length;
5329 	uint32_t mbox_tmo;
5330 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
5331 	LPFC_MBOXQ_t *mbox;
5332 
5333 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5334 	if (!mbox)
5335 		return -ENOMEM;
5336 
5337 	/* Find out how many extents are available for this resource type */
5338 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
5339 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5340 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5341 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
5342 			 length, LPFC_SLI4_MBX_EMBED);
5343 
5344 	/* Send an extents count of 0 - the GET doesn't use it. */
5345 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5346 					LPFC_SLI4_MBX_EMBED);
5347 	if (unlikely(rc)) {
5348 		rc = -EIO;
5349 		goto err_exit;
5350 	}
5351 
5352 	if (!phba->sli4_hba.intr_enable)
5353 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5354 	else {
5355 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5356 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5357 	}
5358 	if (unlikely(rc)) {
5359 		rc = -EIO;
5360 		goto err_exit;
5361 	}
5362 
5363 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
5364 	if (bf_get(lpfc_mbox_hdr_status,
5365 		   &rsrc_info->header.cfg_shdr.response)) {
5366 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5367 				"2930 Failed to get resource extents "
5368 				"Status 0x%x Add'l Status 0x%x\n",
5369 				bf_get(lpfc_mbox_hdr_status,
5370 				       &rsrc_info->header.cfg_shdr.response),
5371 				bf_get(lpfc_mbox_hdr_add_status,
5372 				       &rsrc_info->header.cfg_shdr.response));
5373 		rc = -EIO;
5374 		goto err_exit;
5375 	}
5376 
5377 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
5378 			      &rsrc_info->u.rsp);
5379 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
5380 			     &rsrc_info->u.rsp);
5381 
5382 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5383 			"3162 Retrieved extents type-%d from port: count:%d, "
5384 			"size:%d\n", type, *extnt_count, *extnt_size);
5385 
5386 err_exit:
5387 	mempool_free(mbox, phba->mbox_mem_pool);
5388 	return rc;
5389 }
5390 
5391 /**
5392  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
5393  * @phba: Pointer to HBA context object.
5394  * @type: The extent type to check.
5395  *
5396  * This function reads the current available extents from the port and checks
5397  * if the extent count or extent size has changed since the last access.
5398  * Callers use this routine post port reset to understand if there is a
5399  * extent reprovisioning requirement.
5400  *
5401  * Returns:
5402  *   -Error: error indicates problem.
5403  *   1: Extent count or size has changed.
5404  *   0: No changes.
5405  **/
5406 static int
5407 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
5408 {
5409 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
5410 	uint16_t size_diff, rsrc_ext_size;
5411 	int rc = 0;
5412 	struct lpfc_rsrc_blks *rsrc_entry;
5413 	struct list_head *rsrc_blk_list = NULL;
5414 
5415 	size_diff = 0;
5416 	curr_ext_cnt = 0;
5417 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5418 					    &rsrc_ext_cnt,
5419 					    &rsrc_ext_size);
5420 	if (unlikely(rc))
5421 		return -EIO;
5422 
5423 	switch (type) {
5424 	case LPFC_RSC_TYPE_FCOE_RPI:
5425 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5426 		break;
5427 	case LPFC_RSC_TYPE_FCOE_VPI:
5428 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
5429 		break;
5430 	case LPFC_RSC_TYPE_FCOE_XRI:
5431 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5432 		break;
5433 	case LPFC_RSC_TYPE_FCOE_VFI:
5434 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5435 		break;
5436 	default:
5437 		break;
5438 	}
5439 
5440 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
5441 		curr_ext_cnt++;
5442 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
5443 			size_diff++;
5444 	}
5445 
5446 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
5447 		rc = 1;
5448 
5449 	return rc;
5450 }
5451 
5452 /**
5453  * lpfc_sli4_cfg_post_extnts -
5454  * @phba: Pointer to HBA context object.
5455  * @extnt_cnt - number of available extents.
5456  * @type - the extent type (rpi, xri, vfi, vpi).
5457  * @emb - buffer to hold either MBX_EMBED or MBX_NEMBED operation.
5458  * @mbox - pointer to the caller's allocated mailbox structure.
5459  *
5460  * This function executes the extents allocation request.  It also
5461  * takes care of the amount of memory needed to allocate or get the
5462  * allocated extents. It is the caller's responsibility to evaluate
5463  * the response.
5464  *
5465  * Returns:
5466  *   -Error:  Error value describes the condition found.
5467  *   0: if successful
5468  **/
5469 static int
5470 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
5471 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
5472 {
5473 	int rc = 0;
5474 	uint32_t req_len;
5475 	uint32_t emb_len;
5476 	uint32_t alloc_len, mbox_tmo;
5477 
5478 	/* Calculate the total requested length of the dma memory */
5479 	req_len = extnt_cnt * sizeof(uint16_t);
5480 
5481 	/*
5482 	 * Calculate the size of an embedded mailbox.  The uint32_t
5483 	 * accounts for extents-specific word.
5484 	 */
5485 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
5486 		sizeof(uint32_t);
5487 
5488 	/*
5489 	 * Presume the allocation and response will fit into an embedded
5490 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
5491 	 */
5492 	*emb = LPFC_SLI4_MBX_EMBED;
5493 	if (req_len > emb_len) {
5494 		req_len = extnt_cnt * sizeof(uint16_t) +
5495 			sizeof(union lpfc_sli4_cfg_shdr) +
5496 			sizeof(uint32_t);
5497 		*emb = LPFC_SLI4_MBX_NEMBED;
5498 	}
5499 
5500 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5501 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
5502 				     req_len, *emb);
5503 	if (alloc_len < req_len) {
5504 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5505 			"2982 Allocated DMA memory size (x%x) is "
5506 			"less than the requested DMA memory "
5507 			"size (x%x)\n", alloc_len, req_len);
5508 		return -ENOMEM;
5509 	}
5510 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
5511 	if (unlikely(rc))
5512 		return -EIO;
5513 
5514 	if (!phba->sli4_hba.intr_enable)
5515 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5516 	else {
5517 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5518 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5519 	}
5520 
5521 	if (unlikely(rc))
5522 		rc = -EIO;
5523 	return rc;
5524 }
5525 
5526 /**
5527  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
5528  * @phba: Pointer to HBA context object.
5529  * @type:  The resource extent type to allocate.
5530  *
5531  * This function allocates the number of elements for the specified
5532  * resource type.
5533  **/
5534 static int
5535 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
5536 {
5537 	bool emb = false;
5538 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
5539 	uint16_t rsrc_id, rsrc_start, j, k;
5540 	uint16_t *ids;
5541 	int i, rc;
5542 	unsigned long longs;
5543 	unsigned long *bmask;
5544 	struct lpfc_rsrc_blks *rsrc_blks;
5545 	LPFC_MBOXQ_t *mbox;
5546 	uint32_t length;
5547 	struct lpfc_id_range *id_array = NULL;
5548 	void *virtaddr = NULL;
5549 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
5550 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
5551 	struct list_head *ext_blk_list;
5552 
5553 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5554 					    &rsrc_cnt,
5555 					    &rsrc_size);
5556 	if (unlikely(rc))
5557 		return -EIO;
5558 
5559 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
5560 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5561 			"3009 No available Resource Extents "
5562 			"for resource type 0x%x: Count: 0x%x, "
5563 			"Size 0x%x\n", type, rsrc_cnt,
5564 			rsrc_size);
5565 		return -ENOMEM;
5566 	}
5567 
5568 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
5569 			"2903 Post resource extents type-0x%x: "
5570 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
5571 
5572 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5573 	if (!mbox)
5574 		return -ENOMEM;
5575 
5576 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
5577 	if (unlikely(rc)) {
5578 		rc = -EIO;
5579 		goto err_exit;
5580 	}
5581 
5582 	/*
5583 	 * Figure out where the response is located.  Then get local pointers
5584 	 * to the response data.  The port does not guarantee to respond to
5585 	 * all extents counts request so update the local variable with the
5586 	 * allocated count from the port.
5587 	 */
5588 	if (emb == LPFC_SLI4_MBX_EMBED) {
5589 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
5590 		id_array = &rsrc_ext->u.rsp.id[0];
5591 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
5592 	} else {
5593 		virtaddr = mbox->sge_array->addr[0];
5594 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
5595 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
5596 		id_array = &n_rsrc->id;
5597 	}
5598 
5599 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
5600 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
5601 
5602 	/*
5603 	 * Based on the resource size and count, correct the base and max
5604 	 * resource values.
5605 	 */
5606 	length = sizeof(struct lpfc_rsrc_blks);
5607 	switch (type) {
5608 	case LPFC_RSC_TYPE_FCOE_RPI:
5609 		phba->sli4_hba.rpi_bmask = kzalloc(longs *
5610 						   sizeof(unsigned long),
5611 						   GFP_KERNEL);
5612 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
5613 			rc = -ENOMEM;
5614 			goto err_exit;
5615 		}
5616 		phba->sli4_hba.rpi_ids = kzalloc(rsrc_id_cnt *
5617 						 sizeof(uint16_t),
5618 						 GFP_KERNEL);
5619 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
5620 			kfree(phba->sli4_hba.rpi_bmask);
5621 			rc = -ENOMEM;
5622 			goto err_exit;
5623 		}
5624 
5625 		/*
5626 		 * The next_rpi was initialized with the maximum available
5627 		 * count but the port may allocate a smaller number.  Catch
5628 		 * that case and update the next_rpi.
5629 		 */
5630 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
5631 
5632 		/* Initialize local ptrs for common extent processing later. */
5633 		bmask = phba->sli4_hba.rpi_bmask;
5634 		ids = phba->sli4_hba.rpi_ids;
5635 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5636 		break;
5637 	case LPFC_RSC_TYPE_FCOE_VPI:
5638 		phba->vpi_bmask = kzalloc(longs *
5639 					  sizeof(unsigned long),
5640 					  GFP_KERNEL);
5641 		if (unlikely(!phba->vpi_bmask)) {
5642 			rc = -ENOMEM;
5643 			goto err_exit;
5644 		}
5645 		phba->vpi_ids = kzalloc(rsrc_id_cnt *
5646 					 sizeof(uint16_t),
5647 					 GFP_KERNEL);
5648 		if (unlikely(!phba->vpi_ids)) {
5649 			kfree(phba->vpi_bmask);
5650 			rc = -ENOMEM;
5651 			goto err_exit;
5652 		}
5653 
5654 		/* Initialize local ptrs for common extent processing later. */
5655 		bmask = phba->vpi_bmask;
5656 		ids = phba->vpi_ids;
5657 		ext_blk_list = &phba->lpfc_vpi_blk_list;
5658 		break;
5659 	case LPFC_RSC_TYPE_FCOE_XRI:
5660 		phba->sli4_hba.xri_bmask = kzalloc(longs *
5661 						   sizeof(unsigned long),
5662 						   GFP_KERNEL);
5663 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
5664 			rc = -ENOMEM;
5665 			goto err_exit;
5666 		}
5667 		phba->sli4_hba.max_cfg_param.xri_used = 0;
5668 		phba->sli4_hba.xri_ids = kzalloc(rsrc_id_cnt *
5669 						 sizeof(uint16_t),
5670 						 GFP_KERNEL);
5671 		if (unlikely(!phba->sli4_hba.xri_ids)) {
5672 			kfree(phba->sli4_hba.xri_bmask);
5673 			rc = -ENOMEM;
5674 			goto err_exit;
5675 		}
5676 
5677 		/* Initialize local ptrs for common extent processing later. */
5678 		bmask = phba->sli4_hba.xri_bmask;
5679 		ids = phba->sli4_hba.xri_ids;
5680 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5681 		break;
5682 	case LPFC_RSC_TYPE_FCOE_VFI:
5683 		phba->sli4_hba.vfi_bmask = kzalloc(longs *
5684 						   sizeof(unsigned long),
5685 						   GFP_KERNEL);
5686 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
5687 			rc = -ENOMEM;
5688 			goto err_exit;
5689 		}
5690 		phba->sli4_hba.vfi_ids = kzalloc(rsrc_id_cnt *
5691 						 sizeof(uint16_t),
5692 						 GFP_KERNEL);
5693 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
5694 			kfree(phba->sli4_hba.vfi_bmask);
5695 			rc = -ENOMEM;
5696 			goto err_exit;
5697 		}
5698 
5699 		/* Initialize local ptrs for common extent processing later. */
5700 		bmask = phba->sli4_hba.vfi_bmask;
5701 		ids = phba->sli4_hba.vfi_ids;
5702 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5703 		break;
5704 	default:
5705 		/* Unsupported Opcode.  Fail call. */
5706 		id_array = NULL;
5707 		bmask = NULL;
5708 		ids = NULL;
5709 		ext_blk_list = NULL;
5710 		goto err_exit;
5711 	}
5712 
5713 	/*
5714 	 * Complete initializing the extent configuration with the
5715 	 * allocated ids assigned to this function.  The bitmask serves
5716 	 * as an index into the array and manages the available ids.  The
5717 	 * array just stores the ids communicated to the port via the wqes.
5718 	 */
5719 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
5720 		if ((i % 2) == 0)
5721 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
5722 					 &id_array[k]);
5723 		else
5724 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
5725 					 &id_array[k]);
5726 
5727 		rsrc_blks = kzalloc(length, GFP_KERNEL);
5728 		if (unlikely(!rsrc_blks)) {
5729 			rc = -ENOMEM;
5730 			kfree(bmask);
5731 			kfree(ids);
5732 			goto err_exit;
5733 		}
5734 		rsrc_blks->rsrc_start = rsrc_id;
5735 		rsrc_blks->rsrc_size = rsrc_size;
5736 		list_add_tail(&rsrc_blks->list, ext_blk_list);
5737 		rsrc_start = rsrc_id;
5738 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
5739 			phba->sli4_hba.scsi_xri_start = rsrc_start +
5740 				lpfc_sli4_get_iocb_cnt(phba);
5741 			phba->sli4_hba.nvme_xri_start =
5742 				phba->sli4_hba.scsi_xri_start +
5743 				phba->sli4_hba.scsi_xri_max;
5744 		}
5745 
5746 		while (rsrc_id < (rsrc_start + rsrc_size)) {
5747 			ids[j] = rsrc_id;
5748 			rsrc_id++;
5749 			j++;
5750 		}
5751 		/* Entire word processed.  Get next word.*/
5752 		if ((i % 2) == 1)
5753 			k++;
5754 	}
5755  err_exit:
5756 	lpfc_sli4_mbox_cmd_free(phba, mbox);
5757 	return rc;
5758 }
5759 
5760 
5761 
5762 /**
5763  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
5764  * @phba: Pointer to HBA context object.
5765  * @type: the extent's type.
5766  *
5767  * This function deallocates all extents of a particular resource type.
5768  * SLI4 does not allow for deallocating a particular extent range.  It
5769  * is the caller's responsibility to release all kernel memory resources.
5770  **/
5771 static int
5772 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
5773 {
5774 	int rc;
5775 	uint32_t length, mbox_tmo = 0;
5776 	LPFC_MBOXQ_t *mbox;
5777 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
5778 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
5779 
5780 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5781 	if (!mbox)
5782 		return -ENOMEM;
5783 
5784 	/*
5785 	 * This function sends an embedded mailbox because it only sends the
5786 	 * the resource type.  All extents of this type are released by the
5787 	 * port.
5788 	 */
5789 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
5790 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5791 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5792 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
5793 			 length, LPFC_SLI4_MBX_EMBED);
5794 
5795 	/* Send an extents count of 0 - the dealloc doesn't use it. */
5796 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5797 					LPFC_SLI4_MBX_EMBED);
5798 	if (unlikely(rc)) {
5799 		rc = -EIO;
5800 		goto out_free_mbox;
5801 	}
5802 	if (!phba->sli4_hba.intr_enable)
5803 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5804 	else {
5805 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5806 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5807 	}
5808 	if (unlikely(rc)) {
5809 		rc = -EIO;
5810 		goto out_free_mbox;
5811 	}
5812 
5813 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
5814 	if (bf_get(lpfc_mbox_hdr_status,
5815 		   &dealloc_rsrc->header.cfg_shdr.response)) {
5816 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5817 				"2919 Failed to release resource extents "
5818 				"for type %d - Status 0x%x Add'l Status 0x%x. "
5819 				"Resource memory not released.\n",
5820 				type,
5821 				bf_get(lpfc_mbox_hdr_status,
5822 				    &dealloc_rsrc->header.cfg_shdr.response),
5823 				bf_get(lpfc_mbox_hdr_add_status,
5824 				    &dealloc_rsrc->header.cfg_shdr.response));
5825 		rc = -EIO;
5826 		goto out_free_mbox;
5827 	}
5828 
5829 	/* Release kernel memory resources for the specific type. */
5830 	switch (type) {
5831 	case LPFC_RSC_TYPE_FCOE_VPI:
5832 		kfree(phba->vpi_bmask);
5833 		kfree(phba->vpi_ids);
5834 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5835 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5836 				    &phba->lpfc_vpi_blk_list, list) {
5837 			list_del_init(&rsrc_blk->list);
5838 			kfree(rsrc_blk);
5839 		}
5840 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
5841 		break;
5842 	case LPFC_RSC_TYPE_FCOE_XRI:
5843 		kfree(phba->sli4_hba.xri_bmask);
5844 		kfree(phba->sli4_hba.xri_ids);
5845 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5846 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
5847 			list_del_init(&rsrc_blk->list);
5848 			kfree(rsrc_blk);
5849 		}
5850 		break;
5851 	case LPFC_RSC_TYPE_FCOE_VFI:
5852 		kfree(phba->sli4_hba.vfi_bmask);
5853 		kfree(phba->sli4_hba.vfi_ids);
5854 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5855 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5856 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
5857 			list_del_init(&rsrc_blk->list);
5858 			kfree(rsrc_blk);
5859 		}
5860 		break;
5861 	case LPFC_RSC_TYPE_FCOE_RPI:
5862 		/* RPI bitmask and physical id array are cleaned up earlier. */
5863 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5864 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
5865 			list_del_init(&rsrc_blk->list);
5866 			kfree(rsrc_blk);
5867 		}
5868 		break;
5869 	default:
5870 		break;
5871 	}
5872 
5873 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5874 
5875  out_free_mbox:
5876 	mempool_free(mbox, phba->mbox_mem_pool);
5877 	return rc;
5878 }
5879 
5880 static void
5881 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
5882 		  uint32_t feature)
5883 {
5884 	uint32_t len;
5885 
5886 	len = sizeof(struct lpfc_mbx_set_feature) -
5887 		sizeof(struct lpfc_sli4_cfg_mhdr);
5888 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5889 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
5890 			 LPFC_SLI4_MBX_EMBED);
5891 
5892 	switch (feature) {
5893 	case LPFC_SET_UE_RECOVERY:
5894 		bf_set(lpfc_mbx_set_feature_UER,
5895 		       &mbox->u.mqe.un.set_feature, 1);
5896 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
5897 		mbox->u.mqe.un.set_feature.param_len = 8;
5898 		break;
5899 	case LPFC_SET_MDS_DIAGS:
5900 		bf_set(lpfc_mbx_set_feature_mds,
5901 		       &mbox->u.mqe.un.set_feature, 1);
5902 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
5903 		       &mbox->u.mqe.un.set_feature, 0);
5904 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
5905 		mbox->u.mqe.un.set_feature.param_len = 8;
5906 		break;
5907 	}
5908 
5909 	return;
5910 }
5911 
5912 /**
5913  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
5914  * @phba: Pointer to HBA context object.
5915  *
5916  * This function allocates all SLI4 resource identifiers.
5917  **/
5918 int
5919 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
5920 {
5921 	int i, rc, error = 0;
5922 	uint16_t count, base;
5923 	unsigned long longs;
5924 
5925 	if (!phba->sli4_hba.rpi_hdrs_in_use)
5926 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
5927 	if (phba->sli4_hba.extents_in_use) {
5928 		/*
5929 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
5930 		 * resource extent count must be read and allocated before
5931 		 * provisioning the resource id arrays.
5932 		 */
5933 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
5934 		    LPFC_IDX_RSRC_RDY) {
5935 			/*
5936 			 * Extent-based resources are set - the driver could
5937 			 * be in a port reset. Figure out if any corrective
5938 			 * actions need to be taken.
5939 			 */
5940 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5941 						 LPFC_RSC_TYPE_FCOE_VFI);
5942 			if (rc != 0)
5943 				error++;
5944 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5945 						 LPFC_RSC_TYPE_FCOE_VPI);
5946 			if (rc != 0)
5947 				error++;
5948 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5949 						 LPFC_RSC_TYPE_FCOE_XRI);
5950 			if (rc != 0)
5951 				error++;
5952 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5953 						 LPFC_RSC_TYPE_FCOE_RPI);
5954 			if (rc != 0)
5955 				error++;
5956 
5957 			/*
5958 			 * It's possible that the number of resources
5959 			 * provided to this port instance changed between
5960 			 * resets.  Detect this condition and reallocate
5961 			 * resources.  Otherwise, there is no action.
5962 			 */
5963 			if (error) {
5964 				lpfc_printf_log(phba, KERN_INFO,
5965 						LOG_MBOX | LOG_INIT,
5966 						"2931 Detected extent resource "
5967 						"change.  Reallocating all "
5968 						"extents.\n");
5969 				rc = lpfc_sli4_dealloc_extent(phba,
5970 						 LPFC_RSC_TYPE_FCOE_VFI);
5971 				rc = lpfc_sli4_dealloc_extent(phba,
5972 						 LPFC_RSC_TYPE_FCOE_VPI);
5973 				rc = lpfc_sli4_dealloc_extent(phba,
5974 						 LPFC_RSC_TYPE_FCOE_XRI);
5975 				rc = lpfc_sli4_dealloc_extent(phba,
5976 						 LPFC_RSC_TYPE_FCOE_RPI);
5977 			} else
5978 				return 0;
5979 		}
5980 
5981 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
5982 		if (unlikely(rc))
5983 			goto err_exit;
5984 
5985 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
5986 		if (unlikely(rc))
5987 			goto err_exit;
5988 
5989 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
5990 		if (unlikely(rc))
5991 			goto err_exit;
5992 
5993 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
5994 		if (unlikely(rc))
5995 			goto err_exit;
5996 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
5997 		       LPFC_IDX_RSRC_RDY);
5998 		return rc;
5999 	} else {
6000 		/*
6001 		 * The port does not support resource extents.  The XRI, VPI,
6002 		 * VFI, RPI resource ids were determined from READ_CONFIG.
6003 		 * Just allocate the bitmasks and provision the resource id
6004 		 * arrays.  If a port reset is active, the resources don't
6005 		 * need any action - just exit.
6006 		 */
6007 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6008 		    LPFC_IDX_RSRC_RDY) {
6009 			lpfc_sli4_dealloc_resource_identifiers(phba);
6010 			lpfc_sli4_remove_rpis(phba);
6011 		}
6012 		/* RPIs. */
6013 		count = phba->sli4_hba.max_cfg_param.max_rpi;
6014 		if (count <= 0) {
6015 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6016 					"3279 Invalid provisioning of "
6017 					"rpi:%d\n", count);
6018 			rc = -EINVAL;
6019 			goto err_exit;
6020 		}
6021 		base = phba->sli4_hba.max_cfg_param.rpi_base;
6022 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6023 		phba->sli4_hba.rpi_bmask = kzalloc(longs *
6024 						   sizeof(unsigned long),
6025 						   GFP_KERNEL);
6026 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6027 			rc = -ENOMEM;
6028 			goto err_exit;
6029 		}
6030 		phba->sli4_hba.rpi_ids = kzalloc(count *
6031 						 sizeof(uint16_t),
6032 						 GFP_KERNEL);
6033 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6034 			rc = -ENOMEM;
6035 			goto free_rpi_bmask;
6036 		}
6037 
6038 		for (i = 0; i < count; i++)
6039 			phba->sli4_hba.rpi_ids[i] = base + i;
6040 
6041 		/* VPIs. */
6042 		count = phba->sli4_hba.max_cfg_param.max_vpi;
6043 		if (count <= 0) {
6044 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6045 					"3280 Invalid provisioning of "
6046 					"vpi:%d\n", count);
6047 			rc = -EINVAL;
6048 			goto free_rpi_ids;
6049 		}
6050 		base = phba->sli4_hba.max_cfg_param.vpi_base;
6051 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6052 		phba->vpi_bmask = kzalloc(longs *
6053 					  sizeof(unsigned long),
6054 					  GFP_KERNEL);
6055 		if (unlikely(!phba->vpi_bmask)) {
6056 			rc = -ENOMEM;
6057 			goto free_rpi_ids;
6058 		}
6059 		phba->vpi_ids = kzalloc(count *
6060 					sizeof(uint16_t),
6061 					GFP_KERNEL);
6062 		if (unlikely(!phba->vpi_ids)) {
6063 			rc = -ENOMEM;
6064 			goto free_vpi_bmask;
6065 		}
6066 
6067 		for (i = 0; i < count; i++)
6068 			phba->vpi_ids[i] = base + i;
6069 
6070 		/* XRIs. */
6071 		count = phba->sli4_hba.max_cfg_param.max_xri;
6072 		if (count <= 0) {
6073 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6074 					"3281 Invalid provisioning of "
6075 					"xri:%d\n", count);
6076 			rc = -EINVAL;
6077 			goto free_vpi_ids;
6078 		}
6079 		base = phba->sli4_hba.max_cfg_param.xri_base;
6080 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6081 		phba->sli4_hba.xri_bmask = kzalloc(longs *
6082 						   sizeof(unsigned long),
6083 						   GFP_KERNEL);
6084 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6085 			rc = -ENOMEM;
6086 			goto free_vpi_ids;
6087 		}
6088 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6089 		phba->sli4_hba.xri_ids = kzalloc(count *
6090 						 sizeof(uint16_t),
6091 						 GFP_KERNEL);
6092 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6093 			rc = -ENOMEM;
6094 			goto free_xri_bmask;
6095 		}
6096 
6097 		for (i = 0; i < count; i++)
6098 			phba->sli4_hba.xri_ids[i] = base + i;
6099 
6100 		/* VFIs. */
6101 		count = phba->sli4_hba.max_cfg_param.max_vfi;
6102 		if (count <= 0) {
6103 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6104 					"3282 Invalid provisioning of "
6105 					"vfi:%d\n", count);
6106 			rc = -EINVAL;
6107 			goto free_xri_ids;
6108 		}
6109 		base = phba->sli4_hba.max_cfg_param.vfi_base;
6110 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6111 		phba->sli4_hba.vfi_bmask = kzalloc(longs *
6112 						   sizeof(unsigned long),
6113 						   GFP_KERNEL);
6114 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6115 			rc = -ENOMEM;
6116 			goto free_xri_ids;
6117 		}
6118 		phba->sli4_hba.vfi_ids = kzalloc(count *
6119 						 sizeof(uint16_t),
6120 						 GFP_KERNEL);
6121 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6122 			rc = -ENOMEM;
6123 			goto free_vfi_bmask;
6124 		}
6125 
6126 		for (i = 0; i < count; i++)
6127 			phba->sli4_hba.vfi_ids[i] = base + i;
6128 
6129 		/*
6130 		 * Mark all resources ready.  An HBA reset doesn't need
6131 		 * to reset the initialization.
6132 		 */
6133 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6134 		       LPFC_IDX_RSRC_RDY);
6135 		return 0;
6136 	}
6137 
6138  free_vfi_bmask:
6139 	kfree(phba->sli4_hba.vfi_bmask);
6140 	phba->sli4_hba.vfi_bmask = NULL;
6141  free_xri_ids:
6142 	kfree(phba->sli4_hba.xri_ids);
6143 	phba->sli4_hba.xri_ids = NULL;
6144  free_xri_bmask:
6145 	kfree(phba->sli4_hba.xri_bmask);
6146 	phba->sli4_hba.xri_bmask = NULL;
6147  free_vpi_ids:
6148 	kfree(phba->vpi_ids);
6149 	phba->vpi_ids = NULL;
6150  free_vpi_bmask:
6151 	kfree(phba->vpi_bmask);
6152 	phba->vpi_bmask = NULL;
6153  free_rpi_ids:
6154 	kfree(phba->sli4_hba.rpi_ids);
6155 	phba->sli4_hba.rpi_ids = NULL;
6156  free_rpi_bmask:
6157 	kfree(phba->sli4_hba.rpi_bmask);
6158 	phba->sli4_hba.rpi_bmask = NULL;
6159  err_exit:
6160 	return rc;
6161 }
6162 
6163 /**
6164  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
6165  * @phba: Pointer to HBA context object.
6166  *
6167  * This function allocates the number of elements for the specified
6168  * resource type.
6169  **/
6170 int
6171 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
6172 {
6173 	if (phba->sli4_hba.extents_in_use) {
6174 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6175 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6176 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6177 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6178 	} else {
6179 		kfree(phba->vpi_bmask);
6180 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6181 		kfree(phba->vpi_ids);
6182 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6183 		kfree(phba->sli4_hba.xri_bmask);
6184 		kfree(phba->sli4_hba.xri_ids);
6185 		kfree(phba->sli4_hba.vfi_bmask);
6186 		kfree(phba->sli4_hba.vfi_ids);
6187 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6188 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6189 	}
6190 
6191 	return 0;
6192 }
6193 
6194 /**
6195  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
6196  * @phba: Pointer to HBA context object.
6197  * @type: The resource extent type.
6198  * @extnt_count: buffer to hold port extent count response
6199  * @extnt_size: buffer to hold port extent size response.
6200  *
6201  * This function calls the port to read the host allocated extents
6202  * for a particular type.
6203  **/
6204 int
6205 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
6206 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
6207 {
6208 	bool emb;
6209 	int rc = 0;
6210 	uint16_t curr_blks = 0;
6211 	uint32_t req_len, emb_len;
6212 	uint32_t alloc_len, mbox_tmo;
6213 	struct list_head *blk_list_head;
6214 	struct lpfc_rsrc_blks *rsrc_blk;
6215 	LPFC_MBOXQ_t *mbox;
6216 	void *virtaddr = NULL;
6217 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6218 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6219 	union  lpfc_sli4_cfg_shdr *shdr;
6220 
6221 	switch (type) {
6222 	case LPFC_RSC_TYPE_FCOE_VPI:
6223 		blk_list_head = &phba->lpfc_vpi_blk_list;
6224 		break;
6225 	case LPFC_RSC_TYPE_FCOE_XRI:
6226 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
6227 		break;
6228 	case LPFC_RSC_TYPE_FCOE_VFI:
6229 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
6230 		break;
6231 	case LPFC_RSC_TYPE_FCOE_RPI:
6232 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
6233 		break;
6234 	default:
6235 		return -EIO;
6236 	}
6237 
6238 	/* Count the number of extents currently allocatd for this type. */
6239 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
6240 		if (curr_blks == 0) {
6241 			/*
6242 			 * The GET_ALLOCATED mailbox does not return the size,
6243 			 * just the count.  The size should be just the size
6244 			 * stored in the current allocated block and all sizes
6245 			 * for an extent type are the same so set the return
6246 			 * value now.
6247 			 */
6248 			*extnt_size = rsrc_blk->rsrc_size;
6249 		}
6250 		curr_blks++;
6251 	}
6252 
6253 	/*
6254 	 * Calculate the size of an embedded mailbox.  The uint32_t
6255 	 * accounts for extents-specific word.
6256 	 */
6257 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6258 		sizeof(uint32_t);
6259 
6260 	/*
6261 	 * Presume the allocation and response will fit into an embedded
6262 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6263 	 */
6264 	emb = LPFC_SLI4_MBX_EMBED;
6265 	req_len = emb_len;
6266 	if (req_len > emb_len) {
6267 		req_len = curr_blks * sizeof(uint16_t) +
6268 			sizeof(union lpfc_sli4_cfg_shdr) +
6269 			sizeof(uint32_t);
6270 		emb = LPFC_SLI4_MBX_NEMBED;
6271 	}
6272 
6273 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6274 	if (!mbox)
6275 		return -ENOMEM;
6276 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
6277 
6278 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6279 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
6280 				     req_len, emb);
6281 	if (alloc_len < req_len) {
6282 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6283 			"2983 Allocated DMA memory size (x%x) is "
6284 			"less than the requested DMA memory "
6285 			"size (x%x)\n", alloc_len, req_len);
6286 		rc = -ENOMEM;
6287 		goto err_exit;
6288 	}
6289 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
6290 	if (unlikely(rc)) {
6291 		rc = -EIO;
6292 		goto err_exit;
6293 	}
6294 
6295 	if (!phba->sli4_hba.intr_enable)
6296 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6297 	else {
6298 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6299 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6300 	}
6301 
6302 	if (unlikely(rc)) {
6303 		rc = -EIO;
6304 		goto err_exit;
6305 	}
6306 
6307 	/*
6308 	 * Figure out where the response is located.  Then get local pointers
6309 	 * to the response data.  The port does not guarantee to respond to
6310 	 * all extents counts request so update the local variable with the
6311 	 * allocated count from the port.
6312 	 */
6313 	if (emb == LPFC_SLI4_MBX_EMBED) {
6314 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6315 		shdr = &rsrc_ext->header.cfg_shdr;
6316 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6317 	} else {
6318 		virtaddr = mbox->sge_array->addr[0];
6319 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6320 		shdr = &n_rsrc->cfg_shdr;
6321 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6322 	}
6323 
6324 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
6325 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
6326 			"2984 Failed to read allocated resources "
6327 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
6328 			type,
6329 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
6330 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
6331 		rc = -EIO;
6332 		goto err_exit;
6333 	}
6334  err_exit:
6335 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6336 	return rc;
6337 }
6338 
6339 /**
6340  * lpfc_sli4_repost_sgl_list - Repsot the buffers sgl pages as block
6341  * @phba: pointer to lpfc hba data structure.
6342  * @pring: Pointer to driver SLI ring object.
6343  * @sgl_list: linked link of sgl buffers to post
6344  * @cnt: number of linked list buffers
6345  *
6346  * This routine walks the list of buffers that have been allocated and
6347  * repost them to the port by using SGL block post. This is needed after a
6348  * pci_function_reset/warm_start or start. It attempts to construct blocks
6349  * of buffer sgls which contains contiguous xris and uses the non-embedded
6350  * SGL block post mailbox commands to post them to the port. For single
6351  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
6352  * mailbox command for posting.
6353  *
6354  * Returns: 0 = success, non-zero failure.
6355  **/
6356 static int
6357 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
6358 			  struct list_head *sgl_list, int cnt)
6359 {
6360 	struct lpfc_sglq *sglq_entry = NULL;
6361 	struct lpfc_sglq *sglq_entry_next = NULL;
6362 	struct lpfc_sglq *sglq_entry_first = NULL;
6363 	int status, total_cnt;
6364 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
6365 	int last_xritag = NO_XRI;
6366 	LIST_HEAD(prep_sgl_list);
6367 	LIST_HEAD(blck_sgl_list);
6368 	LIST_HEAD(allc_sgl_list);
6369 	LIST_HEAD(post_sgl_list);
6370 	LIST_HEAD(free_sgl_list);
6371 
6372 	spin_lock_irq(&phba->hbalock);
6373 	spin_lock(&phba->sli4_hba.sgl_list_lock);
6374 	list_splice_init(sgl_list, &allc_sgl_list);
6375 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
6376 	spin_unlock_irq(&phba->hbalock);
6377 
6378 	total_cnt = cnt;
6379 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
6380 				 &allc_sgl_list, list) {
6381 		list_del_init(&sglq_entry->list);
6382 		block_cnt++;
6383 		if ((last_xritag != NO_XRI) &&
6384 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
6385 			/* a hole in xri block, form a sgl posting block */
6386 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
6387 			post_cnt = block_cnt - 1;
6388 			/* prepare list for next posting block */
6389 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6390 			block_cnt = 1;
6391 		} else {
6392 			/* prepare list for next posting block */
6393 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6394 			/* enough sgls for non-embed sgl mbox command */
6395 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
6396 				list_splice_init(&prep_sgl_list,
6397 						 &blck_sgl_list);
6398 				post_cnt = block_cnt;
6399 				block_cnt = 0;
6400 			}
6401 		}
6402 		num_posted++;
6403 
6404 		/* keep track of last sgl's xritag */
6405 		last_xritag = sglq_entry->sli4_xritag;
6406 
6407 		/* end of repost sgl list condition for buffers */
6408 		if (num_posted == total_cnt) {
6409 			if (post_cnt == 0) {
6410 				list_splice_init(&prep_sgl_list,
6411 						 &blck_sgl_list);
6412 				post_cnt = block_cnt;
6413 			} else if (block_cnt == 1) {
6414 				status = lpfc_sli4_post_sgl(phba,
6415 						sglq_entry->phys, 0,
6416 						sglq_entry->sli4_xritag);
6417 				if (!status) {
6418 					/* successful, put sgl to posted list */
6419 					list_add_tail(&sglq_entry->list,
6420 						      &post_sgl_list);
6421 				} else {
6422 					/* Failure, put sgl to free list */
6423 					lpfc_printf_log(phba, KERN_WARNING,
6424 						LOG_SLI,
6425 						"3159 Failed to post "
6426 						"sgl, xritag:x%x\n",
6427 						sglq_entry->sli4_xritag);
6428 					list_add_tail(&sglq_entry->list,
6429 						      &free_sgl_list);
6430 					total_cnt--;
6431 				}
6432 			}
6433 		}
6434 
6435 		/* continue until a nembed page worth of sgls */
6436 		if (post_cnt == 0)
6437 			continue;
6438 
6439 		/* post the buffer list sgls as a block */
6440 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
6441 						 post_cnt);
6442 
6443 		if (!status) {
6444 			/* success, put sgl list to posted sgl list */
6445 			list_splice_init(&blck_sgl_list, &post_sgl_list);
6446 		} else {
6447 			/* Failure, put sgl list to free sgl list */
6448 			sglq_entry_first = list_first_entry(&blck_sgl_list,
6449 							    struct lpfc_sglq,
6450 							    list);
6451 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6452 					"3160 Failed to post sgl-list, "
6453 					"xritag:x%x-x%x\n",
6454 					sglq_entry_first->sli4_xritag,
6455 					(sglq_entry_first->sli4_xritag +
6456 					 post_cnt - 1));
6457 			list_splice_init(&blck_sgl_list, &free_sgl_list);
6458 			total_cnt -= post_cnt;
6459 		}
6460 
6461 		/* don't reset xirtag due to hole in xri block */
6462 		if (block_cnt == 0)
6463 			last_xritag = NO_XRI;
6464 
6465 		/* reset sgl post count for next round of posting */
6466 		post_cnt = 0;
6467 	}
6468 
6469 	/* free the sgls failed to post */
6470 	lpfc_free_sgl_list(phba, &free_sgl_list);
6471 
6472 	/* push sgls posted to the available list */
6473 	if (!list_empty(&post_sgl_list)) {
6474 		spin_lock_irq(&phba->hbalock);
6475 		spin_lock(&phba->sli4_hba.sgl_list_lock);
6476 		list_splice_init(&post_sgl_list, sgl_list);
6477 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
6478 		spin_unlock_irq(&phba->hbalock);
6479 	} else {
6480 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6481 				"3161 Failure to post sgl to port.\n");
6482 		return -EIO;
6483 	}
6484 
6485 	/* return the number of XRIs actually posted */
6486 	return total_cnt;
6487 }
6488 
6489 void
6490 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
6491 {
6492 	uint32_t len;
6493 
6494 	len = sizeof(struct lpfc_mbx_set_host_data) -
6495 		sizeof(struct lpfc_sli4_cfg_mhdr);
6496 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6497 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
6498 			 LPFC_SLI4_MBX_EMBED);
6499 
6500 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
6501 	mbox->u.mqe.un.set_host_data.param_len =
6502 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
6503 	snprintf(mbox->u.mqe.un.set_host_data.data,
6504 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
6505 		 "Linux %s v"LPFC_DRIVER_VERSION,
6506 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
6507 }
6508 
6509 /**
6510  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
6511  * @phba: Pointer to HBA context object.
6512  *
6513  * This function is the main SLI4 device initialization PCI function. This
6514  * function is called by the HBA initialization code, HBA reset code and
6515  * HBA error attention handler code. Caller is not required to hold any
6516  * locks.
6517  **/
6518 int
6519 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
6520 {
6521 	int rc, i;
6522 	LPFC_MBOXQ_t *mboxq;
6523 	struct lpfc_mqe *mqe;
6524 	uint8_t *vpd;
6525 	uint32_t vpd_size;
6526 	uint32_t ftr_rsp = 0;
6527 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
6528 	struct lpfc_vport *vport = phba->pport;
6529 	struct lpfc_dmabuf *mp;
6530 	struct lpfc_rqb *rqbp;
6531 
6532 	/* Perform a PCI function reset to start from clean */
6533 	rc = lpfc_pci_function_reset(phba);
6534 	if (unlikely(rc))
6535 		return -ENODEV;
6536 
6537 	/* Check the HBA Host Status Register for readyness */
6538 	rc = lpfc_sli4_post_status_check(phba);
6539 	if (unlikely(rc))
6540 		return -ENODEV;
6541 	else {
6542 		spin_lock_irq(&phba->hbalock);
6543 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
6544 		spin_unlock_irq(&phba->hbalock);
6545 	}
6546 
6547 	/*
6548 	 * Allocate a single mailbox container for initializing the
6549 	 * port.
6550 	 */
6551 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6552 	if (!mboxq)
6553 		return -ENOMEM;
6554 
6555 	/* Issue READ_REV to collect vpd and FW information. */
6556 	vpd_size = SLI4_PAGE_SIZE;
6557 	vpd = kzalloc(vpd_size, GFP_KERNEL);
6558 	if (!vpd) {
6559 		rc = -ENOMEM;
6560 		goto out_free_mbox;
6561 	}
6562 
6563 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
6564 	if (unlikely(rc)) {
6565 		kfree(vpd);
6566 		goto out_free_mbox;
6567 	}
6568 
6569 	mqe = &mboxq->u.mqe;
6570 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
6571 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
6572 		phba->hba_flag |= HBA_FCOE_MODE;
6573 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
6574 	} else {
6575 		phba->hba_flag &= ~HBA_FCOE_MODE;
6576 	}
6577 
6578 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
6579 		LPFC_DCBX_CEE_MODE)
6580 		phba->hba_flag |= HBA_FIP_SUPPORT;
6581 	else
6582 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
6583 
6584 	phba->hba_flag &= ~HBA_FCP_IOQ_FLUSH;
6585 
6586 	if (phba->sli_rev != LPFC_SLI_REV4) {
6587 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6588 			"0376 READ_REV Error. SLI Level %d "
6589 			"FCoE enabled %d\n",
6590 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
6591 		rc = -EIO;
6592 		kfree(vpd);
6593 		goto out_free_mbox;
6594 	}
6595 
6596 	/*
6597 	 * Continue initialization with default values even if driver failed
6598 	 * to read FCoE param config regions, only read parameters if the
6599 	 * board is FCoE
6600 	 */
6601 	if (phba->hba_flag & HBA_FCOE_MODE &&
6602 	    lpfc_sli4_read_fcoe_params(phba))
6603 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
6604 			"2570 Failed to read FCoE parameters\n");
6605 
6606 	/*
6607 	 * Retrieve sli4 device physical port name, failure of doing it
6608 	 * is considered as non-fatal.
6609 	 */
6610 	rc = lpfc_sli4_retrieve_pport_name(phba);
6611 	if (!rc)
6612 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
6613 				"3080 Successful retrieving SLI4 device "
6614 				"physical port name: %s.\n", phba->Port);
6615 
6616 	/*
6617 	 * Evaluate the read rev and vpd data. Populate the driver
6618 	 * state with the results. If this routine fails, the failure
6619 	 * is not fatal as the driver will use generic values.
6620 	 */
6621 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
6622 	if (unlikely(!rc)) {
6623 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6624 				"0377 Error %d parsing vpd. "
6625 				"Using defaults.\n", rc);
6626 		rc = 0;
6627 	}
6628 	kfree(vpd);
6629 
6630 	/* Save information as VPD data */
6631 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
6632 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
6633 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
6634 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
6635 					 &mqe->un.read_rev);
6636 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
6637 				       &mqe->un.read_rev);
6638 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
6639 					    &mqe->un.read_rev);
6640 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
6641 					   &mqe->un.read_rev);
6642 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
6643 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
6644 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
6645 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
6646 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
6647 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
6648 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
6649 			"(%d):0380 READ_REV Status x%x "
6650 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
6651 			mboxq->vport ? mboxq->vport->vpi : 0,
6652 			bf_get(lpfc_mqe_status, mqe),
6653 			phba->vpd.rev.opFwName,
6654 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
6655 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
6656 
6657 	/* Reset the DFT_LUN_Q_DEPTH to (max xri >> 3)  */
6658 	rc = (phba->sli4_hba.max_cfg_param.max_xri >> 3);
6659 	if (phba->pport->cfg_lun_queue_depth > rc) {
6660 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6661 				"3362 LUN queue depth changed from %d to %d\n",
6662 				phba->pport->cfg_lun_queue_depth, rc);
6663 		phba->pport->cfg_lun_queue_depth = rc;
6664 	}
6665 
6666 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
6667 	    LPFC_SLI_INTF_IF_TYPE_0) {
6668 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
6669 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6670 		if (rc == MBX_SUCCESS) {
6671 			phba->hba_flag |= HBA_RECOVERABLE_UE;
6672 			/* Set 1Sec interval to detect UE */
6673 			phba->eratt_poll_interval = 1;
6674 			phba->sli4_hba.ue_to_sr = bf_get(
6675 					lpfc_mbx_set_feature_UESR,
6676 					&mboxq->u.mqe.un.set_feature);
6677 			phba->sli4_hba.ue_to_rp = bf_get(
6678 					lpfc_mbx_set_feature_UERP,
6679 					&mboxq->u.mqe.un.set_feature);
6680 		}
6681 	}
6682 
6683 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
6684 		/* Enable MDS Diagnostics only if the SLI Port supports it */
6685 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
6686 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6687 		if (rc != MBX_SUCCESS)
6688 			phba->mds_diags_support = 0;
6689 	}
6690 
6691 	/*
6692 	 * Discover the port's supported feature set and match it against the
6693 	 * hosts requests.
6694 	 */
6695 	lpfc_request_features(phba, mboxq);
6696 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6697 	if (unlikely(rc)) {
6698 		rc = -EIO;
6699 		goto out_free_mbox;
6700 	}
6701 
6702 	/*
6703 	 * The port must support FCP initiator mode as this is the
6704 	 * only mode running in the host.
6705 	 */
6706 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
6707 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
6708 				"0378 No support for fcpi mode.\n");
6709 		ftr_rsp++;
6710 	}
6711 	if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
6712 		phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
6713 	else
6714 		phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
6715 	/*
6716 	 * If the port cannot support the host's requested features
6717 	 * then turn off the global config parameters to disable the
6718 	 * feature in the driver.  This is not a fatal error.
6719 	 */
6720 	phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
6721 	if (phba->cfg_enable_bg) {
6722 		if (bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))
6723 			phba->sli3_options |= LPFC_SLI3_BG_ENABLED;
6724 		else
6725 			ftr_rsp++;
6726 	}
6727 
6728 	if (phba->max_vpi && phba->cfg_enable_npiv &&
6729 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
6730 		ftr_rsp++;
6731 
6732 	if (ftr_rsp) {
6733 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
6734 				"0379 Feature Mismatch Data: x%08x %08x "
6735 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
6736 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
6737 				phba->cfg_enable_npiv, phba->max_vpi);
6738 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
6739 			phba->cfg_enable_bg = 0;
6740 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
6741 			phba->cfg_enable_npiv = 0;
6742 	}
6743 
6744 	/* These SLI3 features are assumed in SLI4 */
6745 	spin_lock_irq(&phba->hbalock);
6746 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
6747 	spin_unlock_irq(&phba->hbalock);
6748 
6749 	/*
6750 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
6751 	 * calls depends on these resources to complete port setup.
6752 	 */
6753 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
6754 	if (rc) {
6755 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6756 				"2920 Failed to alloc Resource IDs "
6757 				"rc = x%x\n", rc);
6758 		goto out_free_mbox;
6759 	}
6760 
6761 	lpfc_set_host_data(phba, mboxq);
6762 
6763 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6764 	if (rc) {
6765 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
6766 				"2134 Failed to set host os driver version %x",
6767 				rc);
6768 	}
6769 
6770 	/* Read the port's service parameters. */
6771 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
6772 	if (rc) {
6773 		phba->link_state = LPFC_HBA_ERROR;
6774 		rc = -ENOMEM;
6775 		goto out_free_mbox;
6776 	}
6777 
6778 	mboxq->vport = vport;
6779 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6780 	mp = (struct lpfc_dmabuf *) mboxq->context1;
6781 	if (rc == MBX_SUCCESS) {
6782 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
6783 		rc = 0;
6784 	}
6785 
6786 	/*
6787 	 * This memory was allocated by the lpfc_read_sparam routine. Release
6788 	 * it to the mbuf pool.
6789 	 */
6790 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
6791 	kfree(mp);
6792 	mboxq->context1 = NULL;
6793 	if (unlikely(rc)) {
6794 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6795 				"0382 READ_SPARAM command failed "
6796 				"status %d, mbxStatus x%x\n",
6797 				rc, bf_get(lpfc_mqe_status, mqe));
6798 		phba->link_state = LPFC_HBA_ERROR;
6799 		rc = -EIO;
6800 		goto out_free_mbox;
6801 	}
6802 
6803 	lpfc_update_vport_wwn(vport);
6804 
6805 	/* Update the fc_host data structures with new wwn. */
6806 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
6807 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
6808 
6809 	/* Create all the SLI4 queues */
6810 	rc = lpfc_sli4_queue_create(phba);
6811 	if (rc) {
6812 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6813 				"3089 Failed to allocate queues\n");
6814 		rc = -ENODEV;
6815 		goto out_free_mbox;
6816 	}
6817 	/* Set up all the queues to the device */
6818 	rc = lpfc_sli4_queue_setup(phba);
6819 	if (unlikely(rc)) {
6820 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6821 				"0381 Error %d during queue setup.\n ", rc);
6822 		goto out_stop_timers;
6823 	}
6824 	/* Initialize the driver internal SLI layer lists. */
6825 	lpfc_sli4_setup(phba);
6826 	lpfc_sli4_queue_init(phba);
6827 
6828 	/* update host els xri-sgl sizes and mappings */
6829 	rc = lpfc_sli4_els_sgl_update(phba);
6830 	if (unlikely(rc)) {
6831 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6832 				"1400 Failed to update xri-sgl size and "
6833 				"mapping: %d\n", rc);
6834 		goto out_destroy_queue;
6835 	}
6836 
6837 	/* register the els sgl pool to the port */
6838 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
6839 				       phba->sli4_hba.els_xri_cnt);
6840 	if (unlikely(rc < 0)) {
6841 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6842 				"0582 Error %d during els sgl post "
6843 				"operation\n", rc);
6844 		rc = -ENODEV;
6845 		goto out_destroy_queue;
6846 	}
6847 	phba->sli4_hba.els_xri_cnt = rc;
6848 
6849 	if (phba->nvmet_support) {
6850 		/* update host nvmet xri-sgl sizes and mappings */
6851 		rc = lpfc_sli4_nvmet_sgl_update(phba);
6852 		if (unlikely(rc)) {
6853 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6854 					"6308 Failed to update nvmet-sgl size "
6855 					"and mapping: %d\n", rc);
6856 			goto out_destroy_queue;
6857 		}
6858 
6859 		/* register the nvmet sgl pool to the port */
6860 		rc = lpfc_sli4_repost_sgl_list(
6861 			phba,
6862 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
6863 			phba->sli4_hba.nvmet_xri_cnt);
6864 		if (unlikely(rc < 0)) {
6865 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6866 					"3117 Error %d during nvmet "
6867 					"sgl post\n", rc);
6868 			rc = -ENODEV;
6869 			goto out_destroy_queue;
6870 		}
6871 		phba->sli4_hba.nvmet_xri_cnt = rc;
6872 		lpfc_nvmet_create_targetport(phba);
6873 	} else {
6874 		/* update host scsi xri-sgl sizes and mappings */
6875 		rc = lpfc_sli4_scsi_sgl_update(phba);
6876 		if (unlikely(rc)) {
6877 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6878 					"6309 Failed to update scsi-sgl size "
6879 					"and mapping: %d\n", rc);
6880 			goto out_destroy_queue;
6881 		}
6882 
6883 		/* update host nvme xri-sgl sizes and mappings */
6884 		rc = lpfc_sli4_nvme_sgl_update(phba);
6885 		if (unlikely(rc)) {
6886 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6887 					"6082 Failed to update nvme-sgl size "
6888 					"and mapping: %d\n", rc);
6889 			goto out_destroy_queue;
6890 		}
6891 	}
6892 
6893 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
6894 
6895 		/* Post initial buffers to all RQs created */
6896 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
6897 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
6898 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
6899 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
6900 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
6901 			rqbp->entry_count = 256;
6902 			rqbp->buffer_count = 0;
6903 
6904 			/* Divide by 4 and round down to multiple of 16 */
6905 			rc = (phba->cfg_nvmet_mrq_post >> 2) & 0xfff8;
6906 			phba->sli4_hba.nvmet_mrq_hdr[i]->entry_repost = rc;
6907 			phba->sli4_hba.nvmet_mrq_data[i]->entry_repost = rc;
6908 
6909 			lpfc_post_rq_buffer(
6910 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
6911 				phba->sli4_hba.nvmet_mrq_data[i],
6912 				phba->cfg_nvmet_mrq_post);
6913 		}
6914 	}
6915 
6916 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
6917 		/* register the allocated scsi sgl pool to the port */
6918 		rc = lpfc_sli4_repost_scsi_sgl_list(phba);
6919 		if (unlikely(rc)) {
6920 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6921 					"0383 Error %d during scsi sgl post "
6922 					"operation\n", rc);
6923 			/* Some Scsi buffers were moved to abort scsi list */
6924 			/* A pci function reset will repost them */
6925 			rc = -ENODEV;
6926 			goto out_destroy_queue;
6927 		}
6928 	}
6929 
6930 	if ((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) &&
6931 	    (phba->nvmet_support == 0)) {
6932 
6933 		/* register the allocated nvme sgl pool to the port */
6934 		rc = lpfc_repost_nvme_sgl_list(phba);
6935 		if (unlikely(rc)) {
6936 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6937 					"6116 Error %d during nvme sgl post "
6938 					"operation\n", rc);
6939 			/* Some NVME buffers were moved to abort nvme list */
6940 			/* A pci function reset will repost them */
6941 			rc = -ENODEV;
6942 			goto out_destroy_queue;
6943 		}
6944 	}
6945 
6946 	/* Post the rpi header region to the device. */
6947 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
6948 	if (unlikely(rc)) {
6949 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6950 				"0393 Error %d during rpi post operation\n",
6951 				rc);
6952 		rc = -ENODEV;
6953 		goto out_destroy_queue;
6954 	}
6955 	lpfc_sli4_node_prep(phba);
6956 
6957 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
6958 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
6959 			/*
6960 			 * The FC Port needs to register FCFI (index 0)
6961 			 */
6962 			lpfc_reg_fcfi(phba, mboxq);
6963 			mboxq->vport = phba->pport;
6964 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6965 			if (rc != MBX_SUCCESS)
6966 				goto out_unset_queue;
6967 			rc = 0;
6968 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
6969 						&mboxq->u.mqe.un.reg_fcfi);
6970 		} else {
6971 			/* We are a NVME Target mode with MRQ > 1 */
6972 
6973 			/* First register the FCFI */
6974 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
6975 			mboxq->vport = phba->pport;
6976 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6977 			if (rc != MBX_SUCCESS)
6978 				goto out_unset_queue;
6979 			rc = 0;
6980 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
6981 						&mboxq->u.mqe.un.reg_fcfi_mrq);
6982 
6983 			/* Next register the MRQs */
6984 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
6985 			mboxq->vport = phba->pport;
6986 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6987 			if (rc != MBX_SUCCESS)
6988 				goto out_unset_queue;
6989 			rc = 0;
6990 		}
6991 		/* Check if the port is configured to be disabled */
6992 		lpfc_sli_read_link_ste(phba);
6993 	}
6994 
6995 	/* Arm the CQs and then EQs on device */
6996 	lpfc_sli4_arm_cqeq_intr(phba);
6997 
6998 	/* Indicate device interrupt mode */
6999 	phba->sli4_hba.intr_enable = 1;
7000 
7001 	/* Allow asynchronous mailbox command to go through */
7002 	spin_lock_irq(&phba->hbalock);
7003 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7004 	spin_unlock_irq(&phba->hbalock);
7005 
7006 	/* Post receive buffers to the device */
7007 	lpfc_sli4_rb_setup(phba);
7008 
7009 	/* Reset HBA FCF states after HBA reset */
7010 	phba->fcf.fcf_flag = 0;
7011 	phba->fcf.current_rec.flag = 0;
7012 
7013 	/* Start the ELS watchdog timer */
7014 	mod_timer(&vport->els_tmofunc,
7015 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
7016 
7017 	/* Start heart beat timer */
7018 	mod_timer(&phba->hb_tmofunc,
7019 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
7020 	phba->hb_outstanding = 0;
7021 	phba->last_completion_time = jiffies;
7022 
7023 	/* Start error attention (ERATT) polling timer */
7024 	mod_timer(&phba->eratt_poll,
7025 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
7026 
7027 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
7028 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
7029 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
7030 		if (!rc) {
7031 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7032 					"2829 This device supports "
7033 					"Advanced Error Reporting (AER)\n");
7034 			spin_lock_irq(&phba->hbalock);
7035 			phba->hba_flag |= HBA_AER_ENABLED;
7036 			spin_unlock_irq(&phba->hbalock);
7037 		} else {
7038 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7039 					"2830 This device does not support "
7040 					"Advanced Error Reporting (AER)\n");
7041 			phba->cfg_aer_support = 0;
7042 		}
7043 		rc = 0;
7044 	}
7045 
7046 	/*
7047 	 * The port is ready, set the host's link state to LINK_DOWN
7048 	 * in preparation for link interrupts.
7049 	 */
7050 	spin_lock_irq(&phba->hbalock);
7051 	phba->link_state = LPFC_LINK_DOWN;
7052 	spin_unlock_irq(&phba->hbalock);
7053 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
7054 	    (phba->hba_flag & LINK_DISABLED)) {
7055 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
7056 				"3103 Adapter Link is disabled.\n");
7057 		lpfc_down_link(phba, mboxq);
7058 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7059 		if (rc != MBX_SUCCESS) {
7060 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
7061 					"3104 Adapter failed to issue "
7062 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
7063 			goto out_unset_queue;
7064 		}
7065 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
7066 		/* don't perform init_link on SLI4 FC port loopback test */
7067 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
7068 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
7069 			if (rc)
7070 				goto out_unset_queue;
7071 		}
7072 	}
7073 	mempool_free(mboxq, phba->mbox_mem_pool);
7074 	return rc;
7075 out_unset_queue:
7076 	/* Unset all the queues set up in this routine when error out */
7077 	lpfc_sli4_queue_unset(phba);
7078 out_destroy_queue:
7079 	lpfc_sli4_queue_destroy(phba);
7080 out_stop_timers:
7081 	lpfc_stop_hba_timers(phba);
7082 out_free_mbox:
7083 	mempool_free(mboxq, phba->mbox_mem_pool);
7084 	return rc;
7085 }
7086 
7087 /**
7088  * lpfc_mbox_timeout - Timeout call back function for mbox timer
7089  * @ptr: context object - pointer to hba structure.
7090  *
7091  * This is the callback function for mailbox timer. The mailbox
7092  * timer is armed when a new mailbox command is issued and the timer
7093  * is deleted when the mailbox complete. The function is called by
7094  * the kernel timer code when a mailbox does not complete within
7095  * expected time. This function wakes up the worker thread to
7096  * process the mailbox timeout and returns. All the processing is
7097  * done by the worker thread function lpfc_mbox_timeout_handler.
7098  **/
7099 void
7100 lpfc_mbox_timeout(unsigned long ptr)
7101 {
7102 	struct lpfc_hba  *phba = (struct lpfc_hba *) ptr;
7103 	unsigned long iflag;
7104 	uint32_t tmo_posted;
7105 
7106 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
7107 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
7108 	if (!tmo_posted)
7109 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
7110 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
7111 
7112 	if (!tmo_posted)
7113 		lpfc_worker_wake_up(phba);
7114 	return;
7115 }
7116 
7117 /**
7118  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
7119  *                                    are pending
7120  * @phba: Pointer to HBA context object.
7121  *
7122  * This function checks if any mailbox completions are present on the mailbox
7123  * completion queue.
7124  **/
7125 static bool
7126 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
7127 {
7128 
7129 	uint32_t idx;
7130 	struct lpfc_queue *mcq;
7131 	struct lpfc_mcqe *mcqe;
7132 	bool pending_completions = false;
7133 
7134 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
7135 		return false;
7136 
7137 	/* Check for completions on mailbox completion queue */
7138 
7139 	mcq = phba->sli4_hba.mbx_cq;
7140 	idx = mcq->hba_index;
7141 	while (bf_get_le32(lpfc_cqe_valid, mcq->qe[idx].cqe)) {
7142 		mcqe = (struct lpfc_mcqe *)mcq->qe[idx].cqe;
7143 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
7144 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
7145 			pending_completions = true;
7146 			break;
7147 		}
7148 		idx = (idx + 1) % mcq->entry_count;
7149 		if (mcq->hba_index == idx)
7150 			break;
7151 	}
7152 	return pending_completions;
7153 
7154 }
7155 
7156 /**
7157  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
7158  *					      that were missed.
7159  * @phba: Pointer to HBA context object.
7160  *
7161  * For sli4, it is possible to miss an interrupt. As such mbox completions
7162  * maybe missed causing erroneous mailbox timeouts to occur. This function
7163  * checks to see if mbox completions are on the mailbox completion queue
7164  * and will process all the completions associated with the eq for the
7165  * mailbox completion queue.
7166  **/
7167 bool
7168 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
7169 {
7170 
7171 	uint32_t eqidx;
7172 	struct lpfc_queue *fpeq = NULL;
7173 	struct lpfc_eqe *eqe;
7174 	bool mbox_pending;
7175 
7176 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
7177 		return false;
7178 
7179 	/* Find the eq associated with the mcq */
7180 
7181 	if (phba->sli4_hba.hba_eq)
7182 		for (eqidx = 0; eqidx < phba->io_channel_irqs; eqidx++)
7183 			if (phba->sli4_hba.hba_eq[eqidx]->queue_id ==
7184 			    phba->sli4_hba.mbx_cq->assoc_qid) {
7185 				fpeq = phba->sli4_hba.hba_eq[eqidx];
7186 				break;
7187 			}
7188 	if (!fpeq)
7189 		return false;
7190 
7191 	/* Turn off interrupts from this EQ */
7192 
7193 	lpfc_sli4_eq_clr_intr(fpeq);
7194 
7195 	/* Check to see if a mbox completion is pending */
7196 
7197 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
7198 
7199 	/*
7200 	 * If a mbox completion is pending, process all the events on EQ
7201 	 * associated with the mbox completion queue (this could include
7202 	 * mailbox commands, async events, els commands, receive queue data
7203 	 * and fcp commands)
7204 	 */
7205 
7206 	if (mbox_pending)
7207 		while ((eqe = lpfc_sli4_eq_get(fpeq))) {
7208 			lpfc_sli4_hba_handle_eqe(phba, eqe, eqidx);
7209 			fpeq->EQ_processed++;
7210 		}
7211 
7212 	/* Always clear and re-arm the EQ */
7213 
7214 	lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_REARM);
7215 
7216 	return mbox_pending;
7217 
7218 }
7219 
7220 /**
7221  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
7222  * @phba: Pointer to HBA context object.
7223  *
7224  * This function is called from worker thread when a mailbox command times out.
7225  * The caller is not required to hold any locks. This function will reset the
7226  * HBA and recover all the pending commands.
7227  **/
7228 void
7229 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
7230 {
7231 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
7232 	MAILBOX_t *mb = NULL;
7233 
7234 	struct lpfc_sli *psli = &phba->sli;
7235 
7236 	/* If the mailbox completed, process the completion and return */
7237 	if (lpfc_sli4_process_missed_mbox_completions(phba))
7238 		return;
7239 
7240 	if (pmbox != NULL)
7241 		mb = &pmbox->u.mb;
7242 	/* Check the pmbox pointer first.  There is a race condition
7243 	 * between the mbox timeout handler getting executed in the
7244 	 * worklist and the mailbox actually completing. When this
7245 	 * race condition occurs, the mbox_active will be NULL.
7246 	 */
7247 	spin_lock_irq(&phba->hbalock);
7248 	if (pmbox == NULL) {
7249 		lpfc_printf_log(phba, KERN_WARNING,
7250 				LOG_MBOX | LOG_SLI,
7251 				"0353 Active Mailbox cleared - mailbox timeout "
7252 				"exiting\n");
7253 		spin_unlock_irq(&phba->hbalock);
7254 		return;
7255 	}
7256 
7257 	/* Mbox cmd <mbxCommand> timeout */
7258 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7259 			"0310 Mailbox command x%x timeout Data: x%x x%x x%p\n",
7260 			mb->mbxCommand,
7261 			phba->pport->port_state,
7262 			phba->sli.sli_flag,
7263 			phba->sli.mbox_active);
7264 	spin_unlock_irq(&phba->hbalock);
7265 
7266 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
7267 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
7268 	 * it to fail all outstanding SCSI IO.
7269 	 */
7270 	spin_lock_irq(&phba->pport->work_port_lock);
7271 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
7272 	spin_unlock_irq(&phba->pport->work_port_lock);
7273 	spin_lock_irq(&phba->hbalock);
7274 	phba->link_state = LPFC_LINK_UNKNOWN;
7275 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
7276 	spin_unlock_irq(&phba->hbalock);
7277 
7278 	lpfc_sli_abort_fcp_rings(phba);
7279 
7280 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7281 			"0345 Resetting board due to mailbox timeout\n");
7282 
7283 	/* Reset the HBA device */
7284 	lpfc_reset_hba(phba);
7285 }
7286 
7287 /**
7288  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
7289  * @phba: Pointer to HBA context object.
7290  * @pmbox: Pointer to mailbox object.
7291  * @flag: Flag indicating how the mailbox need to be processed.
7292  *
7293  * This function is called by discovery code and HBA management code
7294  * to submit a mailbox command to firmware with SLI-3 interface spec. This
7295  * function gets the hbalock to protect the data structures.
7296  * The mailbox command can be submitted in polling mode, in which case
7297  * this function will wait in a polling loop for the completion of the
7298  * mailbox.
7299  * If the mailbox is submitted in no_wait mode (not polling) the
7300  * function will submit the command and returns immediately without waiting
7301  * for the mailbox completion. The no_wait is supported only when HBA
7302  * is in SLI2/SLI3 mode - interrupts are enabled.
7303  * The SLI interface allows only one mailbox pending at a time. If the
7304  * mailbox is issued in polling mode and there is already a mailbox
7305  * pending, then the function will return an error. If the mailbox is issued
7306  * in NO_WAIT mode and there is a mailbox pending already, the function
7307  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
7308  * The sli layer owns the mailbox object until the completion of mailbox
7309  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
7310  * return codes the caller owns the mailbox command after the return of
7311  * the function.
7312  **/
7313 static int
7314 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
7315 		       uint32_t flag)
7316 {
7317 	MAILBOX_t *mbx;
7318 	struct lpfc_sli *psli = &phba->sli;
7319 	uint32_t status, evtctr;
7320 	uint32_t ha_copy, hc_copy;
7321 	int i;
7322 	unsigned long timeout;
7323 	unsigned long drvr_flag = 0;
7324 	uint32_t word0, ldata;
7325 	void __iomem *to_slim;
7326 	int processing_queue = 0;
7327 
7328 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
7329 	if (!pmbox) {
7330 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7331 		/* processing mbox queue from intr_handler */
7332 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
7333 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7334 			return MBX_SUCCESS;
7335 		}
7336 		processing_queue = 1;
7337 		pmbox = lpfc_mbox_get(phba);
7338 		if (!pmbox) {
7339 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7340 			return MBX_SUCCESS;
7341 		}
7342 	}
7343 
7344 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
7345 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
7346 		if(!pmbox->vport) {
7347 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7348 			lpfc_printf_log(phba, KERN_ERR,
7349 					LOG_MBOX | LOG_VPORT,
7350 					"1806 Mbox x%x failed. No vport\n",
7351 					pmbox->u.mb.mbxCommand);
7352 			dump_stack();
7353 			goto out_not_finished;
7354 		}
7355 	}
7356 
7357 	/* If the PCI channel is in offline state, do not post mbox. */
7358 	if (unlikely(pci_channel_offline(phba->pcidev))) {
7359 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7360 		goto out_not_finished;
7361 	}
7362 
7363 	/* If HBA has a deferred error attention, fail the iocb. */
7364 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
7365 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7366 		goto out_not_finished;
7367 	}
7368 
7369 	psli = &phba->sli;
7370 
7371 	mbx = &pmbox->u.mb;
7372 	status = MBX_SUCCESS;
7373 
7374 	if (phba->link_state == LPFC_HBA_ERROR) {
7375 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7376 
7377 		/* Mbox command <mbxCommand> cannot issue */
7378 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7379 				"(%d):0311 Mailbox command x%x cannot "
7380 				"issue Data: x%x x%x\n",
7381 				pmbox->vport ? pmbox->vport->vpi : 0,
7382 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
7383 		goto out_not_finished;
7384 	}
7385 
7386 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
7387 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
7388 			!(hc_copy & HC_MBINT_ENA)) {
7389 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7390 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7391 				"(%d):2528 Mailbox command x%x cannot "
7392 				"issue Data: x%x x%x\n",
7393 				pmbox->vport ? pmbox->vport->vpi : 0,
7394 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
7395 			goto out_not_finished;
7396 		}
7397 	}
7398 
7399 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
7400 		/* Polling for a mbox command when another one is already active
7401 		 * is not allowed in SLI. Also, the driver must have established
7402 		 * SLI2 mode to queue and process multiple mbox commands.
7403 		 */
7404 
7405 		if (flag & MBX_POLL) {
7406 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7407 
7408 			/* Mbox command <mbxCommand> cannot issue */
7409 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7410 					"(%d):2529 Mailbox command x%x "
7411 					"cannot issue Data: x%x x%x\n",
7412 					pmbox->vport ? pmbox->vport->vpi : 0,
7413 					pmbox->u.mb.mbxCommand,
7414 					psli->sli_flag, flag);
7415 			goto out_not_finished;
7416 		}
7417 
7418 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
7419 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7420 			/* Mbox command <mbxCommand> cannot issue */
7421 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7422 					"(%d):2530 Mailbox command x%x "
7423 					"cannot issue Data: x%x x%x\n",
7424 					pmbox->vport ? pmbox->vport->vpi : 0,
7425 					pmbox->u.mb.mbxCommand,
7426 					psli->sli_flag, flag);
7427 			goto out_not_finished;
7428 		}
7429 
7430 		/* Another mailbox command is still being processed, queue this
7431 		 * command to be processed later.
7432 		 */
7433 		lpfc_mbox_put(phba, pmbox);
7434 
7435 		/* Mbox cmd issue - BUSY */
7436 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7437 				"(%d):0308 Mbox cmd issue - BUSY Data: "
7438 				"x%x x%x x%x x%x\n",
7439 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
7440 				mbx->mbxCommand, phba->pport->port_state,
7441 				psli->sli_flag, flag);
7442 
7443 		psli->slistat.mbox_busy++;
7444 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7445 
7446 		if (pmbox->vport) {
7447 			lpfc_debugfs_disc_trc(pmbox->vport,
7448 				LPFC_DISC_TRC_MBOX_VPORT,
7449 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
7450 				(uint32_t)mbx->mbxCommand,
7451 				mbx->un.varWords[0], mbx->un.varWords[1]);
7452 		}
7453 		else {
7454 			lpfc_debugfs_disc_trc(phba->pport,
7455 				LPFC_DISC_TRC_MBOX,
7456 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
7457 				(uint32_t)mbx->mbxCommand,
7458 				mbx->un.varWords[0], mbx->un.varWords[1]);
7459 		}
7460 
7461 		return MBX_BUSY;
7462 	}
7463 
7464 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7465 
7466 	/* If we are not polling, we MUST be in SLI2 mode */
7467 	if (flag != MBX_POLL) {
7468 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
7469 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
7470 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7471 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7472 			/* Mbox command <mbxCommand> cannot issue */
7473 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7474 					"(%d):2531 Mailbox command x%x "
7475 					"cannot issue Data: x%x x%x\n",
7476 					pmbox->vport ? pmbox->vport->vpi : 0,
7477 					pmbox->u.mb.mbxCommand,
7478 					psli->sli_flag, flag);
7479 			goto out_not_finished;
7480 		}
7481 		/* timeout active mbox command */
7482 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
7483 					   1000);
7484 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
7485 	}
7486 
7487 	/* Mailbox cmd <cmd> issue */
7488 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7489 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
7490 			"x%x\n",
7491 			pmbox->vport ? pmbox->vport->vpi : 0,
7492 			mbx->mbxCommand, phba->pport->port_state,
7493 			psli->sli_flag, flag);
7494 
7495 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
7496 		if (pmbox->vport) {
7497 			lpfc_debugfs_disc_trc(pmbox->vport,
7498 				LPFC_DISC_TRC_MBOX_VPORT,
7499 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
7500 				(uint32_t)mbx->mbxCommand,
7501 				mbx->un.varWords[0], mbx->un.varWords[1]);
7502 		}
7503 		else {
7504 			lpfc_debugfs_disc_trc(phba->pport,
7505 				LPFC_DISC_TRC_MBOX,
7506 				"MBOX Send:       cmd:x%x mb:x%x x%x",
7507 				(uint32_t)mbx->mbxCommand,
7508 				mbx->un.varWords[0], mbx->un.varWords[1]);
7509 		}
7510 	}
7511 
7512 	psli->slistat.mbox_cmd++;
7513 	evtctr = psli->slistat.mbox_event;
7514 
7515 	/* next set own bit for the adapter and copy over command word */
7516 	mbx->mbxOwner = OWN_CHIP;
7517 
7518 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7519 		/* Populate mbox extension offset word. */
7520 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
7521 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
7522 				= (uint8_t *)phba->mbox_ext
7523 				  - (uint8_t *)phba->mbox;
7524 		}
7525 
7526 		/* Copy the mailbox extension data */
7527 		if (pmbox->in_ext_byte_len && pmbox->context2) {
7528 			lpfc_sli_pcimem_bcopy(pmbox->context2,
7529 				(uint8_t *)phba->mbox_ext,
7530 				pmbox->in_ext_byte_len);
7531 		}
7532 		/* Copy command data to host SLIM area */
7533 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
7534 	} else {
7535 		/* Populate mbox extension offset word. */
7536 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
7537 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
7538 				= MAILBOX_HBA_EXT_OFFSET;
7539 
7540 		/* Copy the mailbox extension data */
7541 		if (pmbox->in_ext_byte_len && pmbox->context2)
7542 			lpfc_memcpy_to_slim(phba->MBslimaddr +
7543 				MAILBOX_HBA_EXT_OFFSET,
7544 				pmbox->context2, pmbox->in_ext_byte_len);
7545 
7546 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
7547 			/* copy command data into host mbox for cmpl */
7548 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
7549 					      MAILBOX_CMD_SIZE);
7550 
7551 		/* First copy mbox command data to HBA SLIM, skip past first
7552 		   word */
7553 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
7554 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
7555 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
7556 
7557 		/* Next copy over first word, with mbxOwner set */
7558 		ldata = *((uint32_t *)mbx);
7559 		to_slim = phba->MBslimaddr;
7560 		writel(ldata, to_slim);
7561 		readl(to_slim); /* flush */
7562 
7563 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
7564 			/* switch over to host mailbox */
7565 			psli->sli_flag |= LPFC_SLI_ACTIVE;
7566 	}
7567 
7568 	wmb();
7569 
7570 	switch (flag) {
7571 	case MBX_NOWAIT:
7572 		/* Set up reference to mailbox command */
7573 		psli->mbox_active = pmbox;
7574 		/* Interrupt board to do it */
7575 		writel(CA_MBATT, phba->CAregaddr);
7576 		readl(phba->CAregaddr); /* flush */
7577 		/* Don't wait for it to finish, just return */
7578 		break;
7579 
7580 	case MBX_POLL:
7581 		/* Set up null reference to mailbox command */
7582 		psli->mbox_active = NULL;
7583 		/* Interrupt board to do it */
7584 		writel(CA_MBATT, phba->CAregaddr);
7585 		readl(phba->CAregaddr); /* flush */
7586 
7587 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7588 			/* First read mbox status word */
7589 			word0 = *((uint32_t *)phba->mbox);
7590 			word0 = le32_to_cpu(word0);
7591 		} else {
7592 			/* First read mbox status word */
7593 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
7594 				spin_unlock_irqrestore(&phba->hbalock,
7595 						       drvr_flag);
7596 				goto out_not_finished;
7597 			}
7598 		}
7599 
7600 		/* Read the HBA Host Attention Register */
7601 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
7602 			spin_unlock_irqrestore(&phba->hbalock,
7603 						       drvr_flag);
7604 			goto out_not_finished;
7605 		}
7606 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
7607 							1000) + jiffies;
7608 		i = 0;
7609 		/* Wait for command to complete */
7610 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
7611 		       (!(ha_copy & HA_MBATT) &&
7612 			(phba->link_state > LPFC_WARM_START))) {
7613 			if (time_after(jiffies, timeout)) {
7614 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7615 				spin_unlock_irqrestore(&phba->hbalock,
7616 						       drvr_flag);
7617 				goto out_not_finished;
7618 			}
7619 
7620 			/* Check if we took a mbox interrupt while we were
7621 			   polling */
7622 			if (((word0 & OWN_CHIP) != OWN_CHIP)
7623 			    && (evtctr != psli->slistat.mbox_event))
7624 				break;
7625 
7626 			if (i++ > 10) {
7627 				spin_unlock_irqrestore(&phba->hbalock,
7628 						       drvr_flag);
7629 				msleep(1);
7630 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
7631 			}
7632 
7633 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7634 				/* First copy command data */
7635 				word0 = *((uint32_t *)phba->mbox);
7636 				word0 = le32_to_cpu(word0);
7637 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
7638 					MAILBOX_t *slimmb;
7639 					uint32_t slimword0;
7640 					/* Check real SLIM for any errors */
7641 					slimword0 = readl(phba->MBslimaddr);
7642 					slimmb = (MAILBOX_t *) & slimword0;
7643 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
7644 					    && slimmb->mbxStatus) {
7645 						psli->sli_flag &=
7646 						    ~LPFC_SLI_ACTIVE;
7647 						word0 = slimword0;
7648 					}
7649 				}
7650 			} else {
7651 				/* First copy command data */
7652 				word0 = readl(phba->MBslimaddr);
7653 			}
7654 			/* Read the HBA Host Attention Register */
7655 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
7656 				spin_unlock_irqrestore(&phba->hbalock,
7657 						       drvr_flag);
7658 				goto out_not_finished;
7659 			}
7660 		}
7661 
7662 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7663 			/* copy results back to user */
7664 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
7665 						MAILBOX_CMD_SIZE);
7666 			/* Copy the mailbox extension data */
7667 			if (pmbox->out_ext_byte_len && pmbox->context2) {
7668 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
7669 						      pmbox->context2,
7670 						      pmbox->out_ext_byte_len);
7671 			}
7672 		} else {
7673 			/* First copy command data */
7674 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
7675 						MAILBOX_CMD_SIZE);
7676 			/* Copy the mailbox extension data */
7677 			if (pmbox->out_ext_byte_len && pmbox->context2) {
7678 				lpfc_memcpy_from_slim(pmbox->context2,
7679 					phba->MBslimaddr +
7680 					MAILBOX_HBA_EXT_OFFSET,
7681 					pmbox->out_ext_byte_len);
7682 			}
7683 		}
7684 
7685 		writel(HA_MBATT, phba->HAregaddr);
7686 		readl(phba->HAregaddr); /* flush */
7687 
7688 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7689 		status = mbx->mbxStatus;
7690 	}
7691 
7692 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7693 	return status;
7694 
7695 out_not_finished:
7696 	if (processing_queue) {
7697 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
7698 		lpfc_mbox_cmpl_put(phba, pmbox);
7699 	}
7700 	return MBX_NOT_FINISHED;
7701 }
7702 
7703 /**
7704  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
7705  * @phba: Pointer to HBA context object.
7706  *
7707  * The function blocks the posting of SLI4 asynchronous mailbox commands from
7708  * the driver internal pending mailbox queue. It will then try to wait out the
7709  * possible outstanding mailbox command before return.
7710  *
7711  * Returns:
7712  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
7713  * 	the outstanding mailbox command timed out.
7714  **/
7715 static int
7716 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
7717 {
7718 	struct lpfc_sli *psli = &phba->sli;
7719 	int rc = 0;
7720 	unsigned long timeout = 0;
7721 
7722 	/* Mark the asynchronous mailbox command posting as blocked */
7723 	spin_lock_irq(&phba->hbalock);
7724 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
7725 	/* Determine how long we might wait for the active mailbox
7726 	 * command to be gracefully completed by firmware.
7727 	 */
7728 	if (phba->sli.mbox_active)
7729 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
7730 						phba->sli.mbox_active) *
7731 						1000) + jiffies;
7732 	spin_unlock_irq(&phba->hbalock);
7733 
7734 	/* Make sure the mailbox is really active */
7735 	if (timeout)
7736 		lpfc_sli4_process_missed_mbox_completions(phba);
7737 
7738 	/* Wait for the outstnading mailbox command to complete */
7739 	while (phba->sli.mbox_active) {
7740 		/* Check active mailbox complete status every 2ms */
7741 		msleep(2);
7742 		if (time_after(jiffies, timeout)) {
7743 			/* Timeout, marked the outstanding cmd not complete */
7744 			rc = 1;
7745 			break;
7746 		}
7747 	}
7748 
7749 	/* Can not cleanly block async mailbox command, fails it */
7750 	if (rc) {
7751 		spin_lock_irq(&phba->hbalock);
7752 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7753 		spin_unlock_irq(&phba->hbalock);
7754 	}
7755 	return rc;
7756 }
7757 
7758 /**
7759  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
7760  * @phba: Pointer to HBA context object.
7761  *
7762  * The function unblocks and resume posting of SLI4 asynchronous mailbox
7763  * commands from the driver internal pending mailbox queue. It makes sure
7764  * that there is no outstanding mailbox command before resuming posting
7765  * asynchronous mailbox commands. If, for any reason, there is outstanding
7766  * mailbox command, it will try to wait it out before resuming asynchronous
7767  * mailbox command posting.
7768  **/
7769 static void
7770 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
7771 {
7772 	struct lpfc_sli *psli = &phba->sli;
7773 
7774 	spin_lock_irq(&phba->hbalock);
7775 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
7776 		/* Asynchronous mailbox posting is not blocked, do nothing */
7777 		spin_unlock_irq(&phba->hbalock);
7778 		return;
7779 	}
7780 
7781 	/* Outstanding synchronous mailbox command is guaranteed to be done,
7782 	 * successful or timeout, after timing-out the outstanding mailbox
7783 	 * command shall always be removed, so just unblock posting async
7784 	 * mailbox command and resume
7785 	 */
7786 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7787 	spin_unlock_irq(&phba->hbalock);
7788 
7789 	/* wake up worker thread to post asynchronlous mailbox command */
7790 	lpfc_worker_wake_up(phba);
7791 }
7792 
7793 /**
7794  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
7795  * @phba: Pointer to HBA context object.
7796  * @mboxq: Pointer to mailbox object.
7797  *
7798  * The function waits for the bootstrap mailbox register ready bit from
7799  * port for twice the regular mailbox command timeout value.
7800  *
7801  *      0 - no timeout on waiting for bootstrap mailbox register ready.
7802  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
7803  **/
7804 static int
7805 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
7806 {
7807 	uint32_t db_ready;
7808 	unsigned long timeout;
7809 	struct lpfc_register bmbx_reg;
7810 
7811 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
7812 				   * 1000) + jiffies;
7813 
7814 	do {
7815 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
7816 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
7817 		if (!db_ready)
7818 			msleep(2);
7819 
7820 		if (time_after(jiffies, timeout))
7821 			return MBXERR_ERROR;
7822 	} while (!db_ready);
7823 
7824 	return 0;
7825 }
7826 
7827 /**
7828  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
7829  * @phba: Pointer to HBA context object.
7830  * @mboxq: Pointer to mailbox object.
7831  *
7832  * The function posts a mailbox to the port.  The mailbox is expected
7833  * to be comletely filled in and ready for the port to operate on it.
7834  * This routine executes a synchronous completion operation on the
7835  * mailbox by polling for its completion.
7836  *
7837  * The caller must not be holding any locks when calling this routine.
7838  *
7839  * Returns:
7840  *	MBX_SUCCESS - mailbox posted successfully
7841  *	Any of the MBX error values.
7842  **/
7843 static int
7844 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
7845 {
7846 	int rc = MBX_SUCCESS;
7847 	unsigned long iflag;
7848 	uint32_t mcqe_status;
7849 	uint32_t mbx_cmnd;
7850 	struct lpfc_sli *psli = &phba->sli;
7851 	struct lpfc_mqe *mb = &mboxq->u.mqe;
7852 	struct lpfc_bmbx_create *mbox_rgn;
7853 	struct dma_address *dma_address;
7854 
7855 	/*
7856 	 * Only one mailbox can be active to the bootstrap mailbox region
7857 	 * at a time and there is no queueing provided.
7858 	 */
7859 	spin_lock_irqsave(&phba->hbalock, iflag);
7860 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
7861 		spin_unlock_irqrestore(&phba->hbalock, iflag);
7862 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7863 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
7864 				"cannot issue Data: x%x x%x\n",
7865 				mboxq->vport ? mboxq->vport->vpi : 0,
7866 				mboxq->u.mb.mbxCommand,
7867 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7868 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7869 				psli->sli_flag, MBX_POLL);
7870 		return MBXERR_ERROR;
7871 	}
7872 	/* The server grabs the token and owns it until release */
7873 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7874 	phba->sli.mbox_active = mboxq;
7875 	spin_unlock_irqrestore(&phba->hbalock, iflag);
7876 
7877 	/* wait for bootstrap mbox register for readyness */
7878 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7879 	if (rc)
7880 		goto exit;
7881 
7882 	/*
7883 	 * Initialize the bootstrap memory region to avoid stale data areas
7884 	 * in the mailbox post.  Then copy the caller's mailbox contents to
7885 	 * the bmbx mailbox region.
7886 	 */
7887 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
7888 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
7889 	lpfc_sli_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
7890 			      sizeof(struct lpfc_mqe));
7891 
7892 	/* Post the high mailbox dma address to the port and wait for ready. */
7893 	dma_address = &phba->sli4_hba.bmbx.dma_address;
7894 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
7895 
7896 	/* wait for bootstrap mbox register for hi-address write done */
7897 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7898 	if (rc)
7899 		goto exit;
7900 
7901 	/* Post the low mailbox dma address to the port. */
7902 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
7903 
7904 	/* wait for bootstrap mbox register for low address write done */
7905 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7906 	if (rc)
7907 		goto exit;
7908 
7909 	/*
7910 	 * Read the CQ to ensure the mailbox has completed.
7911 	 * If so, update the mailbox status so that the upper layers
7912 	 * can complete the request normally.
7913 	 */
7914 	lpfc_sli_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
7915 			      sizeof(struct lpfc_mqe));
7916 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
7917 	lpfc_sli_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
7918 			      sizeof(struct lpfc_mcqe));
7919 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
7920 	/*
7921 	 * When the CQE status indicates a failure and the mailbox status
7922 	 * indicates success then copy the CQE status into the mailbox status
7923 	 * (and prefix it with x4000).
7924 	 */
7925 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
7926 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
7927 			bf_set(lpfc_mqe_status, mb,
7928 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
7929 		rc = MBXERR_ERROR;
7930 	} else
7931 		lpfc_sli4_swap_str(phba, mboxq);
7932 
7933 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7934 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
7935 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
7936 			" x%x x%x CQ: x%x x%x x%x x%x\n",
7937 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
7938 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7939 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7940 			bf_get(lpfc_mqe_status, mb),
7941 			mb->un.mb_words[0], mb->un.mb_words[1],
7942 			mb->un.mb_words[2], mb->un.mb_words[3],
7943 			mb->un.mb_words[4], mb->un.mb_words[5],
7944 			mb->un.mb_words[6], mb->un.mb_words[7],
7945 			mb->un.mb_words[8], mb->un.mb_words[9],
7946 			mb->un.mb_words[10], mb->un.mb_words[11],
7947 			mb->un.mb_words[12], mboxq->mcqe.word0,
7948 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
7949 			mboxq->mcqe.trailer);
7950 exit:
7951 	/* We are holding the token, no needed for lock when release */
7952 	spin_lock_irqsave(&phba->hbalock, iflag);
7953 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7954 	phba->sli.mbox_active = NULL;
7955 	spin_unlock_irqrestore(&phba->hbalock, iflag);
7956 	return rc;
7957 }
7958 
7959 /**
7960  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
7961  * @phba: Pointer to HBA context object.
7962  * @pmbox: Pointer to mailbox object.
7963  * @flag: Flag indicating how the mailbox need to be processed.
7964  *
7965  * This function is called by discovery code and HBA management code to submit
7966  * a mailbox command to firmware with SLI-4 interface spec.
7967  *
7968  * Return codes the caller owns the mailbox command after the return of the
7969  * function.
7970  **/
7971 static int
7972 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
7973 		       uint32_t flag)
7974 {
7975 	struct lpfc_sli *psli = &phba->sli;
7976 	unsigned long iflags;
7977 	int rc;
7978 
7979 	/* dump from issue mailbox command if setup */
7980 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
7981 
7982 	rc = lpfc_mbox_dev_check(phba);
7983 	if (unlikely(rc)) {
7984 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7985 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
7986 				"cannot issue Data: x%x x%x\n",
7987 				mboxq->vport ? mboxq->vport->vpi : 0,
7988 				mboxq->u.mb.mbxCommand,
7989 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7990 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7991 				psli->sli_flag, flag);
7992 		goto out_not_finished;
7993 	}
7994 
7995 	/* Detect polling mode and jump to a handler */
7996 	if (!phba->sli4_hba.intr_enable) {
7997 		if (flag == MBX_POLL)
7998 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
7999 		else
8000 			rc = -EIO;
8001 		if (rc != MBX_SUCCESS)
8002 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8003 					"(%d):2541 Mailbox command x%x "
8004 					"(x%x/x%x) failure: "
8005 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
8006 					"Data: x%x x%x\n,",
8007 					mboxq->vport ? mboxq->vport->vpi : 0,
8008 					mboxq->u.mb.mbxCommand,
8009 					lpfc_sli_config_mbox_subsys_get(phba,
8010 									mboxq),
8011 					lpfc_sli_config_mbox_opcode_get(phba,
8012 									mboxq),
8013 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
8014 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
8015 					bf_get(lpfc_mcqe_ext_status,
8016 					       &mboxq->mcqe),
8017 					psli->sli_flag, flag);
8018 		return rc;
8019 	} else if (flag == MBX_POLL) {
8020 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8021 				"(%d):2542 Try to issue mailbox command "
8022 				"x%x (x%x/x%x) synchronously ahead of async"
8023 				"mailbox command queue: x%x x%x\n",
8024 				mboxq->vport ? mboxq->vport->vpi : 0,
8025 				mboxq->u.mb.mbxCommand,
8026 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8027 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8028 				psli->sli_flag, flag);
8029 		/* Try to block the asynchronous mailbox posting */
8030 		rc = lpfc_sli4_async_mbox_block(phba);
8031 		if (!rc) {
8032 			/* Successfully blocked, now issue sync mbox cmd */
8033 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
8034 			if (rc != MBX_SUCCESS)
8035 				lpfc_printf_log(phba, KERN_WARNING,
8036 					LOG_MBOX | LOG_SLI,
8037 					"(%d):2597 Sync Mailbox command "
8038 					"x%x (x%x/x%x) failure: "
8039 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
8040 					"Data: x%x x%x\n,",
8041 					mboxq->vport ? mboxq->vport->vpi : 0,
8042 					mboxq->u.mb.mbxCommand,
8043 					lpfc_sli_config_mbox_subsys_get(phba,
8044 									mboxq),
8045 					lpfc_sli_config_mbox_opcode_get(phba,
8046 									mboxq),
8047 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
8048 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
8049 					bf_get(lpfc_mcqe_ext_status,
8050 					       &mboxq->mcqe),
8051 					psli->sli_flag, flag);
8052 			/* Unblock the async mailbox posting afterward */
8053 			lpfc_sli4_async_mbox_unblock(phba);
8054 		}
8055 		return rc;
8056 	}
8057 
8058 	/* Now, interrupt mode asynchrous mailbox command */
8059 	rc = lpfc_mbox_cmd_check(phba, mboxq);
8060 	if (rc) {
8061 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8062 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
8063 				"cannot issue Data: x%x x%x\n",
8064 				mboxq->vport ? mboxq->vport->vpi : 0,
8065 				mboxq->u.mb.mbxCommand,
8066 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8067 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8068 				psli->sli_flag, flag);
8069 		goto out_not_finished;
8070 	}
8071 
8072 	/* Put the mailbox command to the driver internal FIFO */
8073 	psli->slistat.mbox_busy++;
8074 	spin_lock_irqsave(&phba->hbalock, iflags);
8075 	lpfc_mbox_put(phba, mboxq);
8076 	spin_unlock_irqrestore(&phba->hbalock, iflags);
8077 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8078 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
8079 			"x%x (x%x/x%x) x%x x%x x%x\n",
8080 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
8081 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8082 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8083 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8084 			phba->pport->port_state,
8085 			psli->sli_flag, MBX_NOWAIT);
8086 	/* Wake up worker thread to transport mailbox command from head */
8087 	lpfc_worker_wake_up(phba);
8088 
8089 	return MBX_BUSY;
8090 
8091 out_not_finished:
8092 	return MBX_NOT_FINISHED;
8093 }
8094 
8095 /**
8096  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
8097  * @phba: Pointer to HBA context object.
8098  *
8099  * This function is called by worker thread to send a mailbox command to
8100  * SLI4 HBA firmware.
8101  *
8102  **/
8103 int
8104 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
8105 {
8106 	struct lpfc_sli *psli = &phba->sli;
8107 	LPFC_MBOXQ_t *mboxq;
8108 	int rc = MBX_SUCCESS;
8109 	unsigned long iflags;
8110 	struct lpfc_mqe *mqe;
8111 	uint32_t mbx_cmnd;
8112 
8113 	/* Check interrupt mode before post async mailbox command */
8114 	if (unlikely(!phba->sli4_hba.intr_enable))
8115 		return MBX_NOT_FINISHED;
8116 
8117 	/* Check for mailbox command service token */
8118 	spin_lock_irqsave(&phba->hbalock, iflags);
8119 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8120 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8121 		return MBX_NOT_FINISHED;
8122 	}
8123 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8124 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8125 		return MBX_NOT_FINISHED;
8126 	}
8127 	if (unlikely(phba->sli.mbox_active)) {
8128 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8129 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8130 				"0384 There is pending active mailbox cmd\n");
8131 		return MBX_NOT_FINISHED;
8132 	}
8133 	/* Take the mailbox command service token */
8134 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8135 
8136 	/* Get the next mailbox command from head of queue */
8137 	mboxq = lpfc_mbox_get(phba);
8138 
8139 	/* If no more mailbox command waiting for post, we're done */
8140 	if (!mboxq) {
8141 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8142 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8143 		return MBX_SUCCESS;
8144 	}
8145 	phba->sli.mbox_active = mboxq;
8146 	spin_unlock_irqrestore(&phba->hbalock, iflags);
8147 
8148 	/* Check device readiness for posting mailbox command */
8149 	rc = lpfc_mbox_dev_check(phba);
8150 	if (unlikely(rc))
8151 		/* Driver clean routine will clean up pending mailbox */
8152 		goto out_not_finished;
8153 
8154 	/* Prepare the mbox command to be posted */
8155 	mqe = &mboxq->u.mqe;
8156 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
8157 
8158 	/* Start timer for the mbox_tmo and log some mailbox post messages */
8159 	mod_timer(&psli->mbox_tmo, (jiffies +
8160 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
8161 
8162 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8163 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
8164 			"x%x x%x\n",
8165 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
8166 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8167 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8168 			phba->pport->port_state, psli->sli_flag);
8169 
8170 	if (mbx_cmnd != MBX_HEARTBEAT) {
8171 		if (mboxq->vport) {
8172 			lpfc_debugfs_disc_trc(mboxq->vport,
8173 				LPFC_DISC_TRC_MBOX_VPORT,
8174 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
8175 				mbx_cmnd, mqe->un.mb_words[0],
8176 				mqe->un.mb_words[1]);
8177 		} else {
8178 			lpfc_debugfs_disc_trc(phba->pport,
8179 				LPFC_DISC_TRC_MBOX,
8180 				"MBOX Send: cmd:x%x mb:x%x x%x",
8181 				mbx_cmnd, mqe->un.mb_words[0],
8182 				mqe->un.mb_words[1]);
8183 		}
8184 	}
8185 	psli->slistat.mbox_cmd++;
8186 
8187 	/* Post the mailbox command to the port */
8188 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
8189 	if (rc != MBX_SUCCESS) {
8190 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8191 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
8192 				"cannot issue Data: x%x x%x\n",
8193 				mboxq->vport ? mboxq->vport->vpi : 0,
8194 				mboxq->u.mb.mbxCommand,
8195 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8196 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8197 				psli->sli_flag, MBX_NOWAIT);
8198 		goto out_not_finished;
8199 	}
8200 
8201 	return rc;
8202 
8203 out_not_finished:
8204 	spin_lock_irqsave(&phba->hbalock, iflags);
8205 	if (phba->sli.mbox_active) {
8206 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
8207 		__lpfc_mbox_cmpl_put(phba, mboxq);
8208 		/* Release the token */
8209 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8210 		phba->sli.mbox_active = NULL;
8211 	}
8212 	spin_unlock_irqrestore(&phba->hbalock, iflags);
8213 
8214 	return MBX_NOT_FINISHED;
8215 }
8216 
8217 /**
8218  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
8219  * @phba: Pointer to HBA context object.
8220  * @pmbox: Pointer to mailbox object.
8221  * @flag: Flag indicating how the mailbox need to be processed.
8222  *
8223  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
8224  * the API jump table function pointer from the lpfc_hba struct.
8225  *
8226  * Return codes the caller owns the mailbox command after the return of the
8227  * function.
8228  **/
8229 int
8230 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
8231 {
8232 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
8233 }
8234 
8235 /**
8236  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
8237  * @phba: The hba struct for which this call is being executed.
8238  * @dev_grp: The HBA PCI-Device group number.
8239  *
8240  * This routine sets up the mbox interface API function jump table in @phba
8241  * struct.
8242  * Returns: 0 - success, -ENODEV - failure.
8243  **/
8244 int
8245 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8246 {
8247 
8248 	switch (dev_grp) {
8249 	case LPFC_PCI_DEV_LP:
8250 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
8251 		phba->lpfc_sli_handle_slow_ring_event =
8252 				lpfc_sli_handle_slow_ring_event_s3;
8253 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
8254 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
8255 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
8256 		break;
8257 	case LPFC_PCI_DEV_OC:
8258 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
8259 		phba->lpfc_sli_handle_slow_ring_event =
8260 				lpfc_sli_handle_slow_ring_event_s4;
8261 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
8262 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
8263 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
8264 		break;
8265 	default:
8266 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8267 				"1420 Invalid HBA PCI-device group: 0x%x\n",
8268 				dev_grp);
8269 		return -ENODEV;
8270 		break;
8271 	}
8272 	return 0;
8273 }
8274 
8275 /**
8276  * __lpfc_sli_ringtx_put - Add an iocb to the txq
8277  * @phba: Pointer to HBA context object.
8278  * @pring: Pointer to driver SLI ring object.
8279  * @piocb: Pointer to address of newly added command iocb.
8280  *
8281  * This function is called with hbalock held to add a command
8282  * iocb to the txq when SLI layer cannot submit the command iocb
8283  * to the ring.
8284  **/
8285 void
8286 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
8287 		    struct lpfc_iocbq *piocb)
8288 {
8289 	lockdep_assert_held(&phba->hbalock);
8290 	/* Insert the caller's iocb in the txq tail for later processing. */
8291 	list_add_tail(&piocb->list, &pring->txq);
8292 }
8293 
8294 /**
8295  * lpfc_sli_next_iocb - Get the next iocb in the txq
8296  * @phba: Pointer to HBA context object.
8297  * @pring: Pointer to driver SLI ring object.
8298  * @piocb: Pointer to address of newly added command iocb.
8299  *
8300  * This function is called with hbalock held before a new
8301  * iocb is submitted to the firmware. This function checks
8302  * txq to flush the iocbs in txq to Firmware before
8303  * submitting new iocbs to the Firmware.
8304  * If there are iocbs in the txq which need to be submitted
8305  * to firmware, lpfc_sli_next_iocb returns the first element
8306  * of the txq after dequeuing it from txq.
8307  * If there is no iocb in the txq then the function will return
8308  * *piocb and *piocb is set to NULL. Caller needs to check
8309  * *piocb to find if there are more commands in the txq.
8310  **/
8311 static struct lpfc_iocbq *
8312 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
8313 		   struct lpfc_iocbq **piocb)
8314 {
8315 	struct lpfc_iocbq * nextiocb;
8316 
8317 	lockdep_assert_held(&phba->hbalock);
8318 
8319 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
8320 	if (!nextiocb) {
8321 		nextiocb = *piocb;
8322 		*piocb = NULL;
8323 	}
8324 
8325 	return nextiocb;
8326 }
8327 
8328 /**
8329  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
8330  * @phba: Pointer to HBA context object.
8331  * @ring_number: SLI ring number to issue iocb on.
8332  * @piocb: Pointer to command iocb.
8333  * @flag: Flag indicating if this command can be put into txq.
8334  *
8335  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
8336  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
8337  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
8338  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
8339  * this function allows only iocbs for posting buffers. This function finds
8340  * next available slot in the command ring and posts the command to the
8341  * available slot and writes the port attention register to request HBA start
8342  * processing new iocb. If there is no slot available in the ring and
8343  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
8344  * the function returns IOCB_BUSY.
8345  *
8346  * This function is called with hbalock held. The function will return success
8347  * after it successfully submit the iocb to firmware or after adding to the
8348  * txq.
8349  **/
8350 static int
8351 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
8352 		    struct lpfc_iocbq *piocb, uint32_t flag)
8353 {
8354 	struct lpfc_iocbq *nextiocb;
8355 	IOCB_t *iocb;
8356 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
8357 
8358 	lockdep_assert_held(&phba->hbalock);
8359 
8360 	if (piocb->iocb_cmpl && (!piocb->vport) &&
8361 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
8362 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
8363 		lpfc_printf_log(phba, KERN_ERR,
8364 				LOG_SLI | LOG_VPORT,
8365 				"1807 IOCB x%x failed. No vport\n",
8366 				piocb->iocb.ulpCommand);
8367 		dump_stack();
8368 		return IOCB_ERROR;
8369 	}
8370 
8371 
8372 	/* If the PCI channel is in offline state, do not post iocbs. */
8373 	if (unlikely(pci_channel_offline(phba->pcidev)))
8374 		return IOCB_ERROR;
8375 
8376 	/* If HBA has a deferred error attention, fail the iocb. */
8377 	if (unlikely(phba->hba_flag & DEFER_ERATT))
8378 		return IOCB_ERROR;
8379 
8380 	/*
8381 	 * We should never get an IOCB if we are in a < LINK_DOWN state
8382 	 */
8383 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
8384 		return IOCB_ERROR;
8385 
8386 	/*
8387 	 * Check to see if we are blocking IOCB processing because of a
8388 	 * outstanding event.
8389 	 */
8390 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
8391 		goto iocb_busy;
8392 
8393 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
8394 		/*
8395 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
8396 		 * can be issued if the link is not up.
8397 		 */
8398 		switch (piocb->iocb.ulpCommand) {
8399 		case CMD_GEN_REQUEST64_CR:
8400 		case CMD_GEN_REQUEST64_CX:
8401 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
8402 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
8403 					FC_RCTL_DD_UNSOL_CMD) ||
8404 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
8405 					MENLO_TRANSPORT_TYPE))
8406 
8407 				goto iocb_busy;
8408 			break;
8409 		case CMD_QUE_RING_BUF_CN:
8410 		case CMD_QUE_RING_BUF64_CN:
8411 			/*
8412 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
8413 			 * completion, iocb_cmpl MUST be 0.
8414 			 */
8415 			if (piocb->iocb_cmpl)
8416 				piocb->iocb_cmpl = NULL;
8417 			/*FALLTHROUGH*/
8418 		case CMD_CREATE_XRI_CR:
8419 		case CMD_CLOSE_XRI_CN:
8420 		case CMD_CLOSE_XRI_CX:
8421 			break;
8422 		default:
8423 			goto iocb_busy;
8424 		}
8425 
8426 	/*
8427 	 * For FCP commands, we must be in a state where we can process link
8428 	 * attention events.
8429 	 */
8430 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
8431 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
8432 		goto iocb_busy;
8433 	}
8434 
8435 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
8436 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
8437 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
8438 
8439 	if (iocb)
8440 		lpfc_sli_update_ring(phba, pring);
8441 	else
8442 		lpfc_sli_update_full_ring(phba, pring);
8443 
8444 	if (!piocb)
8445 		return IOCB_SUCCESS;
8446 
8447 	goto out_busy;
8448 
8449  iocb_busy:
8450 	pring->stats.iocb_cmd_delay++;
8451 
8452  out_busy:
8453 
8454 	if (!(flag & SLI_IOCB_RET_IOCB)) {
8455 		__lpfc_sli_ringtx_put(phba, pring, piocb);
8456 		return IOCB_SUCCESS;
8457 	}
8458 
8459 	return IOCB_BUSY;
8460 }
8461 
8462 /**
8463  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
8464  * @phba: Pointer to HBA context object.
8465  * @piocb: Pointer to command iocb.
8466  * @sglq: Pointer to the scatter gather queue object.
8467  *
8468  * This routine converts the bpl or bde that is in the IOCB
8469  * to a sgl list for the sli4 hardware. The physical address
8470  * of the bpl/bde is converted back to a virtual address.
8471  * If the IOCB contains a BPL then the list of BDE's is
8472  * converted to sli4_sge's. If the IOCB contains a single
8473  * BDE then it is converted to a single sli_sge.
8474  * The IOCB is still in cpu endianess so the contents of
8475  * the bpl can be used without byte swapping.
8476  *
8477  * Returns valid XRI = Success, NO_XRI = Failure.
8478 **/
8479 static uint16_t
8480 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
8481 		struct lpfc_sglq *sglq)
8482 {
8483 	uint16_t xritag = NO_XRI;
8484 	struct ulp_bde64 *bpl = NULL;
8485 	struct ulp_bde64 bde;
8486 	struct sli4_sge *sgl  = NULL;
8487 	struct lpfc_dmabuf *dmabuf;
8488 	IOCB_t *icmd;
8489 	int numBdes = 0;
8490 	int i = 0;
8491 	uint32_t offset = 0; /* accumulated offset in the sg request list */
8492 	int inbound = 0; /* number of sg reply entries inbound from firmware */
8493 
8494 	if (!piocbq || !sglq)
8495 		return xritag;
8496 
8497 	sgl  = (struct sli4_sge *)sglq->sgl;
8498 	icmd = &piocbq->iocb;
8499 	if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
8500 		return sglq->sli4_xritag;
8501 	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
8502 		numBdes = icmd->un.genreq64.bdl.bdeSize /
8503 				sizeof(struct ulp_bde64);
8504 		/* The addrHigh and addrLow fields within the IOCB
8505 		 * have not been byteswapped yet so there is no
8506 		 * need to swap them back.
8507 		 */
8508 		if (piocbq->context3)
8509 			dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
8510 		else
8511 			return xritag;
8512 
8513 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
8514 		if (!bpl)
8515 			return xritag;
8516 
8517 		for (i = 0; i < numBdes; i++) {
8518 			/* Should already be byte swapped. */
8519 			sgl->addr_hi = bpl->addrHigh;
8520 			sgl->addr_lo = bpl->addrLow;
8521 
8522 			sgl->word2 = le32_to_cpu(sgl->word2);
8523 			if ((i+1) == numBdes)
8524 				bf_set(lpfc_sli4_sge_last, sgl, 1);
8525 			else
8526 				bf_set(lpfc_sli4_sge_last, sgl, 0);
8527 			/* swap the size field back to the cpu so we
8528 			 * can assign it to the sgl.
8529 			 */
8530 			bde.tus.w = le32_to_cpu(bpl->tus.w);
8531 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
8532 			/* The offsets in the sgl need to be accumulated
8533 			 * separately for the request and reply lists.
8534 			 * The request is always first, the reply follows.
8535 			 */
8536 			if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
8537 				/* add up the reply sg entries */
8538 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
8539 					inbound++;
8540 				/* first inbound? reset the offset */
8541 				if (inbound == 1)
8542 					offset = 0;
8543 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
8544 				bf_set(lpfc_sli4_sge_type, sgl,
8545 					LPFC_SGE_TYPE_DATA);
8546 				offset += bde.tus.f.bdeSize;
8547 			}
8548 			sgl->word2 = cpu_to_le32(sgl->word2);
8549 			bpl++;
8550 			sgl++;
8551 		}
8552 	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
8553 			/* The addrHigh and addrLow fields of the BDE have not
8554 			 * been byteswapped yet so they need to be swapped
8555 			 * before putting them in the sgl.
8556 			 */
8557 			sgl->addr_hi =
8558 				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
8559 			sgl->addr_lo =
8560 				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
8561 			sgl->word2 = le32_to_cpu(sgl->word2);
8562 			bf_set(lpfc_sli4_sge_last, sgl, 1);
8563 			sgl->word2 = cpu_to_le32(sgl->word2);
8564 			sgl->sge_len =
8565 				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
8566 	}
8567 	return sglq->sli4_xritag;
8568 }
8569 
8570 /**
8571  * lpfc_sli_iocb2wqe - Convert the IOCB to a work queue entry.
8572  * @phba: Pointer to HBA context object.
8573  * @piocb: Pointer to command iocb.
8574  * @wqe: Pointer to the work queue entry.
8575  *
8576  * This routine converts the iocb command to its Work Queue Entry
8577  * equivalent. The wqe pointer should not have any fields set when
8578  * this routine is called because it will memcpy over them.
8579  * This routine does not set the CQ_ID or the WQEC bits in the
8580  * wqe.
8581  *
8582  * Returns: 0 = Success, IOCB_ERROR = Failure.
8583  **/
8584 static int
8585 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
8586 		union lpfc_wqe *wqe)
8587 {
8588 	uint32_t xmit_len = 0, total_len = 0;
8589 	uint8_t ct = 0;
8590 	uint32_t fip;
8591 	uint32_t abort_tag;
8592 	uint8_t command_type = ELS_COMMAND_NON_FIP;
8593 	uint8_t cmnd;
8594 	uint16_t xritag;
8595 	uint16_t abrt_iotag;
8596 	struct lpfc_iocbq *abrtiocbq;
8597 	struct ulp_bde64 *bpl = NULL;
8598 	uint32_t els_id = LPFC_ELS_ID_DEFAULT;
8599 	int numBdes, i;
8600 	struct ulp_bde64 bde;
8601 	struct lpfc_nodelist *ndlp;
8602 	uint32_t *pcmd;
8603 	uint32_t if_type;
8604 
8605 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
8606 	/* The fcp commands will set command type */
8607 	if (iocbq->iocb_flag &  LPFC_IO_FCP)
8608 		command_type = FCP_COMMAND;
8609 	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
8610 		command_type = ELS_COMMAND_FIP;
8611 	else
8612 		command_type = ELS_COMMAND_NON_FIP;
8613 
8614 	if (phba->fcp_embed_io)
8615 		memset(wqe, 0, sizeof(union lpfc_wqe128));
8616 	/* Some of the fields are in the right position already */
8617 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
8618 	wqe->generic.wqe_com.word7 = 0; /* The ct field has moved so reset */
8619 	wqe->generic.wqe_com.word10 = 0;
8620 
8621 	abort_tag = (uint32_t) iocbq->iotag;
8622 	xritag = iocbq->sli4_xritag;
8623 	/* words0-2 bpl convert bde */
8624 	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
8625 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
8626 				sizeof(struct ulp_bde64);
8627 		bpl  = (struct ulp_bde64 *)
8628 			((struct lpfc_dmabuf *)iocbq->context3)->virt;
8629 		if (!bpl)
8630 			return IOCB_ERROR;
8631 
8632 		/* Should already be byte swapped. */
8633 		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
8634 		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
8635 		/* swap the size field back to the cpu so we
8636 		 * can assign it to the sgl.
8637 		 */
8638 		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
8639 		xmit_len = wqe->generic.bde.tus.f.bdeSize;
8640 		total_len = 0;
8641 		for (i = 0; i < numBdes; i++) {
8642 			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
8643 			total_len += bde.tus.f.bdeSize;
8644 		}
8645 	} else
8646 		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
8647 
8648 	iocbq->iocb.ulpIoTag = iocbq->iotag;
8649 	cmnd = iocbq->iocb.ulpCommand;
8650 
8651 	switch (iocbq->iocb.ulpCommand) {
8652 	case CMD_ELS_REQUEST64_CR:
8653 		if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
8654 			ndlp = iocbq->context_un.ndlp;
8655 		else
8656 			ndlp = (struct lpfc_nodelist *)iocbq->context1;
8657 		if (!iocbq->iocb.ulpLe) {
8658 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8659 				"2007 Only Limited Edition cmd Format"
8660 				" supported 0x%x\n",
8661 				iocbq->iocb.ulpCommand);
8662 			return IOCB_ERROR;
8663 		}
8664 
8665 		wqe->els_req.payload_len = xmit_len;
8666 		/* Els_reguest64 has a TMO */
8667 		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
8668 			iocbq->iocb.ulpTimeout);
8669 		/* Need a VF for word 4 set the vf bit*/
8670 		bf_set(els_req64_vf, &wqe->els_req, 0);
8671 		/* And a VFID for word 12 */
8672 		bf_set(els_req64_vfid, &wqe->els_req, 0);
8673 		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
8674 		bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8675 		       iocbq->iocb.ulpContext);
8676 		bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
8677 		bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
8678 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
8679 		if (command_type == ELS_COMMAND_FIP)
8680 			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
8681 					>> LPFC_FIP_ELS_ID_SHIFT);
8682 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
8683 					iocbq->context2)->virt);
8684 		if_type = bf_get(lpfc_sli_intf_if_type,
8685 					&phba->sli4_hba.sli_intf);
8686 		if (if_type == LPFC_SLI_INTF_IF_TYPE_2) {
8687 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
8688 				*pcmd == ELS_CMD_SCR ||
8689 				*pcmd == ELS_CMD_FDISC ||
8690 				*pcmd == ELS_CMD_LOGO ||
8691 				*pcmd == ELS_CMD_PLOGI)) {
8692 				bf_set(els_req64_sp, &wqe->els_req, 1);
8693 				bf_set(els_req64_sid, &wqe->els_req,
8694 					iocbq->vport->fc_myDID);
8695 				if ((*pcmd == ELS_CMD_FLOGI) &&
8696 					!(phba->fc_topology ==
8697 						LPFC_TOPOLOGY_LOOP))
8698 					bf_set(els_req64_sid, &wqe->els_req, 0);
8699 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
8700 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8701 					phba->vpi_ids[iocbq->vport->vpi]);
8702 			} else if (pcmd && iocbq->context1) {
8703 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
8704 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8705 					phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8706 			}
8707 		}
8708 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
8709 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8710 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
8711 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
8712 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
8713 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
8714 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
8715 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
8716 		wqe->els_req.max_response_payload_len = total_len - xmit_len;
8717 		break;
8718 	case CMD_XMIT_SEQUENCE64_CX:
8719 		bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
8720 		       iocbq->iocb.un.ulpWord[3]);
8721 		bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
8722 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
8723 		/* The entire sequence is transmitted for this IOCB */
8724 		xmit_len = total_len;
8725 		cmnd = CMD_XMIT_SEQUENCE64_CR;
8726 		if (phba->link_flag & LS_LOOPBACK_MODE)
8727 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
8728 	case CMD_XMIT_SEQUENCE64_CR:
8729 		/* word3 iocb=io_tag32 wqe=reserved */
8730 		wqe->xmit_sequence.rsvd3 = 0;
8731 		/* word4 relative_offset memcpy */
8732 		/* word5 r_ctl/df_ctl memcpy */
8733 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
8734 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
8735 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
8736 		       LPFC_WQE_IOD_WRITE);
8737 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
8738 		       LPFC_WQE_LENLOC_WORD12);
8739 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
8740 		wqe->xmit_sequence.xmit_len = xmit_len;
8741 		command_type = OTHER_COMMAND;
8742 		break;
8743 	case CMD_XMIT_BCAST64_CN:
8744 		/* word3 iocb=iotag32 wqe=seq_payload_len */
8745 		wqe->xmit_bcast64.seq_payload_len = xmit_len;
8746 		/* word4 iocb=rsvd wqe=rsvd */
8747 		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
8748 		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
8749 		bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
8750 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8751 		bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
8752 		bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
8753 		bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
8754 		       LPFC_WQE_LENLOC_WORD3);
8755 		bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
8756 		break;
8757 	case CMD_FCP_IWRITE64_CR:
8758 		command_type = FCP_COMMAND_DATA_OUT;
8759 		/* word3 iocb=iotag wqe=payload_offset_len */
8760 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8761 		bf_set(payload_offset_len, &wqe->fcp_iwrite,
8762 		       xmit_len + sizeof(struct fcp_rsp));
8763 		bf_set(cmd_buff_len, &wqe->fcp_iwrite,
8764 		       0);
8765 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
8766 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
8767 		bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
8768 		       iocbq->iocb.ulpFCP2Rcvy);
8769 		bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
8770 		/* Always open the exchange */
8771 		bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
8772 		bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
8773 		       LPFC_WQE_LENLOC_WORD4);
8774 		bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
8775 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
8776 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8777 			bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
8778 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
8779 			if (iocbq->priority) {
8780 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
8781 				       (iocbq->priority << 1));
8782 			} else {
8783 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
8784 				       (phba->cfg_XLanePriority << 1));
8785 			}
8786 		}
8787 		/* Note, word 10 is already initialized to 0 */
8788 
8789 		if (phba->fcp_embed_io) {
8790 			struct lpfc_scsi_buf *lpfc_cmd;
8791 			struct sli4_sge *sgl;
8792 			union lpfc_wqe128 *wqe128;
8793 			struct fcp_cmnd *fcp_cmnd;
8794 			uint32_t *ptr;
8795 
8796 			/* 128 byte wqe support here */
8797 			wqe128 = (union lpfc_wqe128 *)wqe;
8798 
8799 			lpfc_cmd = iocbq->context1;
8800 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
8801 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
8802 
8803 			/* Word 0-2 - FCP_CMND */
8804 			wqe128->generic.bde.tus.f.bdeFlags =
8805 				BUFF_TYPE_BDE_IMMED;
8806 			wqe128->generic.bde.tus.f.bdeSize = sgl->sge_len;
8807 			wqe128->generic.bde.addrHigh = 0;
8808 			wqe128->generic.bde.addrLow =  88;  /* Word 22 */
8809 
8810 			bf_set(wqe_wqes, &wqe128->fcp_iwrite.wqe_com, 1);
8811 
8812 			/* Word 22-29  FCP CMND Payload */
8813 			ptr = &wqe128->words[22];
8814 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
8815 		}
8816 		break;
8817 	case CMD_FCP_IREAD64_CR:
8818 		/* word3 iocb=iotag wqe=payload_offset_len */
8819 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8820 		bf_set(payload_offset_len, &wqe->fcp_iread,
8821 		       xmit_len + sizeof(struct fcp_rsp));
8822 		bf_set(cmd_buff_len, &wqe->fcp_iread,
8823 		       0);
8824 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
8825 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
8826 		bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
8827 		       iocbq->iocb.ulpFCP2Rcvy);
8828 		bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
8829 		/* Always open the exchange */
8830 		bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
8831 		bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
8832 		       LPFC_WQE_LENLOC_WORD4);
8833 		bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
8834 		bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
8835 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8836 			bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
8837 			bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
8838 			if (iocbq->priority) {
8839 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
8840 				       (iocbq->priority << 1));
8841 			} else {
8842 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
8843 				       (phba->cfg_XLanePriority << 1));
8844 			}
8845 		}
8846 		/* Note, word 10 is already initialized to 0 */
8847 
8848 		if (phba->fcp_embed_io) {
8849 			struct lpfc_scsi_buf *lpfc_cmd;
8850 			struct sli4_sge *sgl;
8851 			union lpfc_wqe128 *wqe128;
8852 			struct fcp_cmnd *fcp_cmnd;
8853 			uint32_t *ptr;
8854 
8855 			/* 128 byte wqe support here */
8856 			wqe128 = (union lpfc_wqe128 *)wqe;
8857 
8858 			lpfc_cmd = iocbq->context1;
8859 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
8860 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
8861 
8862 			/* Word 0-2 - FCP_CMND */
8863 			wqe128->generic.bde.tus.f.bdeFlags =
8864 				BUFF_TYPE_BDE_IMMED;
8865 			wqe128->generic.bde.tus.f.bdeSize = sgl->sge_len;
8866 			wqe128->generic.bde.addrHigh = 0;
8867 			wqe128->generic.bde.addrLow =  88;  /* Word 22 */
8868 
8869 			bf_set(wqe_wqes, &wqe128->fcp_iread.wqe_com, 1);
8870 
8871 			/* Word 22-29  FCP CMND Payload */
8872 			ptr = &wqe128->words[22];
8873 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
8874 		}
8875 		break;
8876 	case CMD_FCP_ICMND64_CR:
8877 		/* word3 iocb=iotag wqe=payload_offset_len */
8878 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8879 		bf_set(payload_offset_len, &wqe->fcp_icmd,
8880 		       xmit_len + sizeof(struct fcp_rsp));
8881 		bf_set(cmd_buff_len, &wqe->fcp_icmd,
8882 		       0);
8883 		/* word3 iocb=IO_TAG wqe=reserved */
8884 		bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
8885 		/* Always open the exchange */
8886 		bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
8887 		bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
8888 		bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
8889 		bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
8890 		       LPFC_WQE_LENLOC_NONE);
8891 		bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
8892 		       iocbq->iocb.ulpFCP2Rcvy);
8893 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8894 			bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
8895 			bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
8896 			if (iocbq->priority) {
8897 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
8898 				       (iocbq->priority << 1));
8899 			} else {
8900 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
8901 				       (phba->cfg_XLanePriority << 1));
8902 			}
8903 		}
8904 		/* Note, word 10 is already initialized to 0 */
8905 
8906 		if (phba->fcp_embed_io) {
8907 			struct lpfc_scsi_buf *lpfc_cmd;
8908 			struct sli4_sge *sgl;
8909 			union lpfc_wqe128 *wqe128;
8910 			struct fcp_cmnd *fcp_cmnd;
8911 			uint32_t *ptr;
8912 
8913 			/* 128 byte wqe support here */
8914 			wqe128 = (union lpfc_wqe128 *)wqe;
8915 
8916 			lpfc_cmd = iocbq->context1;
8917 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
8918 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
8919 
8920 			/* Word 0-2 - FCP_CMND */
8921 			wqe128->generic.bde.tus.f.bdeFlags =
8922 				BUFF_TYPE_BDE_IMMED;
8923 			wqe128->generic.bde.tus.f.bdeSize = sgl->sge_len;
8924 			wqe128->generic.bde.addrHigh = 0;
8925 			wqe128->generic.bde.addrLow =  88;  /* Word 22 */
8926 
8927 			bf_set(wqe_wqes, &wqe128->fcp_icmd.wqe_com, 1);
8928 
8929 			/* Word 22-29  FCP CMND Payload */
8930 			ptr = &wqe128->words[22];
8931 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
8932 		}
8933 		break;
8934 	case CMD_GEN_REQUEST64_CR:
8935 		/* For this command calculate the xmit length of the
8936 		 * request bde.
8937 		 */
8938 		xmit_len = 0;
8939 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
8940 			sizeof(struct ulp_bde64);
8941 		for (i = 0; i < numBdes; i++) {
8942 			bde.tus.w = le32_to_cpu(bpl[i].tus.w);
8943 			if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
8944 				break;
8945 			xmit_len += bde.tus.f.bdeSize;
8946 		}
8947 		/* word3 iocb=IO_TAG wqe=request_payload_len */
8948 		wqe->gen_req.request_payload_len = xmit_len;
8949 		/* word4 iocb=parameter wqe=relative_offset memcpy */
8950 		/* word5 [rctl, type, df_ctl, la] copied in memcpy */
8951 		/* word6 context tag copied in memcpy */
8952 		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
8953 			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
8954 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8955 				"2015 Invalid CT %x command 0x%x\n",
8956 				ct, iocbq->iocb.ulpCommand);
8957 			return IOCB_ERROR;
8958 		}
8959 		bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
8960 		bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
8961 		bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
8962 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
8963 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
8964 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
8965 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
8966 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
8967 		wqe->gen_req.max_response_payload_len = total_len - xmit_len;
8968 		command_type = OTHER_COMMAND;
8969 		break;
8970 	case CMD_XMIT_ELS_RSP64_CX:
8971 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
8972 		/* words0-2 BDE memcpy */
8973 		/* word3 iocb=iotag32 wqe=response_payload_len */
8974 		wqe->xmit_els_rsp.response_payload_len = xmit_len;
8975 		/* word4 */
8976 		wqe->xmit_els_rsp.word4 = 0;
8977 		/* word5 iocb=rsvd wge=did */
8978 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
8979 			 iocbq->iocb.un.xseq64.xmit_els_remoteID);
8980 
8981 		if_type = bf_get(lpfc_sli_intf_if_type,
8982 					&phba->sli4_hba.sli_intf);
8983 		if (if_type == LPFC_SLI_INTF_IF_TYPE_2) {
8984 			if (iocbq->vport->fc_flag & FC_PT2PT) {
8985 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
8986 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
8987 					iocbq->vport->fc_myDID);
8988 				if (iocbq->vport->fc_myDID == Fabric_DID) {
8989 					bf_set(wqe_els_did,
8990 						&wqe->xmit_els_rsp.wqe_dest, 0);
8991 				}
8992 			}
8993 		}
8994 		bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
8995 		       ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8996 		bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
8997 		bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
8998 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
8999 		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
9000 			bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
9001 			       phba->vpi_ids[iocbq->vport->vpi]);
9002 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
9003 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
9004 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
9005 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
9006 		       LPFC_WQE_LENLOC_WORD3);
9007 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
9008 		bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
9009 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9010 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9011 					iocbq->context2)->virt);
9012 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
9013 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
9014 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
9015 					iocbq->vport->fc_myDID);
9016 				bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
9017 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
9018 					phba->vpi_ids[phba->pport->vpi]);
9019 		}
9020 		command_type = OTHER_COMMAND;
9021 		break;
9022 	case CMD_CLOSE_XRI_CN:
9023 	case CMD_ABORT_XRI_CN:
9024 	case CMD_ABORT_XRI_CX:
9025 		/* words 0-2 memcpy should be 0 rserved */
9026 		/* port will send abts */
9027 		abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
9028 		if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
9029 			abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
9030 			fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
9031 		} else
9032 			fip = 0;
9033 
9034 		if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
9035 			/*
9036 			 * The link is down, or the command was ELS_FIP
9037 			 * so the fw does not need to send abts
9038 			 * on the wire.
9039 			 */
9040 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
9041 		else
9042 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
9043 		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
9044 		/* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
9045 		wqe->abort_cmd.rsrvd5 = 0;
9046 		bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
9047 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9048 		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
9049 		/*
9050 		 * The abort handler will send us CMD_ABORT_XRI_CN or
9051 		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
9052 		 */
9053 		bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
9054 		bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
9055 		bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
9056 		       LPFC_WQE_LENLOC_NONE);
9057 		cmnd = CMD_ABORT_XRI_CX;
9058 		command_type = OTHER_COMMAND;
9059 		xritag = 0;
9060 		break;
9061 	case CMD_XMIT_BLS_RSP64_CX:
9062 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
9063 		/* As BLS ABTS RSP WQE is very different from other WQEs,
9064 		 * we re-construct this WQE here based on information in
9065 		 * iocbq from scratch.
9066 		 */
9067 		memset(wqe, 0, sizeof(union lpfc_wqe));
9068 		/* OX_ID is invariable to who sent ABTS to CT exchange */
9069 		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
9070 		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
9071 		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
9072 		    LPFC_ABTS_UNSOL_INT) {
9073 			/* ABTS sent by initiator to CT exchange, the
9074 			 * RX_ID field will be filled with the newly
9075 			 * allocated responder XRI.
9076 			 */
9077 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
9078 			       iocbq->sli4_xritag);
9079 		} else {
9080 			/* ABTS sent by responder to CT exchange, the
9081 			 * RX_ID field will be filled with the responder
9082 			 * RX_ID from ABTS.
9083 			 */
9084 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
9085 			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
9086 		}
9087 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
9088 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
9089 
9090 		/* Use CT=VPI */
9091 		bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
9092 			ndlp->nlp_DID);
9093 		bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
9094 			iocbq->iocb.ulpContext);
9095 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
9096 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
9097 			phba->vpi_ids[phba->pport->vpi]);
9098 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
9099 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
9100 		       LPFC_WQE_LENLOC_NONE);
9101 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
9102 		command_type = OTHER_COMMAND;
9103 		if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
9104 			bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
9105 			       bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
9106 			bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
9107 			       bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
9108 			bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
9109 			       bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
9110 		}
9111 
9112 		break;
9113 	case CMD_XRI_ABORTED_CX:
9114 	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
9115 	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
9116 	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
9117 	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
9118 	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
9119 	default:
9120 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9121 				"2014 Invalid command 0x%x\n",
9122 				iocbq->iocb.ulpCommand);
9123 		return IOCB_ERROR;
9124 		break;
9125 	}
9126 
9127 	if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
9128 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
9129 	else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
9130 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
9131 	else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
9132 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
9133 	iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
9134 			      LPFC_IO_DIF_INSERT);
9135 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
9136 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
9137 	wqe->generic.wqe_com.abort_tag = abort_tag;
9138 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
9139 	bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
9140 	bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
9141 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
9142 	return 0;
9143 }
9144 
9145 /**
9146  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
9147  * @phba: Pointer to HBA context object.
9148  * @ring_number: SLI ring number to issue iocb on.
9149  * @piocb: Pointer to command iocb.
9150  * @flag: Flag indicating if this command can be put into txq.
9151  *
9152  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
9153  * an iocb command to an HBA with SLI-4 interface spec.
9154  *
9155  * This function is called with hbalock held. The function will return success
9156  * after it successfully submit the iocb to firmware or after adding to the
9157  * txq.
9158  **/
9159 static int
9160 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
9161 			 struct lpfc_iocbq *piocb, uint32_t flag)
9162 {
9163 	struct lpfc_sglq *sglq;
9164 	union lpfc_wqe *wqe;
9165 	union lpfc_wqe128 wqe128;
9166 	struct lpfc_queue *wq;
9167 	struct lpfc_sli_ring *pring;
9168 
9169 	/* Get the WQ */
9170 	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
9171 	    (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
9172 		if (!phba->cfg_fof || (!(piocb->iocb_flag & LPFC_IO_OAS)))
9173 			wq = phba->sli4_hba.fcp_wq[piocb->hba_wqidx];
9174 		else
9175 			wq = phba->sli4_hba.oas_wq;
9176 	} else {
9177 		wq = phba->sli4_hba.els_wq;
9178 	}
9179 
9180 	/* Get corresponding ring */
9181 	pring = wq->pring;
9182 
9183 	/*
9184 	 * The WQE can be either 64 or 128 bytes,
9185 	 * so allocate space on the stack assuming the largest.
9186 	 */
9187 	wqe = (union lpfc_wqe *)&wqe128;
9188 
9189 	lockdep_assert_held(&phba->hbalock);
9190 
9191 	if (piocb->sli4_xritag == NO_XRI) {
9192 		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
9193 		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
9194 			sglq = NULL;
9195 		else {
9196 			if (!list_empty(&pring->txq)) {
9197 				if (!(flag & SLI_IOCB_RET_IOCB)) {
9198 					__lpfc_sli_ringtx_put(phba,
9199 						pring, piocb);
9200 					return IOCB_SUCCESS;
9201 				} else {
9202 					return IOCB_BUSY;
9203 				}
9204 			} else {
9205 				sglq = __lpfc_sli_get_els_sglq(phba, piocb);
9206 				if (!sglq) {
9207 					if (!(flag & SLI_IOCB_RET_IOCB)) {
9208 						__lpfc_sli_ringtx_put(phba,
9209 								pring,
9210 								piocb);
9211 						return IOCB_SUCCESS;
9212 					} else
9213 						return IOCB_BUSY;
9214 				}
9215 			}
9216 		}
9217 	} else if (piocb->iocb_flag &  LPFC_IO_FCP)
9218 		/* These IO's already have an XRI and a mapped sgl. */
9219 		sglq = NULL;
9220 	else {
9221 		/*
9222 		 * This is a continuation of a commandi,(CX) so this
9223 		 * sglq is on the active list
9224 		 */
9225 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
9226 		if (!sglq)
9227 			return IOCB_ERROR;
9228 	}
9229 
9230 	if (sglq) {
9231 		piocb->sli4_lxritag = sglq->sli4_lxritag;
9232 		piocb->sli4_xritag = sglq->sli4_xritag;
9233 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
9234 			return IOCB_ERROR;
9235 	}
9236 
9237 	if (lpfc_sli4_iocb2wqe(phba, piocb, wqe))
9238 		return IOCB_ERROR;
9239 
9240 	if (lpfc_sli4_wq_put(wq, wqe))
9241 		return IOCB_ERROR;
9242 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
9243 
9244 	return 0;
9245 }
9246 
9247 /**
9248  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
9249  *
9250  * This routine wraps the actual lockless version for issusing IOCB function
9251  * pointer from the lpfc_hba struct.
9252  *
9253  * Return codes:
9254  * IOCB_ERROR - Error
9255  * IOCB_SUCCESS - Success
9256  * IOCB_BUSY - Busy
9257  **/
9258 int
9259 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
9260 		struct lpfc_iocbq *piocb, uint32_t flag)
9261 {
9262 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
9263 }
9264 
9265 /**
9266  * lpfc_sli_api_table_setup - Set up sli api function jump table
9267  * @phba: The hba struct for which this call is being executed.
9268  * @dev_grp: The HBA PCI-Device group number.
9269  *
9270  * This routine sets up the SLI interface API function jump table in @phba
9271  * struct.
9272  * Returns: 0 - success, -ENODEV - failure.
9273  **/
9274 int
9275 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
9276 {
9277 
9278 	switch (dev_grp) {
9279 	case LPFC_PCI_DEV_LP:
9280 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
9281 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
9282 		break;
9283 	case LPFC_PCI_DEV_OC:
9284 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
9285 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
9286 		break;
9287 	default:
9288 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9289 				"1419 Invalid HBA PCI-device group: 0x%x\n",
9290 				dev_grp);
9291 		return -ENODEV;
9292 		break;
9293 	}
9294 	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
9295 	return 0;
9296 }
9297 
9298 /**
9299  * lpfc_sli4_calc_ring - Calculates which ring to use
9300  * @phba: Pointer to HBA context object.
9301  * @piocb: Pointer to command iocb.
9302  *
9303  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
9304  * hba_wqidx, thus we need to calculate the corresponding ring.
9305  * Since ABORTS must go on the same WQ of the command they are
9306  * aborting, we use command's hba_wqidx.
9307  */
9308 struct lpfc_sli_ring *
9309 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
9310 {
9311 	if (piocb->iocb_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
9312 		if (!(phba->cfg_fof) ||
9313 		    (!(piocb->iocb_flag & LPFC_IO_FOF))) {
9314 			if (unlikely(!phba->sli4_hba.fcp_wq))
9315 				return NULL;
9316 			/*
9317 			 * for abort iocb hba_wqidx should already
9318 			 * be setup based on what work queue we used.
9319 			 */
9320 			if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX))
9321 				piocb->hba_wqidx =
9322 					lpfc_sli4_scmd_to_wqidx_distr(phba,
9323 							      piocb->context1);
9324 			return phba->sli4_hba.fcp_wq[piocb->hba_wqidx]->pring;
9325 		} else {
9326 			if (unlikely(!phba->sli4_hba.oas_wq))
9327 				return NULL;
9328 			piocb->hba_wqidx = 0;
9329 			return phba->sli4_hba.oas_wq->pring;
9330 		}
9331 	} else {
9332 		if (unlikely(!phba->sli4_hba.els_wq))
9333 			return NULL;
9334 		piocb->hba_wqidx = 0;
9335 		return phba->sli4_hba.els_wq->pring;
9336 	}
9337 }
9338 
9339 /**
9340  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
9341  * @phba: Pointer to HBA context object.
9342  * @pring: Pointer to driver SLI ring object.
9343  * @piocb: Pointer to command iocb.
9344  * @flag: Flag indicating if this command can be put into txq.
9345  *
9346  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
9347  * function. This function gets the hbalock and calls
9348  * __lpfc_sli_issue_iocb function and will return the error returned
9349  * by __lpfc_sli_issue_iocb function. This wrapper is used by
9350  * functions which do not hold hbalock.
9351  **/
9352 int
9353 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
9354 		    struct lpfc_iocbq *piocb, uint32_t flag)
9355 {
9356 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
9357 	struct lpfc_sli_ring *pring;
9358 	struct lpfc_queue *fpeq;
9359 	struct lpfc_eqe *eqe;
9360 	unsigned long iflags;
9361 	int rc, idx;
9362 
9363 	if (phba->sli_rev == LPFC_SLI_REV4) {
9364 		pring = lpfc_sli4_calc_ring(phba, piocb);
9365 		if (unlikely(pring == NULL))
9366 			return IOCB_ERROR;
9367 
9368 		spin_lock_irqsave(&pring->ring_lock, iflags);
9369 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
9370 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
9371 
9372 		if (lpfc_fcp_look_ahead && (piocb->iocb_flag &  LPFC_IO_FCP)) {
9373 			idx = piocb->hba_wqidx;
9374 			hba_eq_hdl = &phba->sli4_hba.hba_eq_hdl[idx];
9375 
9376 			if (atomic_dec_and_test(&hba_eq_hdl->hba_eq_in_use)) {
9377 
9378 				/* Get associated EQ with this index */
9379 				fpeq = phba->sli4_hba.hba_eq[idx];
9380 
9381 				/* Turn off interrupts from this EQ */
9382 				lpfc_sli4_eq_clr_intr(fpeq);
9383 
9384 				/*
9385 				 * Process all the events on FCP EQ
9386 				 */
9387 				while ((eqe = lpfc_sli4_eq_get(fpeq))) {
9388 					lpfc_sli4_hba_handle_eqe(phba,
9389 						eqe, idx);
9390 					fpeq->EQ_processed++;
9391 				}
9392 
9393 				/* Always clear and re-arm the EQ */
9394 				lpfc_sli4_eq_release(fpeq,
9395 					LPFC_QUEUE_REARM);
9396 			}
9397 			atomic_inc(&hba_eq_hdl->hba_eq_in_use);
9398 		}
9399 	} else {
9400 		/* For now, SLI2/3 will still use hbalock */
9401 		spin_lock_irqsave(&phba->hbalock, iflags);
9402 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
9403 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9404 	}
9405 	return rc;
9406 }
9407 
9408 /**
9409  * lpfc_extra_ring_setup - Extra ring setup function
9410  * @phba: Pointer to HBA context object.
9411  *
9412  * This function is called while driver attaches with the
9413  * HBA to setup the extra ring. The extra ring is used
9414  * only when driver needs to support target mode functionality
9415  * or IP over FC functionalities.
9416  *
9417  * This function is called with no lock held. SLI3 only.
9418  **/
9419 static int
9420 lpfc_extra_ring_setup( struct lpfc_hba *phba)
9421 {
9422 	struct lpfc_sli *psli;
9423 	struct lpfc_sli_ring *pring;
9424 
9425 	psli = &phba->sli;
9426 
9427 	/* Adjust cmd/rsp ring iocb entries more evenly */
9428 
9429 	/* Take some away from the FCP ring */
9430 	pring = &psli->sli3_ring[LPFC_FCP_RING];
9431 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
9432 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
9433 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
9434 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
9435 
9436 	/* and give them to the extra ring */
9437 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
9438 
9439 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
9440 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
9441 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
9442 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
9443 
9444 	/* Setup default profile for this ring */
9445 	pring->iotag_max = 4096;
9446 	pring->num_mask = 1;
9447 	pring->prt[0].profile = 0;      /* Mask 0 */
9448 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
9449 	pring->prt[0].type = phba->cfg_multi_ring_type;
9450 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
9451 	return 0;
9452 }
9453 
9454 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
9455  * @phba: Pointer to HBA context object.
9456  * @iocbq: Pointer to iocb object.
9457  *
9458  * The async_event handler calls this routine when it receives
9459  * an ASYNC_STATUS_CN event from the port.  The port generates
9460  * this event when an Abort Sequence request to an rport fails
9461  * twice in succession.  The abort could be originated by the
9462  * driver or by the port.  The ABTS could have been for an ELS
9463  * or FCP IO.  The port only generates this event when an ABTS
9464  * fails to complete after one retry.
9465  */
9466 static void
9467 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
9468 			  struct lpfc_iocbq *iocbq)
9469 {
9470 	struct lpfc_nodelist *ndlp = NULL;
9471 	uint16_t rpi = 0, vpi = 0;
9472 	struct lpfc_vport *vport = NULL;
9473 
9474 	/* The rpi in the ulpContext is vport-sensitive. */
9475 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
9476 	rpi = iocbq->iocb.ulpContext;
9477 
9478 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9479 			"3092 Port generated ABTS async event "
9480 			"on vpi %d rpi %d status 0x%x\n",
9481 			vpi, rpi, iocbq->iocb.ulpStatus);
9482 
9483 	vport = lpfc_find_vport_by_vpid(phba, vpi);
9484 	if (!vport)
9485 		goto err_exit;
9486 	ndlp = lpfc_findnode_rpi(vport, rpi);
9487 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp))
9488 		goto err_exit;
9489 
9490 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
9491 		lpfc_sli_abts_recover_port(vport, ndlp);
9492 	return;
9493 
9494  err_exit:
9495 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9496 			"3095 Event Context not found, no "
9497 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
9498 			iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
9499 			vpi, rpi);
9500 }
9501 
9502 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
9503  * @phba: pointer to HBA context object.
9504  * @ndlp: nodelist pointer for the impacted rport.
9505  * @axri: pointer to the wcqe containing the failed exchange.
9506  *
9507  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
9508  * port.  The port generates this event when an abort exchange request to an
9509  * rport fails twice in succession with no reply.  The abort could be originated
9510  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
9511  */
9512 void
9513 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
9514 			   struct lpfc_nodelist *ndlp,
9515 			   struct sli4_wcqe_xri_aborted *axri)
9516 {
9517 	struct lpfc_vport *vport;
9518 	uint32_t ext_status = 0;
9519 
9520 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
9521 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9522 				"3115 Node Context not found, driver "
9523 				"ignoring abts err event\n");
9524 		return;
9525 	}
9526 
9527 	vport = ndlp->vport;
9528 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9529 			"3116 Port generated FCP XRI ABORT event on "
9530 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
9531 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
9532 			bf_get(lpfc_wcqe_xa_xri, axri),
9533 			bf_get(lpfc_wcqe_xa_status, axri),
9534 			axri->parameter);
9535 
9536 	/*
9537 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
9538 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
9539 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
9540 	 */
9541 	ext_status = axri->parameter & IOERR_PARAM_MASK;
9542 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
9543 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
9544 		lpfc_sli_abts_recover_port(vport, ndlp);
9545 }
9546 
9547 /**
9548  * lpfc_sli_async_event_handler - ASYNC iocb handler function
9549  * @phba: Pointer to HBA context object.
9550  * @pring: Pointer to driver SLI ring object.
9551  * @iocbq: Pointer to iocb object.
9552  *
9553  * This function is called by the slow ring event handler
9554  * function when there is an ASYNC event iocb in the ring.
9555  * This function is called with no lock held.
9556  * Currently this function handles only temperature related
9557  * ASYNC events. The function decodes the temperature sensor
9558  * event message and posts events for the management applications.
9559  **/
9560 static void
9561 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
9562 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
9563 {
9564 	IOCB_t *icmd;
9565 	uint16_t evt_code;
9566 	struct temp_event temp_event_data;
9567 	struct Scsi_Host *shost;
9568 	uint32_t *iocb_w;
9569 
9570 	icmd = &iocbq->iocb;
9571 	evt_code = icmd->un.asyncstat.evt_code;
9572 
9573 	switch (evt_code) {
9574 	case ASYNC_TEMP_WARN:
9575 	case ASYNC_TEMP_SAFE:
9576 		temp_event_data.data = (uint32_t) icmd->ulpContext;
9577 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
9578 		if (evt_code == ASYNC_TEMP_WARN) {
9579 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
9580 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
9581 				"0347 Adapter is very hot, please take "
9582 				"corrective action. temperature : %d Celsius\n",
9583 				(uint32_t) icmd->ulpContext);
9584 		} else {
9585 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
9586 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
9587 				"0340 Adapter temperature is OK now. "
9588 				"temperature : %d Celsius\n",
9589 				(uint32_t) icmd->ulpContext);
9590 		}
9591 
9592 		/* Send temperature change event to applications */
9593 		shost = lpfc_shost_from_vport(phba->pport);
9594 		fc_host_post_vendor_event(shost, fc_get_event_number(),
9595 			sizeof(temp_event_data), (char *) &temp_event_data,
9596 			LPFC_NL_VENDOR_ID);
9597 		break;
9598 	case ASYNC_STATUS_CN:
9599 		lpfc_sli_abts_err_handler(phba, iocbq);
9600 		break;
9601 	default:
9602 		iocb_w = (uint32_t *) icmd;
9603 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9604 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
9605 			" evt_code 0x%x\n"
9606 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
9607 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
9608 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
9609 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
9610 			pring->ringno, icmd->un.asyncstat.evt_code,
9611 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
9612 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
9613 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
9614 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
9615 
9616 		break;
9617 	}
9618 }
9619 
9620 
9621 /**
9622  * lpfc_sli4_setup - SLI ring setup function
9623  * @phba: Pointer to HBA context object.
9624  *
9625  * lpfc_sli_setup sets up rings of the SLI interface with
9626  * number of iocbs per ring and iotags. This function is
9627  * called while driver attach to the HBA and before the
9628  * interrupts are enabled. So there is no need for locking.
9629  *
9630  * This function always returns 0.
9631  **/
9632 int
9633 lpfc_sli4_setup(struct lpfc_hba *phba)
9634 {
9635 	struct lpfc_sli_ring *pring;
9636 
9637 	pring = phba->sli4_hba.els_wq->pring;
9638 	pring->num_mask = LPFC_MAX_RING_MASK;
9639 	pring->prt[0].profile = 0;	/* Mask 0 */
9640 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
9641 	pring->prt[0].type = FC_TYPE_ELS;
9642 	pring->prt[0].lpfc_sli_rcv_unsol_event =
9643 	    lpfc_els_unsol_event;
9644 	pring->prt[1].profile = 0;	/* Mask 1 */
9645 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
9646 	pring->prt[1].type = FC_TYPE_ELS;
9647 	pring->prt[1].lpfc_sli_rcv_unsol_event =
9648 	    lpfc_els_unsol_event;
9649 	pring->prt[2].profile = 0;	/* Mask 2 */
9650 	/* NameServer Inquiry */
9651 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
9652 	/* NameServer */
9653 	pring->prt[2].type = FC_TYPE_CT;
9654 	pring->prt[2].lpfc_sli_rcv_unsol_event =
9655 	    lpfc_ct_unsol_event;
9656 	pring->prt[3].profile = 0;	/* Mask 3 */
9657 	/* NameServer response */
9658 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
9659 	/* NameServer */
9660 	pring->prt[3].type = FC_TYPE_CT;
9661 	pring->prt[3].lpfc_sli_rcv_unsol_event =
9662 	    lpfc_ct_unsol_event;
9663 	return 0;
9664 }
9665 
9666 /**
9667  * lpfc_sli_setup - SLI ring setup function
9668  * @phba: Pointer to HBA context object.
9669  *
9670  * lpfc_sli_setup sets up rings of the SLI interface with
9671  * number of iocbs per ring and iotags. This function is
9672  * called while driver attach to the HBA and before the
9673  * interrupts are enabled. So there is no need for locking.
9674  *
9675  * This function always returns 0. SLI3 only.
9676  **/
9677 int
9678 lpfc_sli_setup(struct lpfc_hba *phba)
9679 {
9680 	int i, totiocbsize = 0;
9681 	struct lpfc_sli *psli = &phba->sli;
9682 	struct lpfc_sli_ring *pring;
9683 
9684 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
9685 	psli->sli_flag = 0;
9686 
9687 	psli->iocbq_lookup = NULL;
9688 	psli->iocbq_lookup_len = 0;
9689 	psli->last_iotag = 0;
9690 
9691 	for (i = 0; i < psli->num_rings; i++) {
9692 		pring = &psli->sli3_ring[i];
9693 		switch (i) {
9694 		case LPFC_FCP_RING:	/* ring 0 - FCP */
9695 			/* numCiocb and numRiocb are used in config_port */
9696 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
9697 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
9698 			pring->sli.sli3.numCiocb +=
9699 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
9700 			pring->sli.sli3.numRiocb +=
9701 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
9702 			pring->sli.sli3.numCiocb +=
9703 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
9704 			pring->sli.sli3.numRiocb +=
9705 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
9706 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9707 							SLI3_IOCB_CMD_SIZE :
9708 							SLI2_IOCB_CMD_SIZE;
9709 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9710 							SLI3_IOCB_RSP_SIZE :
9711 							SLI2_IOCB_RSP_SIZE;
9712 			pring->iotag_ctr = 0;
9713 			pring->iotag_max =
9714 			    (phba->cfg_hba_queue_depth * 2);
9715 			pring->fast_iotag = pring->iotag_max;
9716 			pring->num_mask = 0;
9717 			break;
9718 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
9719 			/* numCiocb and numRiocb are used in config_port */
9720 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
9721 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
9722 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9723 							SLI3_IOCB_CMD_SIZE :
9724 							SLI2_IOCB_CMD_SIZE;
9725 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9726 							SLI3_IOCB_RSP_SIZE :
9727 							SLI2_IOCB_RSP_SIZE;
9728 			pring->iotag_max = phba->cfg_hba_queue_depth;
9729 			pring->num_mask = 0;
9730 			break;
9731 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
9732 			/* numCiocb and numRiocb are used in config_port */
9733 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
9734 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
9735 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9736 							SLI3_IOCB_CMD_SIZE :
9737 							SLI2_IOCB_CMD_SIZE;
9738 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9739 							SLI3_IOCB_RSP_SIZE :
9740 							SLI2_IOCB_RSP_SIZE;
9741 			pring->fast_iotag = 0;
9742 			pring->iotag_ctr = 0;
9743 			pring->iotag_max = 4096;
9744 			pring->lpfc_sli_rcv_async_status =
9745 				lpfc_sli_async_event_handler;
9746 			pring->num_mask = LPFC_MAX_RING_MASK;
9747 			pring->prt[0].profile = 0;	/* Mask 0 */
9748 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
9749 			pring->prt[0].type = FC_TYPE_ELS;
9750 			pring->prt[0].lpfc_sli_rcv_unsol_event =
9751 			    lpfc_els_unsol_event;
9752 			pring->prt[1].profile = 0;	/* Mask 1 */
9753 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
9754 			pring->prt[1].type = FC_TYPE_ELS;
9755 			pring->prt[1].lpfc_sli_rcv_unsol_event =
9756 			    lpfc_els_unsol_event;
9757 			pring->prt[2].profile = 0;	/* Mask 2 */
9758 			/* NameServer Inquiry */
9759 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
9760 			/* NameServer */
9761 			pring->prt[2].type = FC_TYPE_CT;
9762 			pring->prt[2].lpfc_sli_rcv_unsol_event =
9763 			    lpfc_ct_unsol_event;
9764 			pring->prt[3].profile = 0;	/* Mask 3 */
9765 			/* NameServer response */
9766 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
9767 			/* NameServer */
9768 			pring->prt[3].type = FC_TYPE_CT;
9769 			pring->prt[3].lpfc_sli_rcv_unsol_event =
9770 			    lpfc_ct_unsol_event;
9771 			break;
9772 		}
9773 		totiocbsize += (pring->sli.sli3.numCiocb *
9774 			pring->sli.sli3.sizeCiocb) +
9775 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
9776 	}
9777 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
9778 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
9779 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
9780 		       "SLI2 SLIM Data: x%x x%lx\n",
9781 		       phba->brd_no, totiocbsize,
9782 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
9783 	}
9784 	if (phba->cfg_multi_ring_support == 2)
9785 		lpfc_extra_ring_setup(phba);
9786 
9787 	return 0;
9788 }
9789 
9790 /**
9791  * lpfc_sli4_queue_init - Queue initialization function
9792  * @phba: Pointer to HBA context object.
9793  *
9794  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
9795  * ring. This function also initializes ring indices of each ring.
9796  * This function is called during the initialization of the SLI
9797  * interface of an HBA.
9798  * This function is called with no lock held and always returns
9799  * 1.
9800  **/
9801 void
9802 lpfc_sli4_queue_init(struct lpfc_hba *phba)
9803 {
9804 	struct lpfc_sli *psli;
9805 	struct lpfc_sli_ring *pring;
9806 	int i;
9807 
9808 	psli = &phba->sli;
9809 	spin_lock_irq(&phba->hbalock);
9810 	INIT_LIST_HEAD(&psli->mboxq);
9811 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
9812 	/* Initialize list headers for txq and txcmplq as double linked lists */
9813 	for (i = 0; i < phba->cfg_fcp_io_channel; i++) {
9814 		pring = phba->sli4_hba.fcp_wq[i]->pring;
9815 		pring->flag = 0;
9816 		pring->ringno = LPFC_FCP_RING;
9817 		INIT_LIST_HEAD(&pring->txq);
9818 		INIT_LIST_HEAD(&pring->txcmplq);
9819 		INIT_LIST_HEAD(&pring->iocb_continueq);
9820 		spin_lock_init(&pring->ring_lock);
9821 	}
9822 	for (i = 0; i < phba->cfg_nvme_io_channel; i++) {
9823 		pring = phba->sli4_hba.nvme_wq[i]->pring;
9824 		pring->flag = 0;
9825 		pring->ringno = LPFC_FCP_RING;
9826 		INIT_LIST_HEAD(&pring->txq);
9827 		INIT_LIST_HEAD(&pring->txcmplq);
9828 		INIT_LIST_HEAD(&pring->iocb_continueq);
9829 		spin_lock_init(&pring->ring_lock);
9830 	}
9831 	pring = phba->sli4_hba.els_wq->pring;
9832 	pring->flag = 0;
9833 	pring->ringno = LPFC_ELS_RING;
9834 	INIT_LIST_HEAD(&pring->txq);
9835 	INIT_LIST_HEAD(&pring->txcmplq);
9836 	INIT_LIST_HEAD(&pring->iocb_continueq);
9837 	spin_lock_init(&pring->ring_lock);
9838 
9839 	if (phba->cfg_nvme_io_channel) {
9840 		pring = phba->sli4_hba.nvmels_wq->pring;
9841 		pring->flag = 0;
9842 		pring->ringno = LPFC_ELS_RING;
9843 		INIT_LIST_HEAD(&pring->txq);
9844 		INIT_LIST_HEAD(&pring->txcmplq);
9845 		INIT_LIST_HEAD(&pring->iocb_continueq);
9846 		spin_lock_init(&pring->ring_lock);
9847 	}
9848 
9849 	if (phba->cfg_fof) {
9850 		pring = phba->sli4_hba.oas_wq->pring;
9851 		pring->flag = 0;
9852 		pring->ringno = LPFC_FCP_RING;
9853 		INIT_LIST_HEAD(&pring->txq);
9854 		INIT_LIST_HEAD(&pring->txcmplq);
9855 		INIT_LIST_HEAD(&pring->iocb_continueq);
9856 		spin_lock_init(&pring->ring_lock);
9857 	}
9858 
9859 	spin_unlock_irq(&phba->hbalock);
9860 }
9861 
9862 /**
9863  * lpfc_sli_queue_init - Queue initialization function
9864  * @phba: Pointer to HBA context object.
9865  *
9866  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
9867  * ring. This function also initializes ring indices of each ring.
9868  * This function is called during the initialization of the SLI
9869  * interface of an HBA.
9870  * This function is called with no lock held and always returns
9871  * 1.
9872  **/
9873 void
9874 lpfc_sli_queue_init(struct lpfc_hba *phba)
9875 {
9876 	struct lpfc_sli *psli;
9877 	struct lpfc_sli_ring *pring;
9878 	int i;
9879 
9880 	psli = &phba->sli;
9881 	spin_lock_irq(&phba->hbalock);
9882 	INIT_LIST_HEAD(&psli->mboxq);
9883 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
9884 	/* Initialize list headers for txq and txcmplq as double linked lists */
9885 	for (i = 0; i < psli->num_rings; i++) {
9886 		pring = &psli->sli3_ring[i];
9887 		pring->ringno = i;
9888 		pring->sli.sli3.next_cmdidx  = 0;
9889 		pring->sli.sli3.local_getidx = 0;
9890 		pring->sli.sli3.cmdidx = 0;
9891 		INIT_LIST_HEAD(&pring->iocb_continueq);
9892 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
9893 		INIT_LIST_HEAD(&pring->postbufq);
9894 		pring->flag = 0;
9895 		INIT_LIST_HEAD(&pring->txq);
9896 		INIT_LIST_HEAD(&pring->txcmplq);
9897 		spin_lock_init(&pring->ring_lock);
9898 	}
9899 	spin_unlock_irq(&phba->hbalock);
9900 }
9901 
9902 /**
9903  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
9904  * @phba: Pointer to HBA context object.
9905  *
9906  * This routine flushes the mailbox command subsystem. It will unconditionally
9907  * flush all the mailbox commands in the three possible stages in the mailbox
9908  * command sub-system: pending mailbox command queue; the outstanding mailbox
9909  * command; and completed mailbox command queue. It is caller's responsibility
9910  * to make sure that the driver is in the proper state to flush the mailbox
9911  * command sub-system. Namely, the posting of mailbox commands into the
9912  * pending mailbox command queue from the various clients must be stopped;
9913  * either the HBA is in a state that it will never works on the outstanding
9914  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
9915  * mailbox command has been completed.
9916  **/
9917 static void
9918 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
9919 {
9920 	LIST_HEAD(completions);
9921 	struct lpfc_sli *psli = &phba->sli;
9922 	LPFC_MBOXQ_t *pmb;
9923 	unsigned long iflag;
9924 
9925 	/* Flush all the mailbox commands in the mbox system */
9926 	spin_lock_irqsave(&phba->hbalock, iflag);
9927 	/* The pending mailbox command queue */
9928 	list_splice_init(&phba->sli.mboxq, &completions);
9929 	/* The outstanding active mailbox command */
9930 	if (psli->mbox_active) {
9931 		list_add_tail(&psli->mbox_active->list, &completions);
9932 		psli->mbox_active = NULL;
9933 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9934 	}
9935 	/* The completed mailbox command queue */
9936 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
9937 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9938 
9939 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
9940 	while (!list_empty(&completions)) {
9941 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
9942 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
9943 		if (pmb->mbox_cmpl)
9944 			pmb->mbox_cmpl(phba, pmb);
9945 	}
9946 }
9947 
9948 /**
9949  * lpfc_sli_host_down - Vport cleanup function
9950  * @vport: Pointer to virtual port object.
9951  *
9952  * lpfc_sli_host_down is called to clean up the resources
9953  * associated with a vport before destroying virtual
9954  * port data structures.
9955  * This function does following operations:
9956  * - Free discovery resources associated with this virtual
9957  *   port.
9958  * - Free iocbs associated with this virtual port in
9959  *   the txq.
9960  * - Send abort for all iocb commands associated with this
9961  *   vport in txcmplq.
9962  *
9963  * This function is called with no lock held and always returns 1.
9964  **/
9965 int
9966 lpfc_sli_host_down(struct lpfc_vport *vport)
9967 {
9968 	LIST_HEAD(completions);
9969 	struct lpfc_hba *phba = vport->phba;
9970 	struct lpfc_sli *psli = &phba->sli;
9971 	struct lpfc_queue *qp = NULL;
9972 	struct lpfc_sli_ring *pring;
9973 	struct lpfc_iocbq *iocb, *next_iocb;
9974 	int i;
9975 	unsigned long flags = 0;
9976 	uint16_t prev_pring_flag;
9977 
9978 	lpfc_cleanup_discovery_resources(vport);
9979 
9980 	spin_lock_irqsave(&phba->hbalock, flags);
9981 
9982 	/*
9983 	 * Error everything on the txq since these iocbs
9984 	 * have not been given to the FW yet.
9985 	 * Also issue ABTS for everything on the txcmplq
9986 	 */
9987 	if (phba->sli_rev != LPFC_SLI_REV4) {
9988 		for (i = 0; i < psli->num_rings; i++) {
9989 			pring = &psli->sli3_ring[i];
9990 			prev_pring_flag = pring->flag;
9991 			/* Only slow rings */
9992 			if (pring->ringno == LPFC_ELS_RING) {
9993 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
9994 				/* Set the lpfc data pending flag */
9995 				set_bit(LPFC_DATA_READY, &phba->data_flags);
9996 			}
9997 			list_for_each_entry_safe(iocb, next_iocb,
9998 						 &pring->txq, list) {
9999 				if (iocb->vport != vport)
10000 					continue;
10001 				list_move_tail(&iocb->list, &completions);
10002 			}
10003 			list_for_each_entry_safe(iocb, next_iocb,
10004 						 &pring->txcmplq, list) {
10005 				if (iocb->vport != vport)
10006 					continue;
10007 				lpfc_sli_issue_abort_iotag(phba, pring, iocb);
10008 			}
10009 			pring->flag = prev_pring_flag;
10010 		}
10011 	} else {
10012 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
10013 			pring = qp->pring;
10014 			if (!pring)
10015 				continue;
10016 			if (pring == phba->sli4_hba.els_wq->pring) {
10017 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10018 				/* Set the lpfc data pending flag */
10019 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10020 			}
10021 			prev_pring_flag = pring->flag;
10022 			spin_lock_irq(&pring->ring_lock);
10023 			list_for_each_entry_safe(iocb, next_iocb,
10024 						 &pring->txq, list) {
10025 				if (iocb->vport != vport)
10026 					continue;
10027 				list_move_tail(&iocb->list, &completions);
10028 			}
10029 			spin_unlock_irq(&pring->ring_lock);
10030 			list_for_each_entry_safe(iocb, next_iocb,
10031 						 &pring->txcmplq, list) {
10032 				if (iocb->vport != vport)
10033 					continue;
10034 				lpfc_sli_issue_abort_iotag(phba, pring, iocb);
10035 			}
10036 			pring->flag = prev_pring_flag;
10037 		}
10038 	}
10039 	spin_unlock_irqrestore(&phba->hbalock, flags);
10040 
10041 	/* Cancel all the IOCBs from the completions list */
10042 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
10043 			      IOERR_SLI_DOWN);
10044 	return 1;
10045 }
10046 
10047 /**
10048  * lpfc_sli_hba_down - Resource cleanup function for the HBA
10049  * @phba: Pointer to HBA context object.
10050  *
10051  * This function cleans up all iocb, buffers, mailbox commands
10052  * while shutting down the HBA. This function is called with no
10053  * lock held and always returns 1.
10054  * This function does the following to cleanup driver resources:
10055  * - Free discovery resources for each virtual port
10056  * - Cleanup any pending fabric iocbs
10057  * - Iterate through the iocb txq and free each entry
10058  *   in the list.
10059  * - Free up any buffer posted to the HBA
10060  * - Free mailbox commands in the mailbox queue.
10061  **/
10062 int
10063 lpfc_sli_hba_down(struct lpfc_hba *phba)
10064 {
10065 	LIST_HEAD(completions);
10066 	struct lpfc_sli *psli = &phba->sli;
10067 	struct lpfc_queue *qp = NULL;
10068 	struct lpfc_sli_ring *pring;
10069 	struct lpfc_dmabuf *buf_ptr;
10070 	unsigned long flags = 0;
10071 	int i;
10072 
10073 	/* Shutdown the mailbox command sub-system */
10074 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
10075 
10076 	lpfc_hba_down_prep(phba);
10077 
10078 	lpfc_fabric_abort_hba(phba);
10079 
10080 	spin_lock_irqsave(&phba->hbalock, flags);
10081 
10082 	/*
10083 	 * Error everything on the txq since these iocbs
10084 	 * have not been given to the FW yet.
10085 	 */
10086 	if (phba->sli_rev != LPFC_SLI_REV4) {
10087 		for (i = 0; i < psli->num_rings; i++) {
10088 			pring = &psli->sli3_ring[i];
10089 			/* Only slow rings */
10090 			if (pring->ringno == LPFC_ELS_RING) {
10091 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10092 				/* Set the lpfc data pending flag */
10093 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10094 			}
10095 			list_splice_init(&pring->txq, &completions);
10096 		}
10097 	} else {
10098 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
10099 			pring = qp->pring;
10100 			if (!pring)
10101 				continue;
10102 			spin_lock_irq(&pring->ring_lock);
10103 			list_splice_init(&pring->txq, &completions);
10104 			spin_unlock_irq(&pring->ring_lock);
10105 			if (pring == phba->sli4_hba.els_wq->pring) {
10106 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10107 				/* Set the lpfc data pending flag */
10108 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10109 			}
10110 		}
10111 	}
10112 	spin_unlock_irqrestore(&phba->hbalock, flags);
10113 
10114 	/* Cancel all the IOCBs from the completions list */
10115 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
10116 			      IOERR_SLI_DOWN);
10117 
10118 	spin_lock_irqsave(&phba->hbalock, flags);
10119 	list_splice_init(&phba->elsbuf, &completions);
10120 	phba->elsbuf_cnt = 0;
10121 	phba->elsbuf_prev_cnt = 0;
10122 	spin_unlock_irqrestore(&phba->hbalock, flags);
10123 
10124 	while (!list_empty(&completions)) {
10125 		list_remove_head(&completions, buf_ptr,
10126 			struct lpfc_dmabuf, list);
10127 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
10128 		kfree(buf_ptr);
10129 	}
10130 
10131 	/* Return any active mbox cmds */
10132 	del_timer_sync(&psli->mbox_tmo);
10133 
10134 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
10135 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
10136 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
10137 
10138 	return 1;
10139 }
10140 
10141 /**
10142  * lpfc_sli_pcimem_bcopy - SLI memory copy function
10143  * @srcp: Source memory pointer.
10144  * @destp: Destination memory pointer.
10145  * @cnt: Number of words required to be copied.
10146  *
10147  * This function is used for copying data between driver memory
10148  * and the SLI memory. This function also changes the endianness
10149  * of each word if native endianness is different from SLI
10150  * endianness. This function can be called with or without
10151  * lock.
10152  **/
10153 void
10154 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
10155 {
10156 	uint32_t *src = srcp;
10157 	uint32_t *dest = destp;
10158 	uint32_t ldata;
10159 	int i;
10160 
10161 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
10162 		ldata = *src;
10163 		ldata = le32_to_cpu(ldata);
10164 		*dest = ldata;
10165 		src++;
10166 		dest++;
10167 	}
10168 }
10169 
10170 
10171 /**
10172  * lpfc_sli_bemem_bcopy - SLI memory copy function
10173  * @srcp: Source memory pointer.
10174  * @destp: Destination memory pointer.
10175  * @cnt: Number of words required to be copied.
10176  *
10177  * This function is used for copying data between a data structure
10178  * with big endian representation to local endianness.
10179  * This function can be called with or without lock.
10180  **/
10181 void
10182 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
10183 {
10184 	uint32_t *src = srcp;
10185 	uint32_t *dest = destp;
10186 	uint32_t ldata;
10187 	int i;
10188 
10189 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
10190 		ldata = *src;
10191 		ldata = be32_to_cpu(ldata);
10192 		*dest = ldata;
10193 		src++;
10194 		dest++;
10195 	}
10196 }
10197 
10198 /**
10199  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
10200  * @phba: Pointer to HBA context object.
10201  * @pring: Pointer to driver SLI ring object.
10202  * @mp: Pointer to driver buffer object.
10203  *
10204  * This function is called with no lock held.
10205  * It always return zero after adding the buffer to the postbufq
10206  * buffer list.
10207  **/
10208 int
10209 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10210 			 struct lpfc_dmabuf *mp)
10211 {
10212 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
10213 	   later */
10214 	spin_lock_irq(&phba->hbalock);
10215 	list_add_tail(&mp->list, &pring->postbufq);
10216 	pring->postbufq_cnt++;
10217 	spin_unlock_irq(&phba->hbalock);
10218 	return 0;
10219 }
10220 
10221 /**
10222  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
10223  * @phba: Pointer to HBA context object.
10224  *
10225  * When HBQ is enabled, buffers are searched based on tags. This function
10226  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
10227  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
10228  * does not conflict with tags of buffer posted for unsolicited events.
10229  * The function returns the allocated tag. The function is called with
10230  * no locks held.
10231  **/
10232 uint32_t
10233 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
10234 {
10235 	spin_lock_irq(&phba->hbalock);
10236 	phba->buffer_tag_count++;
10237 	/*
10238 	 * Always set the QUE_BUFTAG_BIT to distiguish between
10239 	 * a tag assigned by HBQ.
10240 	 */
10241 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
10242 	spin_unlock_irq(&phba->hbalock);
10243 	return phba->buffer_tag_count;
10244 }
10245 
10246 /**
10247  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
10248  * @phba: Pointer to HBA context object.
10249  * @pring: Pointer to driver SLI ring object.
10250  * @tag: Buffer tag.
10251  *
10252  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
10253  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
10254  * iocb is posted to the response ring with the tag of the buffer.
10255  * This function searches the pring->postbufq list using the tag
10256  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
10257  * iocb. If the buffer is found then lpfc_dmabuf object of the
10258  * buffer is returned to the caller else NULL is returned.
10259  * This function is called with no lock held.
10260  **/
10261 struct lpfc_dmabuf *
10262 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10263 			uint32_t tag)
10264 {
10265 	struct lpfc_dmabuf *mp, *next_mp;
10266 	struct list_head *slp = &pring->postbufq;
10267 
10268 	/* Search postbufq, from the beginning, looking for a match on tag */
10269 	spin_lock_irq(&phba->hbalock);
10270 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
10271 		if (mp->buffer_tag == tag) {
10272 			list_del_init(&mp->list);
10273 			pring->postbufq_cnt--;
10274 			spin_unlock_irq(&phba->hbalock);
10275 			return mp;
10276 		}
10277 	}
10278 
10279 	spin_unlock_irq(&phba->hbalock);
10280 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10281 			"0402 Cannot find virtual addr for buffer tag on "
10282 			"ring %d Data x%lx x%p x%p x%x\n",
10283 			pring->ringno, (unsigned long) tag,
10284 			slp->next, slp->prev, pring->postbufq_cnt);
10285 
10286 	return NULL;
10287 }
10288 
10289 /**
10290  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
10291  * @phba: Pointer to HBA context object.
10292  * @pring: Pointer to driver SLI ring object.
10293  * @phys: DMA address of the buffer.
10294  *
10295  * This function searches the buffer list using the dma_address
10296  * of unsolicited event to find the driver's lpfc_dmabuf object
10297  * corresponding to the dma_address. The function returns the
10298  * lpfc_dmabuf object if a buffer is found else it returns NULL.
10299  * This function is called by the ct and els unsolicited event
10300  * handlers to get the buffer associated with the unsolicited
10301  * event.
10302  *
10303  * This function is called with no lock held.
10304  **/
10305 struct lpfc_dmabuf *
10306 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10307 			 dma_addr_t phys)
10308 {
10309 	struct lpfc_dmabuf *mp, *next_mp;
10310 	struct list_head *slp = &pring->postbufq;
10311 
10312 	/* Search postbufq, from the beginning, looking for a match on phys */
10313 	spin_lock_irq(&phba->hbalock);
10314 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
10315 		if (mp->phys == phys) {
10316 			list_del_init(&mp->list);
10317 			pring->postbufq_cnt--;
10318 			spin_unlock_irq(&phba->hbalock);
10319 			return mp;
10320 		}
10321 	}
10322 
10323 	spin_unlock_irq(&phba->hbalock);
10324 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10325 			"0410 Cannot find virtual addr for mapped buf on "
10326 			"ring %d Data x%llx x%p x%p x%x\n",
10327 			pring->ringno, (unsigned long long)phys,
10328 			slp->next, slp->prev, pring->postbufq_cnt);
10329 	return NULL;
10330 }
10331 
10332 /**
10333  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
10334  * @phba: Pointer to HBA context object.
10335  * @cmdiocb: Pointer to driver command iocb object.
10336  * @rspiocb: Pointer to driver response iocb object.
10337  *
10338  * This function is the completion handler for the abort iocbs for
10339  * ELS commands. This function is called from the ELS ring event
10340  * handler with no lock held. This function frees memory resources
10341  * associated with the abort iocb.
10342  **/
10343 static void
10344 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
10345 			struct lpfc_iocbq *rspiocb)
10346 {
10347 	IOCB_t *irsp = &rspiocb->iocb;
10348 	uint16_t abort_iotag, abort_context;
10349 	struct lpfc_iocbq *abort_iocb = NULL;
10350 
10351 	if (irsp->ulpStatus) {
10352 
10353 		/*
10354 		 * Assume that the port already completed and returned, or
10355 		 * will return the iocb. Just Log the message.
10356 		 */
10357 		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
10358 		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
10359 
10360 		spin_lock_irq(&phba->hbalock);
10361 		if (phba->sli_rev < LPFC_SLI_REV4) {
10362 			if (abort_iotag != 0 &&
10363 				abort_iotag <= phba->sli.last_iotag)
10364 				abort_iocb =
10365 					phba->sli.iocbq_lookup[abort_iotag];
10366 		} else
10367 			/* For sli4 the abort_tag is the XRI,
10368 			 * so the abort routine puts the iotag  of the iocb
10369 			 * being aborted in the context field of the abort
10370 			 * IOCB.
10371 			 */
10372 			abort_iocb = phba->sli.iocbq_lookup[abort_context];
10373 
10374 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
10375 				"0327 Cannot abort els iocb %p "
10376 				"with tag %x context %x, abort status %x, "
10377 				"abort code %x\n",
10378 				abort_iocb, abort_iotag, abort_context,
10379 				irsp->ulpStatus, irsp->un.ulpWord[4]);
10380 
10381 		spin_unlock_irq(&phba->hbalock);
10382 	}
10383 	lpfc_sli_release_iocbq(phba, cmdiocb);
10384 	return;
10385 }
10386 
10387 /**
10388  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
10389  * @phba: Pointer to HBA context object.
10390  * @cmdiocb: Pointer to driver command iocb object.
10391  * @rspiocb: Pointer to driver response iocb object.
10392  *
10393  * The function is called from SLI ring event handler with no
10394  * lock held. This function is the completion handler for ELS commands
10395  * which are aborted. The function frees memory resources used for
10396  * the aborted ELS commands.
10397  **/
10398 static void
10399 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
10400 		     struct lpfc_iocbq *rspiocb)
10401 {
10402 	IOCB_t *irsp = &rspiocb->iocb;
10403 
10404 	/* ELS cmd tag <ulpIoTag> completes */
10405 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
10406 			"0139 Ignoring ELS cmd tag x%x completion Data: "
10407 			"x%x x%x x%x\n",
10408 			irsp->ulpIoTag, irsp->ulpStatus,
10409 			irsp->un.ulpWord[4], irsp->ulpTimeout);
10410 	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
10411 		lpfc_ct_free_iocb(phba, cmdiocb);
10412 	else
10413 		lpfc_els_free_iocb(phba, cmdiocb);
10414 	return;
10415 }
10416 
10417 /**
10418  * lpfc_sli_abort_iotag_issue - Issue abort for a command iocb
10419  * @phba: Pointer to HBA context object.
10420  * @pring: Pointer to driver SLI ring object.
10421  * @cmdiocb: Pointer to driver command iocb object.
10422  *
10423  * This function issues an abort iocb for the provided command iocb down to
10424  * the port. Other than the case the outstanding command iocb is an abort
10425  * request, this function issues abort out unconditionally. This function is
10426  * called with hbalock held. The function returns 0 when it fails due to
10427  * memory allocation failure or when the command iocb is an abort request.
10428  **/
10429 static int
10430 lpfc_sli_abort_iotag_issue(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10431 			   struct lpfc_iocbq *cmdiocb)
10432 {
10433 	struct lpfc_vport *vport = cmdiocb->vport;
10434 	struct lpfc_iocbq *abtsiocbp;
10435 	IOCB_t *icmd = NULL;
10436 	IOCB_t *iabt = NULL;
10437 	int retval;
10438 	unsigned long iflags;
10439 
10440 	lockdep_assert_held(&phba->hbalock);
10441 
10442 	/*
10443 	 * There are certain command types we don't want to abort.  And we
10444 	 * don't want to abort commands that are already in the process of
10445 	 * being aborted.
10446 	 */
10447 	icmd = &cmdiocb->iocb;
10448 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
10449 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
10450 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
10451 		return 0;
10452 
10453 	/* issue ABTS for this IOCB based on iotag */
10454 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
10455 	if (abtsiocbp == NULL)
10456 		return 0;
10457 
10458 	/* This signals the response to set the correct status
10459 	 * before calling the completion handler
10460 	 */
10461 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
10462 
10463 	iabt = &abtsiocbp->iocb;
10464 	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
10465 	iabt->un.acxri.abortContextTag = icmd->ulpContext;
10466 	if (phba->sli_rev == LPFC_SLI_REV4) {
10467 		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
10468 		iabt->un.acxri.abortContextTag = cmdiocb->iotag;
10469 	}
10470 	else
10471 		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
10472 	iabt->ulpLe = 1;
10473 	iabt->ulpClass = icmd->ulpClass;
10474 
10475 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
10476 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
10477 	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
10478 		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
10479 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
10480 		abtsiocbp->iocb_flag |= LPFC_IO_FOF;
10481 
10482 	if (phba->link_state >= LPFC_LINK_UP)
10483 		iabt->ulpCommand = CMD_ABORT_XRI_CN;
10484 	else
10485 		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
10486 
10487 	abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
10488 	abtsiocbp->vport = vport;
10489 
10490 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
10491 			 "0339 Abort xri x%x, original iotag x%x, "
10492 			 "abort cmd iotag x%x\n",
10493 			 iabt->un.acxri.abortIoTag,
10494 			 iabt->un.acxri.abortContextTag,
10495 			 abtsiocbp->iotag);
10496 
10497 	if (phba->sli_rev == LPFC_SLI_REV4) {
10498 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
10499 		if (unlikely(pring == NULL))
10500 			return 0;
10501 		/* Note: both hbalock and ring_lock need to be set here */
10502 		spin_lock_irqsave(&pring->ring_lock, iflags);
10503 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
10504 			abtsiocbp, 0);
10505 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
10506 	} else {
10507 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
10508 			abtsiocbp, 0);
10509 	}
10510 
10511 	if (retval)
10512 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
10513 
10514 	/*
10515 	 * Caller to this routine should check for IOCB_ERROR
10516 	 * and handle it properly.  This routine no longer removes
10517 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
10518 	 */
10519 	return retval;
10520 }
10521 
10522 /**
10523  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
10524  * @phba: Pointer to HBA context object.
10525  * @pring: Pointer to driver SLI ring object.
10526  * @cmdiocb: Pointer to driver command iocb object.
10527  *
10528  * This function issues an abort iocb for the provided command iocb. In case
10529  * of unloading, the abort iocb will not be issued to commands on the ELS
10530  * ring. Instead, the callback function shall be changed to those commands
10531  * so that nothing happens when them finishes. This function is called with
10532  * hbalock held. The function returns 0 when the command iocb is an abort
10533  * request.
10534  **/
10535 int
10536 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10537 			   struct lpfc_iocbq *cmdiocb)
10538 {
10539 	struct lpfc_vport *vport = cmdiocb->vport;
10540 	int retval = IOCB_ERROR;
10541 	IOCB_t *icmd = NULL;
10542 
10543 	lockdep_assert_held(&phba->hbalock);
10544 
10545 	/*
10546 	 * There are certain command types we don't want to abort.  And we
10547 	 * don't want to abort commands that are already in the process of
10548 	 * being aborted.
10549 	 */
10550 	icmd = &cmdiocb->iocb;
10551 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
10552 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
10553 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
10554 		return 0;
10555 
10556 	/*
10557 	 * If we're unloading, don't abort iocb on the ELS ring, but change
10558 	 * the callback so that nothing happens when it finishes.
10559 	 */
10560 	if ((vport->load_flag & FC_UNLOADING) &&
10561 	    (pring->ringno == LPFC_ELS_RING)) {
10562 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
10563 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
10564 		else
10565 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
10566 		goto abort_iotag_exit;
10567 	}
10568 
10569 	/* Now, we try to issue the abort to the cmdiocb out */
10570 	retval = lpfc_sli_abort_iotag_issue(phba, pring, cmdiocb);
10571 
10572 abort_iotag_exit:
10573 	/*
10574 	 * Caller to this routine should check for IOCB_ERROR
10575 	 * and handle it properly.  This routine no longer removes
10576 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
10577 	 */
10578 	return retval;
10579 }
10580 
10581 /**
10582  * lpfc_sli4_abort_nvme_io - Issue abort for a command iocb
10583  * @phba: Pointer to HBA context object.
10584  * @pring: Pointer to driver SLI ring object.
10585  * @cmdiocb: Pointer to driver command iocb object.
10586  *
10587  * This function issues an abort iocb for the provided command iocb down to
10588  * the port. Other than the case the outstanding command iocb is an abort
10589  * request, this function issues abort out unconditionally. This function is
10590  * called with hbalock held. The function returns 0 when it fails due to
10591  * memory allocation failure or when the command iocb is an abort request.
10592  **/
10593 static int
10594 lpfc_sli4_abort_nvme_io(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10595 			struct lpfc_iocbq *cmdiocb)
10596 {
10597 	struct lpfc_vport *vport = cmdiocb->vport;
10598 	struct lpfc_iocbq *abtsiocbp;
10599 	union lpfc_wqe *abts_wqe;
10600 	int retval;
10601 
10602 	/*
10603 	 * There are certain command types we don't want to abort.  And we
10604 	 * don't want to abort commands that are already in the process of
10605 	 * being aborted.
10606 	 */
10607 	if (cmdiocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
10608 	    cmdiocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN ||
10609 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
10610 		return 0;
10611 
10612 	/* issue ABTS for this io based on iotag */
10613 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
10614 	if (abtsiocbp == NULL)
10615 		return 0;
10616 
10617 	/* This signals the response to set the correct status
10618 	 * before calling the completion handler
10619 	 */
10620 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
10621 
10622 	/* Complete prepping the abort wqe and issue to the FW. */
10623 	abts_wqe = &abtsiocbp->wqe;
10624 	bf_set(abort_cmd_ia, &abts_wqe->abort_cmd, 0);
10625 	bf_set(abort_cmd_criteria, &abts_wqe->abort_cmd, T_XRI_TAG);
10626 
10627 	/* Explicitly set reserved fields to zero.*/
10628 	abts_wqe->abort_cmd.rsrvd4 = 0;
10629 	abts_wqe->abort_cmd.rsrvd5 = 0;
10630 
10631 	/* WQE Common - word 6.  Context is XRI tag.  Set 0. */
10632 	bf_set(wqe_xri_tag, &abts_wqe->abort_cmd.wqe_com, 0);
10633 	bf_set(wqe_ctxt_tag, &abts_wqe->abort_cmd.wqe_com, 0);
10634 
10635 	/* word 7 */
10636 	bf_set(wqe_ct, &abts_wqe->abort_cmd.wqe_com, 0);
10637 	bf_set(wqe_cmnd, &abts_wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
10638 	bf_set(wqe_class, &abts_wqe->abort_cmd.wqe_com,
10639 	       cmdiocb->iocb.ulpClass);
10640 
10641 	/* word 8 - tell the FW to abort the IO associated with this
10642 	 * outstanding exchange ID.
10643 	 */
10644 	abts_wqe->abort_cmd.wqe_com.abort_tag = cmdiocb->sli4_xritag;
10645 
10646 	/* word 9 - this is the iotag for the abts_wqe completion. */
10647 	bf_set(wqe_reqtag, &abts_wqe->abort_cmd.wqe_com,
10648 	       abtsiocbp->iotag);
10649 
10650 	/* word 10 */
10651 	bf_set(wqe_wqid, &abts_wqe->abort_cmd.wqe_com, cmdiocb->hba_wqidx);
10652 	bf_set(wqe_qosd, &abts_wqe->abort_cmd.wqe_com, 1);
10653 	bf_set(wqe_lenloc, &abts_wqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
10654 
10655 	/* word 11 */
10656 	bf_set(wqe_cmd_type, &abts_wqe->abort_cmd.wqe_com, OTHER_COMMAND);
10657 	bf_set(wqe_wqec, &abts_wqe->abort_cmd.wqe_com, 1);
10658 	bf_set(wqe_cqid, &abts_wqe->abort_cmd.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10659 
10660 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
10661 	abtsiocbp->iocb_flag |= LPFC_IO_NVME;
10662 	abtsiocbp->vport = vport;
10663 	abtsiocbp->wqe_cmpl = lpfc_nvme_abort_fcreq_cmpl;
10664 	retval = lpfc_sli4_issue_wqe(phba, LPFC_FCP_RING, abtsiocbp);
10665 	if (retval == IOCB_ERROR) {
10666 		lpfc_printf_vlog(vport, KERN_ERR, LOG_NVME,
10667 				 "6147 Failed abts issue_wqe with status x%x "
10668 				 "for oxid x%x\n",
10669 				 retval, cmdiocb->sli4_xritag);
10670 		lpfc_sli_release_iocbq(phba, abtsiocbp);
10671 		return retval;
10672 	}
10673 
10674 	lpfc_printf_vlog(vport, KERN_ERR, LOG_NVME,
10675 			 "6148 Drv Abort NVME Request Issued for "
10676 			 "ox_id x%x on reqtag x%x\n",
10677 			 cmdiocb->sli4_xritag,
10678 			 abtsiocbp->iotag);
10679 
10680 	return retval;
10681 }
10682 
10683 /**
10684  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
10685  * @phba: pointer to lpfc HBA data structure.
10686  *
10687  * This routine will abort all pending and outstanding iocbs to an HBA.
10688  **/
10689 void
10690 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
10691 {
10692 	struct lpfc_sli *psli = &phba->sli;
10693 	struct lpfc_sli_ring *pring;
10694 	struct lpfc_queue *qp = NULL;
10695 	int i;
10696 
10697 	if (phba->sli_rev != LPFC_SLI_REV4) {
10698 		for (i = 0; i < psli->num_rings; i++) {
10699 			pring = &psli->sli3_ring[i];
10700 			lpfc_sli_abort_iocb_ring(phba, pring);
10701 		}
10702 		return;
10703 	}
10704 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
10705 		pring = qp->pring;
10706 		if (!pring)
10707 			continue;
10708 		lpfc_sli_abort_iocb_ring(phba, pring);
10709 	}
10710 }
10711 
10712 /**
10713  * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
10714  * @iocbq: Pointer to driver iocb object.
10715  * @vport: Pointer to driver virtual port object.
10716  * @tgt_id: SCSI ID of the target.
10717  * @lun_id: LUN ID of the scsi device.
10718  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
10719  *
10720  * This function acts as an iocb filter for functions which abort or count
10721  * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
10722  * 0 if the filtering criteria is met for the given iocb and will return
10723  * 1 if the filtering criteria is not met.
10724  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
10725  * given iocb is for the SCSI device specified by vport, tgt_id and
10726  * lun_id parameter.
10727  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
10728  * given iocb is for the SCSI target specified by vport and tgt_id
10729  * parameters.
10730  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
10731  * given iocb is for the SCSI host associated with the given vport.
10732  * This function is called with no locks held.
10733  **/
10734 static int
10735 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
10736 			   uint16_t tgt_id, uint64_t lun_id,
10737 			   lpfc_ctx_cmd ctx_cmd)
10738 {
10739 	struct lpfc_scsi_buf *lpfc_cmd;
10740 	int rc = 1;
10741 
10742 	if (!(iocbq->iocb_flag &  LPFC_IO_FCP))
10743 		return rc;
10744 
10745 	if (iocbq->vport != vport)
10746 		return rc;
10747 
10748 	lpfc_cmd = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
10749 
10750 	if (lpfc_cmd->pCmd == NULL)
10751 		return rc;
10752 
10753 	switch (ctx_cmd) {
10754 	case LPFC_CTX_LUN:
10755 		if ((lpfc_cmd->rdata->pnode) &&
10756 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
10757 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
10758 			rc = 0;
10759 		break;
10760 	case LPFC_CTX_TGT:
10761 		if ((lpfc_cmd->rdata->pnode) &&
10762 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
10763 			rc = 0;
10764 		break;
10765 	case LPFC_CTX_HOST:
10766 		rc = 0;
10767 		break;
10768 	default:
10769 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
10770 			__func__, ctx_cmd);
10771 		break;
10772 	}
10773 
10774 	return rc;
10775 }
10776 
10777 /**
10778  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
10779  * @vport: Pointer to virtual port.
10780  * @tgt_id: SCSI ID of the target.
10781  * @lun_id: LUN ID of the scsi device.
10782  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10783  *
10784  * This function returns number of FCP commands pending for the vport.
10785  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
10786  * commands pending on the vport associated with SCSI device specified
10787  * by tgt_id and lun_id parameters.
10788  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
10789  * commands pending on the vport associated with SCSI target specified
10790  * by tgt_id parameter.
10791  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
10792  * commands pending on the vport.
10793  * This function returns the number of iocbs which satisfy the filter.
10794  * This function is called without any lock held.
10795  **/
10796 int
10797 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
10798 		  lpfc_ctx_cmd ctx_cmd)
10799 {
10800 	struct lpfc_hba *phba = vport->phba;
10801 	struct lpfc_iocbq *iocbq;
10802 	int sum, i;
10803 
10804 	spin_lock_irq(&phba->hbalock);
10805 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
10806 		iocbq = phba->sli.iocbq_lookup[i];
10807 
10808 		if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
10809 						ctx_cmd) == 0)
10810 			sum++;
10811 	}
10812 	spin_unlock_irq(&phba->hbalock);
10813 
10814 	return sum;
10815 }
10816 
10817 /**
10818  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
10819  * @phba: Pointer to HBA context object
10820  * @cmdiocb: Pointer to command iocb object.
10821  * @rspiocb: Pointer to response iocb object.
10822  *
10823  * This function is called when an aborted FCP iocb completes. This
10824  * function is called by the ring event handler with no lock held.
10825  * This function frees the iocb.
10826  **/
10827 void
10828 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
10829 			struct lpfc_iocbq *rspiocb)
10830 {
10831 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10832 			"3096 ABORT_XRI_CN completing on rpi x%x "
10833 			"original iotag x%x, abort cmd iotag x%x "
10834 			"status 0x%x, reason 0x%x\n",
10835 			cmdiocb->iocb.un.acxri.abortContextTag,
10836 			cmdiocb->iocb.un.acxri.abortIoTag,
10837 			cmdiocb->iotag, rspiocb->iocb.ulpStatus,
10838 			rspiocb->iocb.un.ulpWord[4]);
10839 	lpfc_sli_release_iocbq(phba, cmdiocb);
10840 	return;
10841 }
10842 
10843 /**
10844  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
10845  * @vport: Pointer to virtual port.
10846  * @pring: Pointer to driver SLI ring object.
10847  * @tgt_id: SCSI ID of the target.
10848  * @lun_id: LUN ID of the scsi device.
10849  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10850  *
10851  * This function sends an abort command for every SCSI command
10852  * associated with the given virtual port pending on the ring
10853  * filtered by lpfc_sli_validate_fcp_iocb function.
10854  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
10855  * FCP iocbs associated with lun specified by tgt_id and lun_id
10856  * parameters
10857  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
10858  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
10859  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
10860  * FCP iocbs associated with virtual port.
10861  * This function returns number of iocbs it failed to abort.
10862  * This function is called with no locks held.
10863  **/
10864 int
10865 lpfc_sli_abort_iocb(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
10866 		    uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd abort_cmd)
10867 {
10868 	struct lpfc_hba *phba = vport->phba;
10869 	struct lpfc_iocbq *iocbq;
10870 	struct lpfc_iocbq *abtsiocb;
10871 	IOCB_t *cmd = NULL;
10872 	int errcnt = 0, ret_val = 0;
10873 	int i;
10874 
10875 	for (i = 1; i <= phba->sli.last_iotag; i++) {
10876 		iocbq = phba->sli.iocbq_lookup[i];
10877 
10878 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
10879 					       abort_cmd) != 0)
10880 			continue;
10881 
10882 		/*
10883 		 * If the iocbq is already being aborted, don't take a second
10884 		 * action, but do count it.
10885 		 */
10886 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
10887 			continue;
10888 
10889 		/* issue ABTS for this IOCB based on iotag */
10890 		abtsiocb = lpfc_sli_get_iocbq(phba);
10891 		if (abtsiocb == NULL) {
10892 			errcnt++;
10893 			continue;
10894 		}
10895 
10896 		/* indicate the IO is being aborted by the driver. */
10897 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
10898 
10899 		cmd = &iocbq->iocb;
10900 		abtsiocb->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
10901 		abtsiocb->iocb.un.acxri.abortContextTag = cmd->ulpContext;
10902 		if (phba->sli_rev == LPFC_SLI_REV4)
10903 			abtsiocb->iocb.un.acxri.abortIoTag = iocbq->sli4_xritag;
10904 		else
10905 			abtsiocb->iocb.un.acxri.abortIoTag = cmd->ulpIoTag;
10906 		abtsiocb->iocb.ulpLe = 1;
10907 		abtsiocb->iocb.ulpClass = cmd->ulpClass;
10908 		abtsiocb->vport = vport;
10909 
10910 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
10911 		abtsiocb->hba_wqidx = iocbq->hba_wqidx;
10912 		if (iocbq->iocb_flag & LPFC_IO_FCP)
10913 			abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
10914 		if (iocbq->iocb_flag & LPFC_IO_FOF)
10915 			abtsiocb->iocb_flag |= LPFC_IO_FOF;
10916 
10917 		if (lpfc_is_link_up(phba))
10918 			abtsiocb->iocb.ulpCommand = CMD_ABORT_XRI_CN;
10919 		else
10920 			abtsiocb->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
10921 
10922 		/* Setup callback routine and issue the command. */
10923 		abtsiocb->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
10924 		ret_val = lpfc_sli_issue_iocb(phba, pring->ringno,
10925 					      abtsiocb, 0);
10926 		if (ret_val == IOCB_ERROR) {
10927 			lpfc_sli_release_iocbq(phba, abtsiocb);
10928 			errcnt++;
10929 			continue;
10930 		}
10931 	}
10932 
10933 	return errcnt;
10934 }
10935 
10936 /**
10937  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
10938  * @vport: Pointer to virtual port.
10939  * @pring: Pointer to driver SLI ring object.
10940  * @tgt_id: SCSI ID of the target.
10941  * @lun_id: LUN ID of the scsi device.
10942  * @taskmgmt_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10943  *
10944  * This function sends an abort command for every SCSI command
10945  * associated with the given virtual port pending on the ring
10946  * filtered by lpfc_sli_validate_fcp_iocb function.
10947  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
10948  * FCP iocbs associated with lun specified by tgt_id and lun_id
10949  * parameters
10950  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
10951  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
10952  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
10953  * FCP iocbs associated with virtual port.
10954  * This function returns number of iocbs it aborted .
10955  * This function is called with no locks held right after a taskmgmt
10956  * command is sent.
10957  **/
10958 int
10959 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
10960 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
10961 {
10962 	struct lpfc_hba *phba = vport->phba;
10963 	struct lpfc_scsi_buf *lpfc_cmd;
10964 	struct lpfc_iocbq *abtsiocbq;
10965 	struct lpfc_nodelist *ndlp;
10966 	struct lpfc_iocbq *iocbq;
10967 	IOCB_t *icmd;
10968 	int sum, i, ret_val;
10969 	unsigned long iflags;
10970 	struct lpfc_sli_ring *pring_s4;
10971 
10972 	spin_lock_irq(&phba->hbalock);
10973 
10974 	/* all I/Os are in process of being flushed */
10975 	if (phba->hba_flag & HBA_FCP_IOQ_FLUSH) {
10976 		spin_unlock_irq(&phba->hbalock);
10977 		return 0;
10978 	}
10979 	sum = 0;
10980 
10981 	for (i = 1; i <= phba->sli.last_iotag; i++) {
10982 		iocbq = phba->sli.iocbq_lookup[i];
10983 
10984 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
10985 					       cmd) != 0)
10986 			continue;
10987 
10988 		/*
10989 		 * If the iocbq is already being aborted, don't take a second
10990 		 * action, but do count it.
10991 		 */
10992 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
10993 			continue;
10994 
10995 		/* issue ABTS for this IOCB based on iotag */
10996 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
10997 		if (abtsiocbq == NULL)
10998 			continue;
10999 
11000 		icmd = &iocbq->iocb;
11001 		abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
11002 		abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
11003 		if (phba->sli_rev == LPFC_SLI_REV4)
11004 			abtsiocbq->iocb.un.acxri.abortIoTag =
11005 							 iocbq->sli4_xritag;
11006 		else
11007 			abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
11008 		abtsiocbq->iocb.ulpLe = 1;
11009 		abtsiocbq->iocb.ulpClass = icmd->ulpClass;
11010 		abtsiocbq->vport = vport;
11011 
11012 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11013 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
11014 		if (iocbq->iocb_flag & LPFC_IO_FCP)
11015 			abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
11016 		if (iocbq->iocb_flag & LPFC_IO_FOF)
11017 			abtsiocbq->iocb_flag |= LPFC_IO_FOF;
11018 
11019 		lpfc_cmd = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
11020 		ndlp = lpfc_cmd->rdata->pnode;
11021 
11022 		if (lpfc_is_link_up(phba) &&
11023 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
11024 			abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
11025 		else
11026 			abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
11027 
11028 		/* Setup callback routine and issue the command. */
11029 		abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
11030 
11031 		/*
11032 		 * Indicate the IO is being aborted by the driver and set
11033 		 * the caller's flag into the aborted IO.
11034 		 */
11035 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
11036 
11037 		if (phba->sli_rev == LPFC_SLI_REV4) {
11038 			pring_s4 = lpfc_sli4_calc_ring(phba, iocbq);
11039 			if (pring_s4 == NULL)
11040 				continue;
11041 			/* Note: both hbalock and ring_lock must be set here */
11042 			spin_lock_irqsave(&pring_s4->ring_lock, iflags);
11043 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
11044 							abtsiocbq, 0);
11045 			spin_unlock_irqrestore(&pring_s4->ring_lock, iflags);
11046 		} else {
11047 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
11048 							abtsiocbq, 0);
11049 		}
11050 
11051 
11052 		if (ret_val == IOCB_ERROR)
11053 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
11054 		else
11055 			sum++;
11056 	}
11057 	spin_unlock_irq(&phba->hbalock);
11058 	return sum;
11059 }
11060 
11061 /**
11062  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
11063  * @phba: Pointer to HBA context object.
11064  * @cmdiocbq: Pointer to command iocb.
11065  * @rspiocbq: Pointer to response iocb.
11066  *
11067  * This function is the completion handler for iocbs issued using
11068  * lpfc_sli_issue_iocb_wait function. This function is called by the
11069  * ring event handler function without any lock held. This function
11070  * can be called from both worker thread context and interrupt
11071  * context. This function also can be called from other thread which
11072  * cleans up the SLI layer objects.
11073  * This function copy the contents of the response iocb to the
11074  * response iocb memory object provided by the caller of
11075  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
11076  * sleeps for the iocb completion.
11077  **/
11078 static void
11079 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
11080 			struct lpfc_iocbq *cmdiocbq,
11081 			struct lpfc_iocbq *rspiocbq)
11082 {
11083 	wait_queue_head_t *pdone_q;
11084 	unsigned long iflags;
11085 	struct lpfc_scsi_buf *lpfc_cmd;
11086 
11087 	spin_lock_irqsave(&phba->hbalock, iflags);
11088 	if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
11089 
11090 		/*
11091 		 * A time out has occurred for the iocb.  If a time out
11092 		 * completion handler has been supplied, call it.  Otherwise,
11093 		 * just free the iocbq.
11094 		 */
11095 
11096 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11097 		cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
11098 		cmdiocbq->wait_iocb_cmpl = NULL;
11099 		if (cmdiocbq->iocb_cmpl)
11100 			(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
11101 		else
11102 			lpfc_sli_release_iocbq(phba, cmdiocbq);
11103 		return;
11104 	}
11105 
11106 	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
11107 	if (cmdiocbq->context2 && rspiocbq)
11108 		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
11109 		       &rspiocbq->iocb, sizeof(IOCB_t));
11110 
11111 	/* Set the exchange busy flag for task management commands */
11112 	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
11113 		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
11114 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_scsi_buf,
11115 			cur_iocbq);
11116 		lpfc_cmd->exch_busy = rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY;
11117 	}
11118 
11119 	pdone_q = cmdiocbq->context_un.wait_queue;
11120 	if (pdone_q)
11121 		wake_up(pdone_q);
11122 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11123 	return;
11124 }
11125 
11126 /**
11127  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
11128  * @phba: Pointer to HBA context object..
11129  * @piocbq: Pointer to command iocb.
11130  * @flag: Flag to test.
11131  *
11132  * This routine grabs the hbalock and then test the iocb_flag to
11133  * see if the passed in flag is set.
11134  * Returns:
11135  * 1 if flag is set.
11136  * 0 if flag is not set.
11137  **/
11138 static int
11139 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
11140 		 struct lpfc_iocbq *piocbq, uint32_t flag)
11141 {
11142 	unsigned long iflags;
11143 	int ret;
11144 
11145 	spin_lock_irqsave(&phba->hbalock, iflags);
11146 	ret = piocbq->iocb_flag & flag;
11147 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11148 	return ret;
11149 
11150 }
11151 
11152 /**
11153  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
11154  * @phba: Pointer to HBA context object..
11155  * @pring: Pointer to sli ring.
11156  * @piocb: Pointer to command iocb.
11157  * @prspiocbq: Pointer to response iocb.
11158  * @timeout: Timeout in number of seconds.
11159  *
11160  * This function issues the iocb to firmware and waits for the
11161  * iocb to complete. The iocb_cmpl field of the shall be used
11162  * to handle iocbs which time out. If the field is NULL, the
11163  * function shall free the iocbq structure.  If more clean up is
11164  * needed, the caller is expected to provide a completion function
11165  * that will provide the needed clean up.  If the iocb command is
11166  * not completed within timeout seconds, the function will either
11167  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
11168  * completion function set in the iocb_cmpl field and then return
11169  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
11170  * resources if this function returns IOCB_TIMEDOUT.
11171  * The function waits for the iocb completion using an
11172  * non-interruptible wait.
11173  * This function will sleep while waiting for iocb completion.
11174  * So, this function should not be called from any context which
11175  * does not allow sleeping. Due to the same reason, this function
11176  * cannot be called with interrupt disabled.
11177  * This function assumes that the iocb completions occur while
11178  * this function sleep. So, this function cannot be called from
11179  * the thread which process iocb completion for this ring.
11180  * This function clears the iocb_flag of the iocb object before
11181  * issuing the iocb and the iocb completion handler sets this
11182  * flag and wakes this thread when the iocb completes.
11183  * The contents of the response iocb will be copied to prspiocbq
11184  * by the completion handler when the command completes.
11185  * This function returns IOCB_SUCCESS when success.
11186  * This function is called with no lock held.
11187  **/
11188 int
11189 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
11190 			 uint32_t ring_number,
11191 			 struct lpfc_iocbq *piocb,
11192 			 struct lpfc_iocbq *prspiocbq,
11193 			 uint32_t timeout)
11194 {
11195 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
11196 	long timeleft, timeout_req = 0;
11197 	int retval = IOCB_SUCCESS;
11198 	uint32_t creg_val;
11199 	struct lpfc_iocbq *iocb;
11200 	int txq_cnt = 0;
11201 	int txcmplq_cnt = 0;
11202 	struct lpfc_sli_ring *pring;
11203 	unsigned long iflags;
11204 	bool iocb_completed = true;
11205 
11206 	if (phba->sli_rev >= LPFC_SLI_REV4)
11207 		pring = lpfc_sli4_calc_ring(phba, piocb);
11208 	else
11209 		pring = &phba->sli.sli3_ring[ring_number];
11210 	/*
11211 	 * If the caller has provided a response iocbq buffer, then context2
11212 	 * is NULL or its an error.
11213 	 */
11214 	if (prspiocbq) {
11215 		if (piocb->context2)
11216 			return IOCB_ERROR;
11217 		piocb->context2 = prspiocbq;
11218 	}
11219 
11220 	piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
11221 	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
11222 	piocb->context_un.wait_queue = &done_q;
11223 	piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
11224 
11225 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
11226 		if (lpfc_readl(phba->HCregaddr, &creg_val))
11227 			return IOCB_ERROR;
11228 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
11229 		writel(creg_val, phba->HCregaddr);
11230 		readl(phba->HCregaddr); /* flush */
11231 	}
11232 
11233 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
11234 				     SLI_IOCB_RET_IOCB);
11235 	if (retval == IOCB_SUCCESS) {
11236 		timeout_req = msecs_to_jiffies(timeout * 1000);
11237 		timeleft = wait_event_timeout(done_q,
11238 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
11239 				timeout_req);
11240 		spin_lock_irqsave(&phba->hbalock, iflags);
11241 		if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
11242 
11243 			/*
11244 			 * IOCB timed out.  Inform the wake iocb wait
11245 			 * completion function and set local status
11246 			 */
11247 
11248 			iocb_completed = false;
11249 			piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
11250 		}
11251 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11252 		if (iocb_completed) {
11253 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11254 					"0331 IOCB wake signaled\n");
11255 			/* Note: we are not indicating if the IOCB has a success
11256 			 * status or not - that's for the caller to check.
11257 			 * IOCB_SUCCESS means just that the command was sent and
11258 			 * completed. Not that it completed successfully.
11259 			 * */
11260 		} else if (timeleft == 0) {
11261 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11262 					"0338 IOCB wait timeout error - no "
11263 					"wake response Data x%x\n", timeout);
11264 			retval = IOCB_TIMEDOUT;
11265 		} else {
11266 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11267 					"0330 IOCB wake NOT set, "
11268 					"Data x%x x%lx\n",
11269 					timeout, (timeleft / jiffies));
11270 			retval = IOCB_TIMEDOUT;
11271 		}
11272 	} else if (retval == IOCB_BUSY) {
11273 		if (phba->cfg_log_verbose & LOG_SLI) {
11274 			list_for_each_entry(iocb, &pring->txq, list) {
11275 				txq_cnt++;
11276 			}
11277 			list_for_each_entry(iocb, &pring->txcmplq, list) {
11278 				txcmplq_cnt++;
11279 			}
11280 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11281 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
11282 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
11283 		}
11284 		return retval;
11285 	} else {
11286 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11287 				"0332 IOCB wait issue failed, Data x%x\n",
11288 				retval);
11289 		retval = IOCB_ERROR;
11290 	}
11291 
11292 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
11293 		if (lpfc_readl(phba->HCregaddr, &creg_val))
11294 			return IOCB_ERROR;
11295 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
11296 		writel(creg_val, phba->HCregaddr);
11297 		readl(phba->HCregaddr); /* flush */
11298 	}
11299 
11300 	if (prspiocbq)
11301 		piocb->context2 = NULL;
11302 
11303 	piocb->context_un.wait_queue = NULL;
11304 	piocb->iocb_cmpl = NULL;
11305 	return retval;
11306 }
11307 
11308 /**
11309  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
11310  * @phba: Pointer to HBA context object.
11311  * @pmboxq: Pointer to driver mailbox object.
11312  * @timeout: Timeout in number of seconds.
11313  *
11314  * This function issues the mailbox to firmware and waits for the
11315  * mailbox command to complete. If the mailbox command is not
11316  * completed within timeout seconds, it returns MBX_TIMEOUT.
11317  * The function waits for the mailbox completion using an
11318  * interruptible wait. If the thread is woken up due to a
11319  * signal, MBX_TIMEOUT error is returned to the caller. Caller
11320  * should not free the mailbox resources, if this function returns
11321  * MBX_TIMEOUT.
11322  * This function will sleep while waiting for mailbox completion.
11323  * So, this function should not be called from any context which
11324  * does not allow sleeping. Due to the same reason, this function
11325  * cannot be called with interrupt disabled.
11326  * This function assumes that the mailbox completion occurs while
11327  * this function sleep. So, this function cannot be called from
11328  * the worker thread which processes mailbox completion.
11329  * This function is called in the context of HBA management
11330  * applications.
11331  * This function returns MBX_SUCCESS when successful.
11332  * This function is called with no lock held.
11333  **/
11334 int
11335 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
11336 			 uint32_t timeout)
11337 {
11338 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
11339 	MAILBOX_t *mb = NULL;
11340 	int retval;
11341 	unsigned long flag;
11342 
11343 	/* The caller might set context1 for extended buffer */
11344 	if (pmboxq->context1)
11345 		mb = (MAILBOX_t *)pmboxq->context1;
11346 
11347 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
11348 	/* setup wake call as IOCB callback */
11349 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
11350 	/* setup context field to pass wait_queue pointer to wake function  */
11351 	pmboxq->context1 = &done_q;
11352 
11353 	/* now issue the command */
11354 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
11355 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
11356 		wait_event_interruptible_timeout(done_q,
11357 				pmboxq->mbox_flag & LPFC_MBX_WAKE,
11358 				msecs_to_jiffies(timeout * 1000));
11359 
11360 		spin_lock_irqsave(&phba->hbalock, flag);
11361 		/* restore the possible extended buffer for free resource */
11362 		pmboxq->context1 = (uint8_t *)mb;
11363 		/*
11364 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
11365 		 * else do not free the resources.
11366 		 */
11367 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
11368 			retval = MBX_SUCCESS;
11369 		} else {
11370 			retval = MBX_TIMEOUT;
11371 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
11372 		}
11373 		spin_unlock_irqrestore(&phba->hbalock, flag);
11374 	} else {
11375 		/* restore the possible extended buffer for free resource */
11376 		pmboxq->context1 = (uint8_t *)mb;
11377 	}
11378 
11379 	return retval;
11380 }
11381 
11382 /**
11383  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
11384  * @phba: Pointer to HBA context.
11385  *
11386  * This function is called to shutdown the driver's mailbox sub-system.
11387  * It first marks the mailbox sub-system is in a block state to prevent
11388  * the asynchronous mailbox command from issued off the pending mailbox
11389  * command queue. If the mailbox command sub-system shutdown is due to
11390  * HBA error conditions such as EEH or ERATT, this routine shall invoke
11391  * the mailbox sub-system flush routine to forcefully bring down the
11392  * mailbox sub-system. Otherwise, if it is due to normal condition (such
11393  * as with offline or HBA function reset), this routine will wait for the
11394  * outstanding mailbox command to complete before invoking the mailbox
11395  * sub-system flush routine to gracefully bring down mailbox sub-system.
11396  **/
11397 void
11398 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
11399 {
11400 	struct lpfc_sli *psli = &phba->sli;
11401 	unsigned long timeout;
11402 
11403 	if (mbx_action == LPFC_MBX_NO_WAIT) {
11404 		/* delay 100ms for port state */
11405 		msleep(100);
11406 		lpfc_sli_mbox_sys_flush(phba);
11407 		return;
11408 	}
11409 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
11410 
11411 	spin_lock_irq(&phba->hbalock);
11412 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
11413 
11414 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
11415 		/* Determine how long we might wait for the active mailbox
11416 		 * command to be gracefully completed by firmware.
11417 		 */
11418 		if (phba->sli.mbox_active)
11419 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
11420 						phba->sli.mbox_active) *
11421 						1000) + jiffies;
11422 		spin_unlock_irq(&phba->hbalock);
11423 
11424 		while (phba->sli.mbox_active) {
11425 			/* Check active mailbox complete status every 2ms */
11426 			msleep(2);
11427 			if (time_after(jiffies, timeout))
11428 				/* Timeout, let the mailbox flush routine to
11429 				 * forcefully release active mailbox command
11430 				 */
11431 				break;
11432 		}
11433 	} else
11434 		spin_unlock_irq(&phba->hbalock);
11435 
11436 	lpfc_sli_mbox_sys_flush(phba);
11437 }
11438 
11439 /**
11440  * lpfc_sli_eratt_read - read sli-3 error attention events
11441  * @phba: Pointer to HBA context.
11442  *
11443  * This function is called to read the SLI3 device error attention registers
11444  * for possible error attention events. The caller must hold the hostlock
11445  * with spin_lock_irq().
11446  *
11447  * This function returns 1 when there is Error Attention in the Host Attention
11448  * Register and returns 0 otherwise.
11449  **/
11450 static int
11451 lpfc_sli_eratt_read(struct lpfc_hba *phba)
11452 {
11453 	uint32_t ha_copy;
11454 
11455 	/* Read chip Host Attention (HA) register */
11456 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
11457 		goto unplug_err;
11458 
11459 	if (ha_copy & HA_ERATT) {
11460 		/* Read host status register to retrieve error event */
11461 		if (lpfc_sli_read_hs(phba))
11462 			goto unplug_err;
11463 
11464 		/* Check if there is a deferred error condition is active */
11465 		if ((HS_FFER1 & phba->work_hs) &&
11466 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
11467 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
11468 			phba->hba_flag |= DEFER_ERATT;
11469 			/* Clear all interrupt enable conditions */
11470 			writel(0, phba->HCregaddr);
11471 			readl(phba->HCregaddr);
11472 		}
11473 
11474 		/* Set the driver HA work bitmap */
11475 		phba->work_ha |= HA_ERATT;
11476 		/* Indicate polling handles this ERATT */
11477 		phba->hba_flag |= HBA_ERATT_HANDLED;
11478 		return 1;
11479 	}
11480 	return 0;
11481 
11482 unplug_err:
11483 	/* Set the driver HS work bitmap */
11484 	phba->work_hs |= UNPLUG_ERR;
11485 	/* Set the driver HA work bitmap */
11486 	phba->work_ha |= HA_ERATT;
11487 	/* Indicate polling handles this ERATT */
11488 	phba->hba_flag |= HBA_ERATT_HANDLED;
11489 	return 1;
11490 }
11491 
11492 /**
11493  * lpfc_sli4_eratt_read - read sli-4 error attention events
11494  * @phba: Pointer to HBA context.
11495  *
11496  * This function is called to read the SLI4 device error attention registers
11497  * for possible error attention events. The caller must hold the hostlock
11498  * with spin_lock_irq().
11499  *
11500  * This function returns 1 when there is Error Attention in the Host Attention
11501  * Register and returns 0 otherwise.
11502  **/
11503 static int
11504 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
11505 {
11506 	uint32_t uerr_sta_hi, uerr_sta_lo;
11507 	uint32_t if_type, portsmphr;
11508 	struct lpfc_register portstat_reg;
11509 
11510 	/*
11511 	 * For now, use the SLI4 device internal unrecoverable error
11512 	 * registers for error attention. This can be changed later.
11513 	 */
11514 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11515 	switch (if_type) {
11516 	case LPFC_SLI_INTF_IF_TYPE_0:
11517 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
11518 			&uerr_sta_lo) ||
11519 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
11520 			&uerr_sta_hi)) {
11521 			phba->work_hs |= UNPLUG_ERR;
11522 			phba->work_ha |= HA_ERATT;
11523 			phba->hba_flag |= HBA_ERATT_HANDLED;
11524 			return 1;
11525 		}
11526 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
11527 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
11528 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11529 					"1423 HBA Unrecoverable error: "
11530 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
11531 					"ue_mask_lo_reg=0x%x, "
11532 					"ue_mask_hi_reg=0x%x\n",
11533 					uerr_sta_lo, uerr_sta_hi,
11534 					phba->sli4_hba.ue_mask_lo,
11535 					phba->sli4_hba.ue_mask_hi);
11536 			phba->work_status[0] = uerr_sta_lo;
11537 			phba->work_status[1] = uerr_sta_hi;
11538 			phba->work_ha |= HA_ERATT;
11539 			phba->hba_flag |= HBA_ERATT_HANDLED;
11540 			return 1;
11541 		}
11542 		break;
11543 	case LPFC_SLI_INTF_IF_TYPE_2:
11544 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
11545 			&portstat_reg.word0) ||
11546 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
11547 			&portsmphr)){
11548 			phba->work_hs |= UNPLUG_ERR;
11549 			phba->work_ha |= HA_ERATT;
11550 			phba->hba_flag |= HBA_ERATT_HANDLED;
11551 			return 1;
11552 		}
11553 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
11554 			phba->work_status[0] =
11555 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
11556 			phba->work_status[1] =
11557 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
11558 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11559 					"2885 Port Status Event: "
11560 					"port status reg 0x%x, "
11561 					"port smphr reg 0x%x, "
11562 					"error 1=0x%x, error 2=0x%x\n",
11563 					portstat_reg.word0,
11564 					portsmphr,
11565 					phba->work_status[0],
11566 					phba->work_status[1]);
11567 			phba->work_ha |= HA_ERATT;
11568 			phba->hba_flag |= HBA_ERATT_HANDLED;
11569 			return 1;
11570 		}
11571 		break;
11572 	case LPFC_SLI_INTF_IF_TYPE_1:
11573 	default:
11574 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11575 				"2886 HBA Error Attention on unsupported "
11576 				"if type %d.", if_type);
11577 		return 1;
11578 	}
11579 
11580 	return 0;
11581 }
11582 
11583 /**
11584  * lpfc_sli_check_eratt - check error attention events
11585  * @phba: Pointer to HBA context.
11586  *
11587  * This function is called from timer soft interrupt context to check HBA's
11588  * error attention register bit for error attention events.
11589  *
11590  * This function returns 1 when there is Error Attention in the Host Attention
11591  * Register and returns 0 otherwise.
11592  **/
11593 int
11594 lpfc_sli_check_eratt(struct lpfc_hba *phba)
11595 {
11596 	uint32_t ha_copy;
11597 
11598 	/* If somebody is waiting to handle an eratt, don't process it
11599 	 * here. The brdkill function will do this.
11600 	 */
11601 	if (phba->link_flag & LS_IGNORE_ERATT)
11602 		return 0;
11603 
11604 	/* Check if interrupt handler handles this ERATT */
11605 	spin_lock_irq(&phba->hbalock);
11606 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
11607 		/* Interrupt handler has handled ERATT */
11608 		spin_unlock_irq(&phba->hbalock);
11609 		return 0;
11610 	}
11611 
11612 	/*
11613 	 * If there is deferred error attention, do not check for error
11614 	 * attention
11615 	 */
11616 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11617 		spin_unlock_irq(&phba->hbalock);
11618 		return 0;
11619 	}
11620 
11621 	/* If PCI channel is offline, don't process it */
11622 	if (unlikely(pci_channel_offline(phba->pcidev))) {
11623 		spin_unlock_irq(&phba->hbalock);
11624 		return 0;
11625 	}
11626 
11627 	switch (phba->sli_rev) {
11628 	case LPFC_SLI_REV2:
11629 	case LPFC_SLI_REV3:
11630 		/* Read chip Host Attention (HA) register */
11631 		ha_copy = lpfc_sli_eratt_read(phba);
11632 		break;
11633 	case LPFC_SLI_REV4:
11634 		/* Read device Uncoverable Error (UERR) registers */
11635 		ha_copy = lpfc_sli4_eratt_read(phba);
11636 		break;
11637 	default:
11638 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11639 				"0299 Invalid SLI revision (%d)\n",
11640 				phba->sli_rev);
11641 		ha_copy = 0;
11642 		break;
11643 	}
11644 	spin_unlock_irq(&phba->hbalock);
11645 
11646 	return ha_copy;
11647 }
11648 
11649 /**
11650  * lpfc_intr_state_check - Check device state for interrupt handling
11651  * @phba: Pointer to HBA context.
11652  *
11653  * This inline routine checks whether a device or its PCI slot is in a state
11654  * that the interrupt should be handled.
11655  *
11656  * This function returns 0 if the device or the PCI slot is in a state that
11657  * interrupt should be handled, otherwise -EIO.
11658  */
11659 static inline int
11660 lpfc_intr_state_check(struct lpfc_hba *phba)
11661 {
11662 	/* If the pci channel is offline, ignore all the interrupts */
11663 	if (unlikely(pci_channel_offline(phba->pcidev)))
11664 		return -EIO;
11665 
11666 	/* Update device level interrupt statistics */
11667 	phba->sli.slistat.sli_intr++;
11668 
11669 	/* Ignore all interrupts during initialization. */
11670 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
11671 		return -EIO;
11672 
11673 	return 0;
11674 }
11675 
11676 /**
11677  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
11678  * @irq: Interrupt number.
11679  * @dev_id: The device context pointer.
11680  *
11681  * This function is directly called from the PCI layer as an interrupt
11682  * service routine when device with SLI-3 interface spec is enabled with
11683  * MSI-X multi-message interrupt mode and there are slow-path events in
11684  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
11685  * interrupt mode, this function is called as part of the device-level
11686  * interrupt handler. When the PCI slot is in error recovery or the HBA
11687  * is undergoing initialization, the interrupt handler will not process
11688  * the interrupt. The link attention and ELS ring attention events are
11689  * handled by the worker thread. The interrupt handler signals the worker
11690  * thread and returns for these events. This function is called without
11691  * any lock held. It gets the hbalock to access and update SLI data
11692  * structures.
11693  *
11694  * This function returns IRQ_HANDLED when interrupt is handled else it
11695  * returns IRQ_NONE.
11696  **/
11697 irqreturn_t
11698 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
11699 {
11700 	struct lpfc_hba  *phba;
11701 	uint32_t ha_copy, hc_copy;
11702 	uint32_t work_ha_copy;
11703 	unsigned long status;
11704 	unsigned long iflag;
11705 	uint32_t control;
11706 
11707 	MAILBOX_t *mbox, *pmbox;
11708 	struct lpfc_vport *vport;
11709 	struct lpfc_nodelist *ndlp;
11710 	struct lpfc_dmabuf *mp;
11711 	LPFC_MBOXQ_t *pmb;
11712 	int rc;
11713 
11714 	/*
11715 	 * Get the driver's phba structure from the dev_id and
11716 	 * assume the HBA is not interrupting.
11717 	 */
11718 	phba = (struct lpfc_hba *)dev_id;
11719 
11720 	if (unlikely(!phba))
11721 		return IRQ_NONE;
11722 
11723 	/*
11724 	 * Stuff needs to be attented to when this function is invoked as an
11725 	 * individual interrupt handler in MSI-X multi-message interrupt mode
11726 	 */
11727 	if (phba->intr_type == MSIX) {
11728 		/* Check device state for handling interrupt */
11729 		if (lpfc_intr_state_check(phba))
11730 			return IRQ_NONE;
11731 		/* Need to read HA REG for slow-path events */
11732 		spin_lock_irqsave(&phba->hbalock, iflag);
11733 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
11734 			goto unplug_error;
11735 		/* If somebody is waiting to handle an eratt don't process it
11736 		 * here. The brdkill function will do this.
11737 		 */
11738 		if (phba->link_flag & LS_IGNORE_ERATT)
11739 			ha_copy &= ~HA_ERATT;
11740 		/* Check the need for handling ERATT in interrupt handler */
11741 		if (ha_copy & HA_ERATT) {
11742 			if (phba->hba_flag & HBA_ERATT_HANDLED)
11743 				/* ERATT polling has handled ERATT */
11744 				ha_copy &= ~HA_ERATT;
11745 			else
11746 				/* Indicate interrupt handler handles ERATT */
11747 				phba->hba_flag |= HBA_ERATT_HANDLED;
11748 		}
11749 
11750 		/*
11751 		 * If there is deferred error attention, do not check for any
11752 		 * interrupt.
11753 		 */
11754 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11755 			spin_unlock_irqrestore(&phba->hbalock, iflag);
11756 			return IRQ_NONE;
11757 		}
11758 
11759 		/* Clear up only attention source related to slow-path */
11760 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
11761 			goto unplug_error;
11762 
11763 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
11764 			HC_LAINT_ENA | HC_ERINT_ENA),
11765 			phba->HCregaddr);
11766 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
11767 			phba->HAregaddr);
11768 		writel(hc_copy, phba->HCregaddr);
11769 		readl(phba->HAregaddr); /* flush */
11770 		spin_unlock_irqrestore(&phba->hbalock, iflag);
11771 	} else
11772 		ha_copy = phba->ha_copy;
11773 
11774 	work_ha_copy = ha_copy & phba->work_ha_mask;
11775 
11776 	if (work_ha_copy) {
11777 		if (work_ha_copy & HA_LATT) {
11778 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
11779 				/*
11780 				 * Turn off Link Attention interrupts
11781 				 * until CLEAR_LA done
11782 				 */
11783 				spin_lock_irqsave(&phba->hbalock, iflag);
11784 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
11785 				if (lpfc_readl(phba->HCregaddr, &control))
11786 					goto unplug_error;
11787 				control &= ~HC_LAINT_ENA;
11788 				writel(control, phba->HCregaddr);
11789 				readl(phba->HCregaddr); /* flush */
11790 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11791 			}
11792 			else
11793 				work_ha_copy &= ~HA_LATT;
11794 		}
11795 
11796 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
11797 			/*
11798 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
11799 			 * the only slow ring.
11800 			 */
11801 			status = (work_ha_copy &
11802 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
11803 			status >>= (4*LPFC_ELS_RING);
11804 			if (status & HA_RXMASK) {
11805 				spin_lock_irqsave(&phba->hbalock, iflag);
11806 				if (lpfc_readl(phba->HCregaddr, &control))
11807 					goto unplug_error;
11808 
11809 				lpfc_debugfs_slow_ring_trc(phba,
11810 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
11811 				control, status,
11812 				(uint32_t)phba->sli.slistat.sli_intr);
11813 
11814 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
11815 					lpfc_debugfs_slow_ring_trc(phba,
11816 						"ISR Disable ring:"
11817 						"pwork:x%x hawork:x%x wait:x%x",
11818 						phba->work_ha, work_ha_copy,
11819 						(uint32_t)((unsigned long)
11820 						&phba->work_waitq));
11821 
11822 					control &=
11823 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
11824 					writel(control, phba->HCregaddr);
11825 					readl(phba->HCregaddr); /* flush */
11826 				}
11827 				else {
11828 					lpfc_debugfs_slow_ring_trc(phba,
11829 						"ISR slow ring:   pwork:"
11830 						"x%x hawork:x%x wait:x%x",
11831 						phba->work_ha, work_ha_copy,
11832 						(uint32_t)((unsigned long)
11833 						&phba->work_waitq));
11834 				}
11835 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11836 			}
11837 		}
11838 		spin_lock_irqsave(&phba->hbalock, iflag);
11839 		if (work_ha_copy & HA_ERATT) {
11840 			if (lpfc_sli_read_hs(phba))
11841 				goto unplug_error;
11842 			/*
11843 			 * Check if there is a deferred error condition
11844 			 * is active
11845 			 */
11846 			if ((HS_FFER1 & phba->work_hs) &&
11847 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
11848 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
11849 				  phba->work_hs)) {
11850 				phba->hba_flag |= DEFER_ERATT;
11851 				/* Clear all interrupt enable conditions */
11852 				writel(0, phba->HCregaddr);
11853 				readl(phba->HCregaddr);
11854 			}
11855 		}
11856 
11857 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
11858 			pmb = phba->sli.mbox_active;
11859 			pmbox = &pmb->u.mb;
11860 			mbox = phba->mbox;
11861 			vport = pmb->vport;
11862 
11863 			/* First check out the status word */
11864 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
11865 			if (pmbox->mbxOwner != OWN_HOST) {
11866 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11867 				/*
11868 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
11869 				 * mbxStatus <status>
11870 				 */
11871 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11872 						LOG_SLI,
11873 						"(%d):0304 Stray Mailbox "
11874 						"Interrupt mbxCommand x%x "
11875 						"mbxStatus x%x\n",
11876 						(vport ? vport->vpi : 0),
11877 						pmbox->mbxCommand,
11878 						pmbox->mbxStatus);
11879 				/* clear mailbox attention bit */
11880 				work_ha_copy &= ~HA_MBATT;
11881 			} else {
11882 				phba->sli.mbox_active = NULL;
11883 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11884 				phba->last_completion_time = jiffies;
11885 				del_timer(&phba->sli.mbox_tmo);
11886 				if (pmb->mbox_cmpl) {
11887 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
11888 							MAILBOX_CMD_SIZE);
11889 					if (pmb->out_ext_byte_len &&
11890 						pmb->context2)
11891 						lpfc_sli_pcimem_bcopy(
11892 						phba->mbox_ext,
11893 						pmb->context2,
11894 						pmb->out_ext_byte_len);
11895 				}
11896 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
11897 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
11898 
11899 					lpfc_debugfs_disc_trc(vport,
11900 						LPFC_DISC_TRC_MBOX_VPORT,
11901 						"MBOX dflt rpi: : "
11902 						"status:x%x rpi:x%x",
11903 						(uint32_t)pmbox->mbxStatus,
11904 						pmbox->un.varWords[0], 0);
11905 
11906 					if (!pmbox->mbxStatus) {
11907 						mp = (struct lpfc_dmabuf *)
11908 							(pmb->context1);
11909 						ndlp = (struct lpfc_nodelist *)
11910 							pmb->context2;
11911 
11912 						/* Reg_LOGIN of dflt RPI was
11913 						 * successful. new lets get
11914 						 * rid of the RPI using the
11915 						 * same mbox buffer.
11916 						 */
11917 						lpfc_unreg_login(phba,
11918 							vport->vpi,
11919 							pmbox->un.varWords[0],
11920 							pmb);
11921 						pmb->mbox_cmpl =
11922 							lpfc_mbx_cmpl_dflt_rpi;
11923 						pmb->context1 = mp;
11924 						pmb->context2 = ndlp;
11925 						pmb->vport = vport;
11926 						rc = lpfc_sli_issue_mbox(phba,
11927 								pmb,
11928 								MBX_NOWAIT);
11929 						if (rc != MBX_BUSY)
11930 							lpfc_printf_log(phba,
11931 							KERN_ERR,
11932 							LOG_MBOX | LOG_SLI,
11933 							"0350 rc should have"
11934 							"been MBX_BUSY\n");
11935 						if (rc != MBX_NOT_FINISHED)
11936 							goto send_current_mbox;
11937 					}
11938 				}
11939 				spin_lock_irqsave(
11940 						&phba->pport->work_port_lock,
11941 						iflag);
11942 				phba->pport->work_port_events &=
11943 					~WORKER_MBOX_TMO;
11944 				spin_unlock_irqrestore(
11945 						&phba->pport->work_port_lock,
11946 						iflag);
11947 				lpfc_mbox_cmpl_put(phba, pmb);
11948 			}
11949 		} else
11950 			spin_unlock_irqrestore(&phba->hbalock, iflag);
11951 
11952 		if ((work_ha_copy & HA_MBATT) &&
11953 		    (phba->sli.mbox_active == NULL)) {
11954 send_current_mbox:
11955 			/* Process next mailbox command if there is one */
11956 			do {
11957 				rc = lpfc_sli_issue_mbox(phba, NULL,
11958 							 MBX_NOWAIT);
11959 			} while (rc == MBX_NOT_FINISHED);
11960 			if (rc != MBX_SUCCESS)
11961 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11962 						LOG_SLI, "0349 rc should be "
11963 						"MBX_SUCCESS\n");
11964 		}
11965 
11966 		spin_lock_irqsave(&phba->hbalock, iflag);
11967 		phba->work_ha |= work_ha_copy;
11968 		spin_unlock_irqrestore(&phba->hbalock, iflag);
11969 		lpfc_worker_wake_up(phba);
11970 	}
11971 	return IRQ_HANDLED;
11972 unplug_error:
11973 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11974 	return IRQ_HANDLED;
11975 
11976 } /* lpfc_sli_sp_intr_handler */
11977 
11978 /**
11979  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
11980  * @irq: Interrupt number.
11981  * @dev_id: The device context pointer.
11982  *
11983  * This function is directly called from the PCI layer as an interrupt
11984  * service routine when device with SLI-3 interface spec is enabled with
11985  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
11986  * ring event in the HBA. However, when the device is enabled with either
11987  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
11988  * device-level interrupt handler. When the PCI slot is in error recovery
11989  * or the HBA is undergoing initialization, the interrupt handler will not
11990  * process the interrupt. The SCSI FCP fast-path ring event are handled in
11991  * the intrrupt context. This function is called without any lock held.
11992  * It gets the hbalock to access and update SLI data structures.
11993  *
11994  * This function returns IRQ_HANDLED when interrupt is handled else it
11995  * returns IRQ_NONE.
11996  **/
11997 irqreturn_t
11998 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
11999 {
12000 	struct lpfc_hba  *phba;
12001 	uint32_t ha_copy;
12002 	unsigned long status;
12003 	unsigned long iflag;
12004 	struct lpfc_sli_ring *pring;
12005 
12006 	/* Get the driver's phba structure from the dev_id and
12007 	 * assume the HBA is not interrupting.
12008 	 */
12009 	phba = (struct lpfc_hba *) dev_id;
12010 
12011 	if (unlikely(!phba))
12012 		return IRQ_NONE;
12013 
12014 	/*
12015 	 * Stuff needs to be attented to when this function is invoked as an
12016 	 * individual interrupt handler in MSI-X multi-message interrupt mode
12017 	 */
12018 	if (phba->intr_type == MSIX) {
12019 		/* Check device state for handling interrupt */
12020 		if (lpfc_intr_state_check(phba))
12021 			return IRQ_NONE;
12022 		/* Need to read HA REG for FCP ring and other ring events */
12023 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
12024 			return IRQ_HANDLED;
12025 		/* Clear up only attention source related to fast-path */
12026 		spin_lock_irqsave(&phba->hbalock, iflag);
12027 		/*
12028 		 * If there is deferred error attention, do not check for
12029 		 * any interrupt.
12030 		 */
12031 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12032 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12033 			return IRQ_NONE;
12034 		}
12035 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
12036 			phba->HAregaddr);
12037 		readl(phba->HAregaddr); /* flush */
12038 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12039 	} else
12040 		ha_copy = phba->ha_copy;
12041 
12042 	/*
12043 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
12044 	 */
12045 	ha_copy &= ~(phba->work_ha_mask);
12046 
12047 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
12048 	status >>= (4*LPFC_FCP_RING);
12049 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12050 	if (status & HA_RXMASK)
12051 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
12052 
12053 	if (phba->cfg_multi_ring_support == 2) {
12054 		/*
12055 		 * Process all events on extra ring. Take the optimized path
12056 		 * for extra ring IO.
12057 		 */
12058 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
12059 		status >>= (4*LPFC_EXTRA_RING);
12060 		if (status & HA_RXMASK) {
12061 			lpfc_sli_handle_fast_ring_event(phba,
12062 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
12063 					status);
12064 		}
12065 	}
12066 	return IRQ_HANDLED;
12067 }  /* lpfc_sli_fp_intr_handler */
12068 
12069 /**
12070  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
12071  * @irq: Interrupt number.
12072  * @dev_id: The device context pointer.
12073  *
12074  * This function is the HBA device-level interrupt handler to device with
12075  * SLI-3 interface spec, called from the PCI layer when either MSI or
12076  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
12077  * requires driver attention. This function invokes the slow-path interrupt
12078  * attention handling function and fast-path interrupt attention handling
12079  * function in turn to process the relevant HBA attention events. This
12080  * function is called without any lock held. It gets the hbalock to access
12081  * and update SLI data structures.
12082  *
12083  * This function returns IRQ_HANDLED when interrupt is handled, else it
12084  * returns IRQ_NONE.
12085  **/
12086 irqreturn_t
12087 lpfc_sli_intr_handler(int irq, void *dev_id)
12088 {
12089 	struct lpfc_hba  *phba;
12090 	irqreturn_t sp_irq_rc, fp_irq_rc;
12091 	unsigned long status1, status2;
12092 	uint32_t hc_copy;
12093 
12094 	/*
12095 	 * Get the driver's phba structure from the dev_id and
12096 	 * assume the HBA is not interrupting.
12097 	 */
12098 	phba = (struct lpfc_hba *) dev_id;
12099 
12100 	if (unlikely(!phba))
12101 		return IRQ_NONE;
12102 
12103 	/* Check device state for handling interrupt */
12104 	if (lpfc_intr_state_check(phba))
12105 		return IRQ_NONE;
12106 
12107 	spin_lock(&phba->hbalock);
12108 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
12109 		spin_unlock(&phba->hbalock);
12110 		return IRQ_HANDLED;
12111 	}
12112 
12113 	if (unlikely(!phba->ha_copy)) {
12114 		spin_unlock(&phba->hbalock);
12115 		return IRQ_NONE;
12116 	} else if (phba->ha_copy & HA_ERATT) {
12117 		if (phba->hba_flag & HBA_ERATT_HANDLED)
12118 			/* ERATT polling has handled ERATT */
12119 			phba->ha_copy &= ~HA_ERATT;
12120 		else
12121 			/* Indicate interrupt handler handles ERATT */
12122 			phba->hba_flag |= HBA_ERATT_HANDLED;
12123 	}
12124 
12125 	/*
12126 	 * If there is deferred error attention, do not check for any interrupt.
12127 	 */
12128 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12129 		spin_unlock(&phba->hbalock);
12130 		return IRQ_NONE;
12131 	}
12132 
12133 	/* Clear attention sources except link and error attentions */
12134 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
12135 		spin_unlock(&phba->hbalock);
12136 		return IRQ_HANDLED;
12137 	}
12138 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
12139 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
12140 		phba->HCregaddr);
12141 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
12142 	writel(hc_copy, phba->HCregaddr);
12143 	readl(phba->HAregaddr); /* flush */
12144 	spin_unlock(&phba->hbalock);
12145 
12146 	/*
12147 	 * Invokes slow-path host attention interrupt handling as appropriate.
12148 	 */
12149 
12150 	/* status of events with mailbox and link attention */
12151 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
12152 
12153 	/* status of events with ELS ring */
12154 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
12155 	status2 >>= (4*LPFC_ELS_RING);
12156 
12157 	if (status1 || (status2 & HA_RXMASK))
12158 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
12159 	else
12160 		sp_irq_rc = IRQ_NONE;
12161 
12162 	/*
12163 	 * Invoke fast-path host attention interrupt handling as appropriate.
12164 	 */
12165 
12166 	/* status of events with FCP ring */
12167 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
12168 	status1 >>= (4*LPFC_FCP_RING);
12169 
12170 	/* status of events with extra ring */
12171 	if (phba->cfg_multi_ring_support == 2) {
12172 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
12173 		status2 >>= (4*LPFC_EXTRA_RING);
12174 	} else
12175 		status2 = 0;
12176 
12177 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
12178 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
12179 	else
12180 		fp_irq_rc = IRQ_NONE;
12181 
12182 	/* Return device-level interrupt handling status */
12183 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
12184 }  /* lpfc_sli_intr_handler */
12185 
12186 /**
12187  * lpfc_sli4_fcp_xri_abort_event_proc - Process fcp xri abort event
12188  * @phba: pointer to lpfc hba data structure.
12189  *
12190  * This routine is invoked by the worker thread to process all the pending
12191  * SLI4 FCP abort XRI events.
12192  **/
12193 void lpfc_sli4_fcp_xri_abort_event_proc(struct lpfc_hba *phba)
12194 {
12195 	struct lpfc_cq_event *cq_event;
12196 
12197 	/* First, declare the fcp xri abort event has been handled */
12198 	spin_lock_irq(&phba->hbalock);
12199 	phba->hba_flag &= ~FCP_XRI_ABORT_EVENT;
12200 	spin_unlock_irq(&phba->hbalock);
12201 	/* Now, handle all the fcp xri abort events */
12202 	while (!list_empty(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue)) {
12203 		/* Get the first event from the head of the event queue */
12204 		spin_lock_irq(&phba->hbalock);
12205 		list_remove_head(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue,
12206 				 cq_event, struct lpfc_cq_event, list);
12207 		spin_unlock_irq(&phba->hbalock);
12208 		/* Notify aborted XRI for FCP work queue */
12209 		lpfc_sli4_fcp_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
12210 		/* Free the event processed back to the free pool */
12211 		lpfc_sli4_cq_event_release(phba, cq_event);
12212 	}
12213 }
12214 
12215 /**
12216  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
12217  * @phba: pointer to lpfc hba data structure.
12218  *
12219  * This routine is invoked by the worker thread to process all the pending
12220  * SLI4 els abort xri events.
12221  **/
12222 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
12223 {
12224 	struct lpfc_cq_event *cq_event;
12225 
12226 	/* First, declare the els xri abort event has been handled */
12227 	spin_lock_irq(&phba->hbalock);
12228 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
12229 	spin_unlock_irq(&phba->hbalock);
12230 	/* Now, handle all the els xri abort events */
12231 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
12232 		/* Get the first event from the head of the event queue */
12233 		spin_lock_irq(&phba->hbalock);
12234 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
12235 				 cq_event, struct lpfc_cq_event, list);
12236 		spin_unlock_irq(&phba->hbalock);
12237 		/* Notify aborted XRI for ELS work queue */
12238 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
12239 		/* Free the event processed back to the free pool */
12240 		lpfc_sli4_cq_event_release(phba, cq_event);
12241 	}
12242 }
12243 
12244 /**
12245  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
12246  * @phba: pointer to lpfc hba data structure
12247  * @pIocbIn: pointer to the rspiocbq
12248  * @pIocbOut: pointer to the cmdiocbq
12249  * @wcqe: pointer to the complete wcqe
12250  *
12251  * This routine transfers the fields of a command iocbq to a response iocbq
12252  * by copying all the IOCB fields from command iocbq and transferring the
12253  * completion status information from the complete wcqe.
12254  **/
12255 static void
12256 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
12257 			      struct lpfc_iocbq *pIocbIn,
12258 			      struct lpfc_iocbq *pIocbOut,
12259 			      struct lpfc_wcqe_complete *wcqe)
12260 {
12261 	int numBdes, i;
12262 	unsigned long iflags;
12263 	uint32_t status, max_response;
12264 	struct lpfc_dmabuf *dmabuf;
12265 	struct ulp_bde64 *bpl, bde;
12266 	size_t offset = offsetof(struct lpfc_iocbq, iocb);
12267 
12268 	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
12269 	       sizeof(struct lpfc_iocbq) - offset);
12270 	/* Map WCQE parameters into irspiocb parameters */
12271 	status = bf_get(lpfc_wcqe_c_status, wcqe);
12272 	pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
12273 	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
12274 		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
12275 			pIocbIn->iocb.un.fcpi.fcpi_parm =
12276 					pIocbOut->iocb.un.fcpi.fcpi_parm -
12277 					wcqe->total_data_placed;
12278 		else
12279 			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
12280 	else {
12281 		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
12282 		switch (pIocbOut->iocb.ulpCommand) {
12283 		case CMD_ELS_REQUEST64_CR:
12284 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
12285 			bpl  = (struct ulp_bde64 *)dmabuf->virt;
12286 			bde.tus.w = le32_to_cpu(bpl[1].tus.w);
12287 			max_response = bde.tus.f.bdeSize;
12288 			break;
12289 		case CMD_GEN_REQUEST64_CR:
12290 			max_response = 0;
12291 			if (!pIocbOut->context3)
12292 				break;
12293 			numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
12294 					sizeof(struct ulp_bde64);
12295 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
12296 			bpl = (struct ulp_bde64 *)dmabuf->virt;
12297 			for (i = 0; i < numBdes; i++) {
12298 				bde.tus.w = le32_to_cpu(bpl[i].tus.w);
12299 				if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
12300 					max_response += bde.tus.f.bdeSize;
12301 			}
12302 			break;
12303 		default:
12304 			max_response = wcqe->total_data_placed;
12305 			break;
12306 		}
12307 		if (max_response < wcqe->total_data_placed)
12308 			pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
12309 		else
12310 			pIocbIn->iocb.un.genreq64.bdl.bdeSize =
12311 				wcqe->total_data_placed;
12312 	}
12313 
12314 	/* Convert BG errors for completion status */
12315 	if (status == CQE_STATUS_DI_ERROR) {
12316 		pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
12317 
12318 		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
12319 			pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
12320 		else
12321 			pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
12322 
12323 		pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
12324 		if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
12325 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
12326 				BGS_GUARD_ERR_MASK;
12327 		if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
12328 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
12329 				BGS_APPTAG_ERR_MASK;
12330 		if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
12331 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
12332 				BGS_REFTAG_ERR_MASK;
12333 
12334 		/* Check to see if there was any good data before the error */
12335 		if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
12336 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
12337 				BGS_HI_WATER_MARK_PRESENT_MASK;
12338 			pIocbIn->iocb.unsli3.sli3_bg.bghm =
12339 				wcqe->total_data_placed;
12340 		}
12341 
12342 		/*
12343 		* Set ALL the error bits to indicate we don't know what
12344 		* type of error it is.
12345 		*/
12346 		if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
12347 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
12348 				(BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
12349 				BGS_GUARD_ERR_MASK);
12350 	}
12351 
12352 	/* Pick up HBA exchange busy condition */
12353 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
12354 		spin_lock_irqsave(&phba->hbalock, iflags);
12355 		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
12356 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12357 	}
12358 }
12359 
12360 /**
12361  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
12362  * @phba: Pointer to HBA context object.
12363  * @wcqe: Pointer to work-queue completion queue entry.
12364  *
12365  * This routine handles an ELS work-queue completion event and construct
12366  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
12367  * discovery engine to handle.
12368  *
12369  * Return: Pointer to the receive IOCBQ, NULL otherwise.
12370  **/
12371 static struct lpfc_iocbq *
12372 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
12373 			       struct lpfc_iocbq *irspiocbq)
12374 {
12375 	struct lpfc_sli_ring *pring;
12376 	struct lpfc_iocbq *cmdiocbq;
12377 	struct lpfc_wcqe_complete *wcqe;
12378 	unsigned long iflags;
12379 
12380 	pring = lpfc_phba_elsring(phba);
12381 
12382 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
12383 	spin_lock_irqsave(&pring->ring_lock, iflags);
12384 	pring->stats.iocb_event++;
12385 	/* Look up the ELS command IOCB and create pseudo response IOCB */
12386 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
12387 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12388 	/* Put the iocb back on the txcmplq */
12389 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
12390 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
12391 
12392 	if (unlikely(!cmdiocbq)) {
12393 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12394 				"0386 ELS complete with no corresponding "
12395 				"cmdiocb: iotag (%d)\n",
12396 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12397 		lpfc_sli_release_iocbq(phba, irspiocbq);
12398 		return NULL;
12399 	}
12400 
12401 	/* Fake the irspiocbq and copy necessary response information */
12402 	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
12403 
12404 	return irspiocbq;
12405 }
12406 
12407 /**
12408  * lpfc_sli4_sp_handle_async_event - Handle an asynchroous event
12409  * @phba: Pointer to HBA context object.
12410  * @cqe: Pointer to mailbox completion queue entry.
12411  *
12412  * This routine process a mailbox completion queue entry with asynchrous
12413  * event.
12414  *
12415  * Return: true if work posted to worker thread, otherwise false.
12416  **/
12417 static bool
12418 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
12419 {
12420 	struct lpfc_cq_event *cq_event;
12421 	unsigned long iflags;
12422 
12423 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12424 			"0392 Async Event: word0:x%x, word1:x%x, "
12425 			"word2:x%x, word3:x%x\n", mcqe->word0,
12426 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
12427 
12428 	/* Allocate a new internal CQ_EVENT entry */
12429 	cq_event = lpfc_sli4_cq_event_alloc(phba);
12430 	if (!cq_event) {
12431 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12432 				"0394 Failed to allocate CQ_EVENT entry\n");
12433 		return false;
12434 	}
12435 
12436 	/* Move the CQE into an asynchronous event entry */
12437 	memcpy(&cq_event->cqe, mcqe, sizeof(struct lpfc_mcqe));
12438 	spin_lock_irqsave(&phba->hbalock, iflags);
12439 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
12440 	/* Set the async event flag */
12441 	phba->hba_flag |= ASYNC_EVENT;
12442 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12443 
12444 	return true;
12445 }
12446 
12447 /**
12448  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
12449  * @phba: Pointer to HBA context object.
12450  * @cqe: Pointer to mailbox completion queue entry.
12451  *
12452  * This routine process a mailbox completion queue entry with mailbox
12453  * completion event.
12454  *
12455  * Return: true if work posted to worker thread, otherwise false.
12456  **/
12457 static bool
12458 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
12459 {
12460 	uint32_t mcqe_status;
12461 	MAILBOX_t *mbox, *pmbox;
12462 	struct lpfc_mqe *mqe;
12463 	struct lpfc_vport *vport;
12464 	struct lpfc_nodelist *ndlp;
12465 	struct lpfc_dmabuf *mp;
12466 	unsigned long iflags;
12467 	LPFC_MBOXQ_t *pmb;
12468 	bool workposted = false;
12469 	int rc;
12470 
12471 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
12472 	if (!bf_get(lpfc_trailer_completed, mcqe))
12473 		goto out_no_mqe_complete;
12474 
12475 	/* Get the reference to the active mbox command */
12476 	spin_lock_irqsave(&phba->hbalock, iflags);
12477 	pmb = phba->sli.mbox_active;
12478 	if (unlikely(!pmb)) {
12479 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
12480 				"1832 No pending MBOX command to handle\n");
12481 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12482 		goto out_no_mqe_complete;
12483 	}
12484 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12485 	mqe = &pmb->u.mqe;
12486 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
12487 	mbox = phba->mbox;
12488 	vport = pmb->vport;
12489 
12490 	/* Reset heartbeat timer */
12491 	phba->last_completion_time = jiffies;
12492 	del_timer(&phba->sli.mbox_tmo);
12493 
12494 	/* Move mbox data to caller's mailbox region, do endian swapping */
12495 	if (pmb->mbox_cmpl && mbox)
12496 		lpfc_sli_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
12497 
12498 	/*
12499 	 * For mcqe errors, conditionally move a modified error code to
12500 	 * the mbox so that the error will not be missed.
12501 	 */
12502 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
12503 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
12504 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
12505 			bf_set(lpfc_mqe_status, mqe,
12506 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
12507 	}
12508 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
12509 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
12510 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
12511 				      "MBOX dflt rpi: status:x%x rpi:x%x",
12512 				      mcqe_status,
12513 				      pmbox->un.varWords[0], 0);
12514 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
12515 			mp = (struct lpfc_dmabuf *)(pmb->context1);
12516 			ndlp = (struct lpfc_nodelist *)pmb->context2;
12517 			/* Reg_LOGIN of dflt RPI was successful. Now lets get
12518 			 * RID of the PPI using the same mbox buffer.
12519 			 */
12520 			lpfc_unreg_login(phba, vport->vpi,
12521 					 pmbox->un.varWords[0], pmb);
12522 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
12523 			pmb->context1 = mp;
12524 			pmb->context2 = ndlp;
12525 			pmb->vport = vport;
12526 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
12527 			if (rc != MBX_BUSY)
12528 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
12529 						LOG_SLI, "0385 rc should "
12530 						"have been MBX_BUSY\n");
12531 			if (rc != MBX_NOT_FINISHED)
12532 				goto send_current_mbox;
12533 		}
12534 	}
12535 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
12536 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
12537 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
12538 
12539 	/* There is mailbox completion work to do */
12540 	spin_lock_irqsave(&phba->hbalock, iflags);
12541 	__lpfc_mbox_cmpl_put(phba, pmb);
12542 	phba->work_ha |= HA_MBATT;
12543 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12544 	workposted = true;
12545 
12546 send_current_mbox:
12547 	spin_lock_irqsave(&phba->hbalock, iflags);
12548 	/* Release the mailbox command posting token */
12549 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
12550 	/* Setting active mailbox pointer need to be in sync to flag clear */
12551 	phba->sli.mbox_active = NULL;
12552 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12553 	/* Wake up worker thread to post the next pending mailbox command */
12554 	lpfc_worker_wake_up(phba);
12555 out_no_mqe_complete:
12556 	if (bf_get(lpfc_trailer_consumed, mcqe))
12557 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
12558 	return workposted;
12559 }
12560 
12561 /**
12562  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
12563  * @phba: Pointer to HBA context object.
12564  * @cqe: Pointer to mailbox completion queue entry.
12565  *
12566  * This routine process a mailbox completion queue entry, it invokes the
12567  * proper mailbox complete handling or asynchrous event handling routine
12568  * according to the MCQE's async bit.
12569  *
12570  * Return: true if work posted to worker thread, otherwise false.
12571  **/
12572 static bool
12573 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_cqe *cqe)
12574 {
12575 	struct lpfc_mcqe mcqe;
12576 	bool workposted;
12577 
12578 	/* Copy the mailbox MCQE and convert endian order as needed */
12579 	lpfc_sli_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
12580 
12581 	/* Invoke the proper event handling routine */
12582 	if (!bf_get(lpfc_trailer_async, &mcqe))
12583 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
12584 	else
12585 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
12586 	return workposted;
12587 }
12588 
12589 /**
12590  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
12591  * @phba: Pointer to HBA context object.
12592  * @cq: Pointer to associated CQ
12593  * @wcqe: Pointer to work-queue completion queue entry.
12594  *
12595  * This routine handles an ELS work-queue completion event.
12596  *
12597  * Return: true if work posted to worker thread, otherwise false.
12598  **/
12599 static bool
12600 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12601 			     struct lpfc_wcqe_complete *wcqe)
12602 {
12603 	struct lpfc_iocbq *irspiocbq;
12604 	unsigned long iflags;
12605 	struct lpfc_sli_ring *pring = cq->pring;
12606 	int txq_cnt = 0;
12607 	int txcmplq_cnt = 0;
12608 	int fcp_txcmplq_cnt = 0;
12609 
12610 	/* Get an irspiocbq for later ELS response processing use */
12611 	irspiocbq = lpfc_sli_get_iocbq(phba);
12612 	if (!irspiocbq) {
12613 		if (!list_empty(&pring->txq))
12614 			txq_cnt++;
12615 		if (!list_empty(&pring->txcmplq))
12616 			txcmplq_cnt++;
12617 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12618 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
12619 			"fcp_txcmplq_cnt=%d, els_txcmplq_cnt=%d\n",
12620 			txq_cnt, phba->iocb_cnt,
12621 			fcp_txcmplq_cnt,
12622 			txcmplq_cnt);
12623 		return false;
12624 	}
12625 
12626 	/* Save off the slow-path queue event for work thread to process */
12627 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
12628 	spin_lock_irqsave(&phba->hbalock, iflags);
12629 	list_add_tail(&irspiocbq->cq_event.list,
12630 		      &phba->sli4_hba.sp_queue_event);
12631 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
12632 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12633 
12634 	return true;
12635 }
12636 
12637 /**
12638  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
12639  * @phba: Pointer to HBA context object.
12640  * @wcqe: Pointer to work-queue completion queue entry.
12641  *
12642  * This routine handles slow-path WQ entry consumed event by invoking the
12643  * proper WQ release routine to the slow-path WQ.
12644  **/
12645 static void
12646 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
12647 			     struct lpfc_wcqe_release *wcqe)
12648 {
12649 	/* sanity check on queue memory */
12650 	if (unlikely(!phba->sli4_hba.els_wq))
12651 		return;
12652 	/* Check for the slow-path ELS work queue */
12653 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
12654 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
12655 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
12656 	else
12657 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12658 				"2579 Slow-path wqe consume event carries "
12659 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
12660 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
12661 				phba->sli4_hba.els_wq->queue_id);
12662 }
12663 
12664 /**
12665  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
12666  * @phba: Pointer to HBA context object.
12667  * @cq: Pointer to a WQ completion queue.
12668  * @wcqe: Pointer to work-queue completion queue entry.
12669  *
12670  * This routine handles an XRI abort event.
12671  *
12672  * Return: true if work posted to worker thread, otherwise false.
12673  **/
12674 static bool
12675 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
12676 				   struct lpfc_queue *cq,
12677 				   struct sli4_wcqe_xri_aborted *wcqe)
12678 {
12679 	bool workposted = false;
12680 	struct lpfc_cq_event *cq_event;
12681 	unsigned long iflags;
12682 
12683 	/* Allocate a new internal CQ_EVENT entry */
12684 	cq_event = lpfc_sli4_cq_event_alloc(phba);
12685 	if (!cq_event) {
12686 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12687 				"0602 Failed to allocate CQ_EVENT entry\n");
12688 		return false;
12689 	}
12690 
12691 	/* Move the CQE into the proper xri abort event list */
12692 	memcpy(&cq_event->cqe, wcqe, sizeof(struct sli4_wcqe_xri_aborted));
12693 	switch (cq->subtype) {
12694 	case LPFC_FCP:
12695 		spin_lock_irqsave(&phba->hbalock, iflags);
12696 		list_add_tail(&cq_event->list,
12697 			      &phba->sli4_hba.sp_fcp_xri_aborted_work_queue);
12698 		/* Set the fcp xri abort event flag */
12699 		phba->hba_flag |= FCP_XRI_ABORT_EVENT;
12700 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12701 		workposted = true;
12702 		break;
12703 	case LPFC_ELS:
12704 		spin_lock_irqsave(&phba->hbalock, iflags);
12705 		list_add_tail(&cq_event->list,
12706 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
12707 		/* Set the els xri abort event flag */
12708 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
12709 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12710 		workposted = true;
12711 		break;
12712 	default:
12713 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12714 				"0603 Invalid work queue CQE subtype (x%x)\n",
12715 				cq->subtype);
12716 		workposted = false;
12717 		break;
12718 	}
12719 	return workposted;
12720 }
12721 
12722 /**
12723  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
12724  * @phba: Pointer to HBA context object.
12725  * @rcqe: Pointer to receive-queue completion queue entry.
12726  *
12727  * This routine process a receive-queue completion queue entry.
12728  *
12729  * Return: true if work posted to worker thread, otherwise false.
12730  **/
12731 static bool
12732 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
12733 {
12734 	bool workposted = false;
12735 	struct fc_frame_header *fc_hdr;
12736 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
12737 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
12738 	struct hbq_dmabuf *dma_buf;
12739 	uint32_t status, rq_id;
12740 	unsigned long iflags;
12741 
12742 	/* sanity check on queue memory */
12743 	if (unlikely(!hrq) || unlikely(!drq))
12744 		return workposted;
12745 
12746 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
12747 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
12748 	else
12749 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
12750 	if (rq_id != hrq->queue_id)
12751 		goto out;
12752 
12753 	status = bf_get(lpfc_rcqe_status, rcqe);
12754 	switch (status) {
12755 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
12756 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12757 				"2537 Receive Frame Truncated!!\n");
12758 		hrq->RQ_buf_trunc++;
12759 	case FC_STATUS_RQ_SUCCESS:
12760 		lpfc_sli4_rq_release(hrq, drq);
12761 		spin_lock_irqsave(&phba->hbalock, iflags);
12762 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
12763 		if (!dma_buf) {
12764 			hrq->RQ_no_buf_found++;
12765 			spin_unlock_irqrestore(&phba->hbalock, iflags);
12766 			goto out;
12767 		}
12768 		hrq->RQ_rcv_buf++;
12769 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
12770 
12771 		/* If a NVME LS event (type 0x28), treat it as Fast path */
12772 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
12773 
12774 		/* save off the frame for the word thread to process */
12775 		list_add_tail(&dma_buf->cq_event.list,
12776 			      &phba->sli4_hba.sp_queue_event);
12777 		/* Frame received */
12778 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
12779 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12780 		workposted = true;
12781 		break;
12782 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
12783 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
12784 		hrq->RQ_no_posted_buf++;
12785 		/* Post more buffers if possible */
12786 		spin_lock_irqsave(&phba->hbalock, iflags);
12787 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
12788 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12789 		workposted = true;
12790 		break;
12791 	}
12792 out:
12793 	return workposted;
12794 }
12795 
12796 /**
12797  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
12798  * @phba: Pointer to HBA context object.
12799  * @cq: Pointer to the completion queue.
12800  * @wcqe: Pointer to a completion queue entry.
12801  *
12802  * This routine process a slow-path work-queue or receive queue completion queue
12803  * entry.
12804  *
12805  * Return: true if work posted to worker thread, otherwise false.
12806  **/
12807 static bool
12808 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12809 			 struct lpfc_cqe *cqe)
12810 {
12811 	struct lpfc_cqe cqevt;
12812 	bool workposted = false;
12813 
12814 	/* Copy the work queue CQE and convert endian order if needed */
12815 	lpfc_sli_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
12816 
12817 	/* Check and process for different type of WCQE and dispatch */
12818 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
12819 	case CQE_CODE_COMPL_WQE:
12820 		/* Process the WQ/RQ complete event */
12821 		phba->last_completion_time = jiffies;
12822 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
12823 				(struct lpfc_wcqe_complete *)&cqevt);
12824 		break;
12825 	case CQE_CODE_RELEASE_WQE:
12826 		/* Process the WQ release event */
12827 		lpfc_sli4_sp_handle_rel_wcqe(phba,
12828 				(struct lpfc_wcqe_release *)&cqevt);
12829 		break;
12830 	case CQE_CODE_XRI_ABORTED:
12831 		/* Process the WQ XRI abort event */
12832 		phba->last_completion_time = jiffies;
12833 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
12834 				(struct sli4_wcqe_xri_aborted *)&cqevt);
12835 		break;
12836 	case CQE_CODE_RECEIVE:
12837 	case CQE_CODE_RECEIVE_V1:
12838 		/* Process the RQ event */
12839 		phba->last_completion_time = jiffies;
12840 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
12841 				(struct lpfc_rcqe *)&cqevt);
12842 		break;
12843 	default:
12844 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12845 				"0388 Not a valid WCQE code: x%x\n",
12846 				bf_get(lpfc_cqe_code, &cqevt));
12847 		break;
12848 	}
12849 	return workposted;
12850 }
12851 
12852 /**
12853  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
12854  * @phba: Pointer to HBA context object.
12855  * @eqe: Pointer to fast-path event queue entry.
12856  *
12857  * This routine process a event queue entry from the slow-path event queue.
12858  * It will check the MajorCode and MinorCode to determine this is for a
12859  * completion event on a completion queue, if not, an error shall be logged
12860  * and just return. Otherwise, it will get to the corresponding completion
12861  * queue and process all the entries on that completion queue, rearm the
12862  * completion queue, and then return.
12863  *
12864  **/
12865 static void
12866 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
12867 	struct lpfc_queue *speq)
12868 {
12869 	struct lpfc_queue *cq = NULL, *childq;
12870 	struct lpfc_cqe *cqe;
12871 	bool workposted = false;
12872 	int ecount = 0;
12873 	uint16_t cqid;
12874 
12875 	/* Get the reference to the corresponding CQ */
12876 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
12877 
12878 	list_for_each_entry(childq, &speq->child_list, list) {
12879 		if (childq->queue_id == cqid) {
12880 			cq = childq;
12881 			break;
12882 		}
12883 	}
12884 	if (unlikely(!cq)) {
12885 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
12886 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12887 					"0365 Slow-path CQ identifier "
12888 					"(%d) does not exist\n", cqid);
12889 		return;
12890 	}
12891 
12892 	/* Save EQ associated with this CQ */
12893 	cq->assoc_qp = speq;
12894 
12895 	/* Process all the entries to the CQ */
12896 	switch (cq->type) {
12897 	case LPFC_MCQ:
12898 		while ((cqe = lpfc_sli4_cq_get(cq))) {
12899 			workposted |= lpfc_sli4_sp_handle_mcqe(phba, cqe);
12900 			if (!(++ecount % cq->entry_repost))
12901 				lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12902 			cq->CQ_mbox++;
12903 		}
12904 		break;
12905 	case LPFC_WCQ:
12906 		while ((cqe = lpfc_sli4_cq_get(cq))) {
12907 			if ((cq->subtype == LPFC_FCP) ||
12908 			    (cq->subtype == LPFC_NVME))
12909 				workposted |= lpfc_sli4_fp_handle_cqe(phba, cq,
12910 								       cqe);
12911 			else
12912 				workposted |= lpfc_sli4_sp_handle_cqe(phba, cq,
12913 								      cqe);
12914 			if (!(++ecount % cq->entry_repost))
12915 				lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12916 		}
12917 
12918 		/* Track the max number of CQEs processed in 1 EQ */
12919 		if (ecount > cq->CQ_max_cqe)
12920 			cq->CQ_max_cqe = ecount;
12921 		break;
12922 	default:
12923 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12924 				"0370 Invalid completion queue type (%d)\n",
12925 				cq->type);
12926 		return;
12927 	}
12928 
12929 	/* Catch the no cq entry condition, log an error */
12930 	if (unlikely(ecount == 0))
12931 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12932 				"0371 No entry from the CQ: identifier "
12933 				"(x%x), type (%d)\n", cq->queue_id, cq->type);
12934 
12935 	/* In any case, flash and re-arm the RCQ */
12936 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
12937 
12938 	/* wake up worker thread if there are works to be done */
12939 	if (workposted)
12940 		lpfc_worker_wake_up(phba);
12941 }
12942 
12943 /**
12944  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
12945  * @phba: Pointer to HBA context object.
12946  * @cq: Pointer to associated CQ
12947  * @wcqe: Pointer to work-queue completion queue entry.
12948  *
12949  * This routine process a fast-path work queue completion entry from fast-path
12950  * event queue for FCP command response completion.
12951  **/
12952 static void
12953 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12954 			     struct lpfc_wcqe_complete *wcqe)
12955 {
12956 	struct lpfc_sli_ring *pring = cq->pring;
12957 	struct lpfc_iocbq *cmdiocbq;
12958 	struct lpfc_iocbq irspiocbq;
12959 	unsigned long iflags;
12960 
12961 	/* Check for response status */
12962 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
12963 		/* If resource errors reported from HBA, reduce queue
12964 		 * depth of the SCSI device.
12965 		 */
12966 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
12967 		     IOSTAT_LOCAL_REJECT)) &&
12968 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
12969 		     IOERR_NO_RESOURCES))
12970 			phba->lpfc_rampdown_queue_depth(phba);
12971 
12972 		/* Log the error status */
12973 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12974 				"0373 FCP complete error: status=x%x, "
12975 				"hw_status=x%x, total_data_specified=%d, "
12976 				"parameter=x%x, word3=x%x\n",
12977 				bf_get(lpfc_wcqe_c_status, wcqe),
12978 				bf_get(lpfc_wcqe_c_hw_status, wcqe),
12979 				wcqe->total_data_placed, wcqe->parameter,
12980 				wcqe->word3);
12981 	}
12982 
12983 	/* Look up the FCP command IOCB and create pseudo response IOCB */
12984 	spin_lock_irqsave(&pring->ring_lock, iflags);
12985 	pring->stats.iocb_event++;
12986 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
12987 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12988 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
12989 	if (unlikely(!cmdiocbq)) {
12990 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12991 				"0374 FCP complete with no corresponding "
12992 				"cmdiocb: iotag (%d)\n",
12993 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12994 		return;
12995 	}
12996 
12997 	if (cq->assoc_qp)
12998 		cmdiocbq->isr_timestamp =
12999 			cq->assoc_qp->isr_timestamp;
13000 
13001 	if (cmdiocbq->iocb_cmpl == NULL) {
13002 		if (cmdiocbq->wqe_cmpl) {
13003 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
13004 				spin_lock_irqsave(&phba->hbalock, iflags);
13005 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
13006 				spin_unlock_irqrestore(&phba->hbalock, iflags);
13007 			}
13008 
13009 			/* Pass the cmd_iocb and the wcqe to the upper layer */
13010 			(cmdiocbq->wqe_cmpl)(phba, cmdiocbq, wcqe);
13011 			return;
13012 		}
13013 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13014 				"0375 FCP cmdiocb not callback function "
13015 				"iotag: (%d)\n",
13016 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13017 		return;
13018 	}
13019 
13020 	/* Fake the irspiocb and copy necessary response information */
13021 	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
13022 
13023 	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
13024 		spin_lock_irqsave(&phba->hbalock, iflags);
13025 		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
13026 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13027 	}
13028 
13029 	/* Pass the cmd_iocb and the rsp state to the upper layer */
13030 	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
13031 }
13032 
13033 /**
13034  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
13035  * @phba: Pointer to HBA context object.
13036  * @cq: Pointer to completion queue.
13037  * @wcqe: Pointer to work-queue completion queue entry.
13038  *
13039  * This routine handles an fast-path WQ entry consumed event by invoking the
13040  * proper WQ release routine to the slow-path WQ.
13041  **/
13042 static void
13043 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13044 			     struct lpfc_wcqe_release *wcqe)
13045 {
13046 	struct lpfc_queue *childwq;
13047 	bool wqid_matched = false;
13048 	uint16_t hba_wqid;
13049 
13050 	/* Check for fast-path FCP work queue release */
13051 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
13052 	list_for_each_entry(childwq, &cq->child_list, list) {
13053 		if (childwq->queue_id == hba_wqid) {
13054 			lpfc_sli4_wq_release(childwq,
13055 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
13056 			wqid_matched = true;
13057 			break;
13058 		}
13059 	}
13060 	/* Report warning log message if no match found */
13061 	if (wqid_matched != true)
13062 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13063 				"2580 Fast-path wqe consume event carries "
13064 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
13065 }
13066 
13067 /**
13068  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
13069  * @phba: Pointer to HBA context object.
13070  * @rcqe: Pointer to receive-queue completion queue entry.
13071  *
13072  * This routine process a receive-queue completion queue entry.
13073  *
13074  * Return: true if work posted to worker thread, otherwise false.
13075  **/
13076 static bool
13077 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13078 			    struct lpfc_rcqe *rcqe)
13079 {
13080 	bool workposted = false;
13081 	struct lpfc_queue *hrq;
13082 	struct lpfc_queue *drq;
13083 	struct rqb_dmabuf *dma_buf;
13084 	struct fc_frame_header *fc_hdr;
13085 	uint32_t status, rq_id;
13086 	unsigned long iflags;
13087 	uint32_t fctl, idx;
13088 
13089 	if ((phba->nvmet_support == 0) ||
13090 	    (phba->sli4_hba.nvmet_cqset == NULL))
13091 		return workposted;
13092 
13093 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
13094 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
13095 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
13096 
13097 	/* sanity check on queue memory */
13098 	if (unlikely(!hrq) || unlikely(!drq))
13099 		return workposted;
13100 
13101 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
13102 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
13103 	else
13104 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
13105 
13106 	if ((phba->nvmet_support == 0) ||
13107 	    (rq_id != hrq->queue_id))
13108 		return workposted;
13109 
13110 	status = bf_get(lpfc_rcqe_status, rcqe);
13111 	switch (status) {
13112 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
13113 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13114 				"6126 Receive Frame Truncated!!\n");
13115 		hrq->RQ_buf_trunc++;
13116 		break;
13117 	case FC_STATUS_RQ_SUCCESS:
13118 		lpfc_sli4_rq_release(hrq, drq);
13119 		spin_lock_irqsave(&phba->hbalock, iflags);
13120 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
13121 		if (!dma_buf) {
13122 			hrq->RQ_no_buf_found++;
13123 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13124 			goto out;
13125 		}
13126 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13127 		hrq->RQ_rcv_buf++;
13128 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
13129 
13130 		/* Just some basic sanity checks on FCP Command frame */
13131 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
13132 		fc_hdr->fh_f_ctl[1] << 8 |
13133 		fc_hdr->fh_f_ctl[2]);
13134 		if (((fctl &
13135 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
13136 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
13137 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
13138 			goto drop;
13139 
13140 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
13141 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length,  rcqe);
13142 			lpfc_nvmet_unsol_fcp_event(
13143 				phba, phba->sli4_hba.els_wq->pring, dma_buf,
13144 				cq->assoc_qp->isr_timestamp);
13145 			return false;
13146 		}
13147 drop:
13148 		lpfc_in_buf_free(phba, &dma_buf->dbuf);
13149 		break;
13150 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
13151 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
13152 		hrq->RQ_no_posted_buf++;
13153 		/* Post more buffers if possible */
13154 		spin_lock_irqsave(&phba->hbalock, iflags);
13155 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
13156 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13157 		workposted = true;
13158 		break;
13159 	}
13160 out:
13161 	return workposted;
13162 }
13163 
13164 /**
13165  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
13166  * @cq: Pointer to the completion queue.
13167  * @eqe: Pointer to fast-path completion queue entry.
13168  *
13169  * This routine process a fast-path work queue completion entry from fast-path
13170  * event queue for FCP command response completion.
13171  **/
13172 static int
13173 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13174 			 struct lpfc_cqe *cqe)
13175 {
13176 	struct lpfc_wcqe_release wcqe;
13177 	bool workposted = false;
13178 
13179 	/* Copy the work queue CQE and convert endian order if needed */
13180 	lpfc_sli_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
13181 
13182 	/* Check and process for different type of WCQE and dispatch */
13183 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
13184 	case CQE_CODE_COMPL_WQE:
13185 	case CQE_CODE_NVME_ERSP:
13186 		cq->CQ_wq++;
13187 		/* Process the WQ complete event */
13188 		phba->last_completion_time = jiffies;
13189 		if ((cq->subtype == LPFC_FCP) || (cq->subtype == LPFC_NVME))
13190 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
13191 				(struct lpfc_wcqe_complete *)&wcqe);
13192 		if (cq->subtype == LPFC_NVME_LS)
13193 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
13194 				(struct lpfc_wcqe_complete *)&wcqe);
13195 		break;
13196 	case CQE_CODE_RELEASE_WQE:
13197 		cq->CQ_release_wqe++;
13198 		/* Process the WQ release event */
13199 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
13200 				(struct lpfc_wcqe_release *)&wcqe);
13201 		break;
13202 	case CQE_CODE_XRI_ABORTED:
13203 		cq->CQ_xri_aborted++;
13204 		/* Process the WQ XRI abort event */
13205 		phba->last_completion_time = jiffies;
13206 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
13207 				(struct sli4_wcqe_xri_aborted *)&wcqe);
13208 		break;
13209 	case CQE_CODE_RECEIVE_V1:
13210 	case CQE_CODE_RECEIVE:
13211 		phba->last_completion_time = jiffies;
13212 		if (cq->subtype == LPFC_NVMET) {
13213 			workposted = lpfc_sli4_nvmet_handle_rcqe(
13214 				phba, cq, (struct lpfc_rcqe *)&wcqe);
13215 		}
13216 		break;
13217 	default:
13218 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13219 				"0144 Not a valid CQE code: x%x\n",
13220 				bf_get(lpfc_wcqe_c_code, &wcqe));
13221 		break;
13222 	}
13223 	return workposted;
13224 }
13225 
13226 /**
13227  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
13228  * @phba: Pointer to HBA context object.
13229  * @eqe: Pointer to fast-path event queue entry.
13230  *
13231  * This routine process a event queue entry from the fast-path event queue.
13232  * It will check the MajorCode and MinorCode to determine this is for a
13233  * completion event on a completion queue, if not, an error shall be logged
13234  * and just return. Otherwise, it will get to the corresponding completion
13235  * queue and process all the entries on the completion queue, rearm the
13236  * completion queue, and then return.
13237  **/
13238 static void
13239 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
13240 			uint32_t qidx)
13241 {
13242 	struct lpfc_queue *cq = NULL;
13243 	struct lpfc_cqe *cqe;
13244 	bool workposted = false;
13245 	uint16_t cqid, id;
13246 	int ecount = 0;
13247 
13248 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
13249 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13250 				"0366 Not a valid completion "
13251 				"event: majorcode=x%x, minorcode=x%x\n",
13252 				bf_get_le32(lpfc_eqe_major_code, eqe),
13253 				bf_get_le32(lpfc_eqe_minor_code, eqe));
13254 		return;
13255 	}
13256 
13257 	/* Get the reference to the corresponding CQ */
13258 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
13259 
13260 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
13261 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
13262 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
13263 			/* Process NVMET unsol rcv */
13264 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
13265 			goto  process_cq;
13266 		}
13267 	}
13268 
13269 	if (phba->sli4_hba.nvme_cq_map &&
13270 	    (cqid == phba->sli4_hba.nvme_cq_map[qidx])) {
13271 		/* Process NVME / NVMET command completion */
13272 		cq = phba->sli4_hba.nvme_cq[qidx];
13273 		goto  process_cq;
13274 	}
13275 
13276 	if (phba->sli4_hba.fcp_cq_map &&
13277 	    (cqid == phba->sli4_hba.fcp_cq_map[qidx])) {
13278 		/* Process FCP command completion */
13279 		cq = phba->sli4_hba.fcp_cq[qidx];
13280 		goto  process_cq;
13281 	}
13282 
13283 	if (phba->sli4_hba.nvmels_cq &&
13284 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
13285 		/* Process NVME unsol rcv */
13286 		cq = phba->sli4_hba.nvmels_cq;
13287 	}
13288 
13289 	/* Otherwise this is a Slow path event */
13290 	if (cq == NULL) {
13291 		lpfc_sli4_sp_handle_eqe(phba, eqe, phba->sli4_hba.hba_eq[qidx]);
13292 		return;
13293 	}
13294 
13295 process_cq:
13296 	if (unlikely(cqid != cq->queue_id)) {
13297 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13298 				"0368 Miss-matched fast-path completion "
13299 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
13300 				cqid, cq->queue_id);
13301 		return;
13302 	}
13303 
13304 	/* Save EQ associated with this CQ */
13305 	cq->assoc_qp = phba->sli4_hba.hba_eq[qidx];
13306 
13307 	/* Process all the entries to the CQ */
13308 	while ((cqe = lpfc_sli4_cq_get(cq))) {
13309 		workposted |= lpfc_sli4_fp_handle_cqe(phba, cq, cqe);
13310 		if (!(++ecount % cq->entry_repost))
13311 			lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
13312 	}
13313 
13314 	/* Track the max number of CQEs processed in 1 EQ */
13315 	if (ecount > cq->CQ_max_cqe)
13316 		cq->CQ_max_cqe = ecount;
13317 
13318 	/* Catch the no cq entry condition */
13319 	if (unlikely(ecount == 0))
13320 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13321 				"0369 No entry from fast-path completion "
13322 				"queue fcpcqid=%d\n", cq->queue_id);
13323 
13324 	/* In any case, flash and re-arm the CQ */
13325 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
13326 
13327 	/* wake up worker thread if there are works to be done */
13328 	if (workposted)
13329 		lpfc_worker_wake_up(phba);
13330 }
13331 
13332 static void
13333 lpfc_sli4_eq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
13334 {
13335 	struct lpfc_eqe *eqe;
13336 
13337 	/* walk all the EQ entries and drop on the floor */
13338 	while ((eqe = lpfc_sli4_eq_get(eq)))
13339 		;
13340 
13341 	/* Clear and re-arm the EQ */
13342 	lpfc_sli4_eq_release(eq, LPFC_QUEUE_REARM);
13343 }
13344 
13345 
13346 /**
13347  * lpfc_sli4_fof_handle_eqe - Process a Flash Optimized Fabric event queue
13348  *			     entry
13349  * @phba: Pointer to HBA context object.
13350  * @eqe: Pointer to fast-path event queue entry.
13351  *
13352  * This routine process a event queue entry from the Flash Optimized Fabric
13353  * event queue.  It will check the MajorCode and MinorCode to determine this
13354  * is for a completion event on a completion queue, if not, an error shall be
13355  * logged and just return. Otherwise, it will get to the corresponding
13356  * completion queue and process all the entries on the completion queue, rearm
13357  * the completion queue, and then return.
13358  **/
13359 static void
13360 lpfc_sli4_fof_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe)
13361 {
13362 	struct lpfc_queue *cq;
13363 	struct lpfc_cqe *cqe;
13364 	bool workposted = false;
13365 	uint16_t cqid;
13366 	int ecount = 0;
13367 
13368 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
13369 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13370 				"9147 Not a valid completion "
13371 				"event: majorcode=x%x, minorcode=x%x\n",
13372 				bf_get_le32(lpfc_eqe_major_code, eqe),
13373 				bf_get_le32(lpfc_eqe_minor_code, eqe));
13374 		return;
13375 	}
13376 
13377 	/* Get the reference to the corresponding CQ */
13378 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
13379 
13380 	/* Next check for OAS */
13381 	cq = phba->sli4_hba.oas_cq;
13382 	if (unlikely(!cq)) {
13383 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
13384 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13385 					"9148 OAS completion queue "
13386 					"does not exist\n");
13387 		return;
13388 	}
13389 
13390 	if (unlikely(cqid != cq->queue_id)) {
13391 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13392 				"9149 Miss-matched fast-path compl "
13393 				"queue id: eqcqid=%d, fcpcqid=%d\n",
13394 				cqid, cq->queue_id);
13395 		return;
13396 	}
13397 
13398 	/* Process all the entries to the OAS CQ */
13399 	while ((cqe = lpfc_sli4_cq_get(cq))) {
13400 		workposted |= lpfc_sli4_fp_handle_cqe(phba, cq, cqe);
13401 		if (!(++ecount % cq->entry_repost))
13402 			lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
13403 	}
13404 
13405 	/* Track the max number of CQEs processed in 1 EQ */
13406 	if (ecount > cq->CQ_max_cqe)
13407 		cq->CQ_max_cqe = ecount;
13408 
13409 	/* Catch the no cq entry condition */
13410 	if (unlikely(ecount == 0))
13411 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13412 				"9153 No entry from fast-path completion "
13413 				"queue fcpcqid=%d\n", cq->queue_id);
13414 
13415 	/* In any case, flash and re-arm the CQ */
13416 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
13417 
13418 	/* wake up worker thread if there are works to be done */
13419 	if (workposted)
13420 		lpfc_worker_wake_up(phba);
13421 }
13422 
13423 /**
13424  * lpfc_sli4_fof_intr_handler - HBA interrupt handler to SLI-4 device
13425  * @irq: Interrupt number.
13426  * @dev_id: The device context pointer.
13427  *
13428  * This function is directly called from the PCI layer as an interrupt
13429  * service routine when device with SLI-4 interface spec is enabled with
13430  * MSI-X multi-message interrupt mode and there is a Flash Optimized Fabric
13431  * IOCB ring event in the HBA. However, when the device is enabled with either
13432  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13433  * device-level interrupt handler. When the PCI slot is in error recovery
13434  * or the HBA is undergoing initialization, the interrupt handler will not
13435  * process the interrupt. The Flash Optimized Fabric ring event are handled in
13436  * the intrrupt context. This function is called without any lock held.
13437  * It gets the hbalock to access and update SLI data structures. Note that,
13438  * the EQ to CQ are one-to-one map such that the EQ index is
13439  * equal to that of CQ index.
13440  *
13441  * This function returns IRQ_HANDLED when interrupt is handled else it
13442  * returns IRQ_NONE.
13443  **/
13444 irqreturn_t
13445 lpfc_sli4_fof_intr_handler(int irq, void *dev_id)
13446 {
13447 	struct lpfc_hba *phba;
13448 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
13449 	struct lpfc_queue *eq;
13450 	struct lpfc_eqe *eqe;
13451 	unsigned long iflag;
13452 	int ecount = 0;
13453 
13454 	/* Get the driver's phba structure from the dev_id */
13455 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
13456 	phba = hba_eq_hdl->phba;
13457 
13458 	if (unlikely(!phba))
13459 		return IRQ_NONE;
13460 
13461 	/* Get to the EQ struct associated with this vector */
13462 	eq = phba->sli4_hba.fof_eq;
13463 	if (unlikely(!eq))
13464 		return IRQ_NONE;
13465 
13466 	/* Check device state for handling interrupt */
13467 	if (unlikely(lpfc_intr_state_check(phba))) {
13468 		eq->EQ_badstate++;
13469 		/* Check again for link_state with lock held */
13470 		spin_lock_irqsave(&phba->hbalock, iflag);
13471 		if (phba->link_state < LPFC_LINK_DOWN)
13472 			/* Flush, clear interrupt, and rearm the EQ */
13473 			lpfc_sli4_eq_flush(phba, eq);
13474 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13475 		return IRQ_NONE;
13476 	}
13477 
13478 	/*
13479 	 * Process all the event on FCP fast-path EQ
13480 	 */
13481 	while ((eqe = lpfc_sli4_eq_get(eq))) {
13482 		lpfc_sli4_fof_handle_eqe(phba, eqe);
13483 		if (!(++ecount % eq->entry_repost))
13484 			lpfc_sli4_eq_release(eq, LPFC_QUEUE_NOARM);
13485 		eq->EQ_processed++;
13486 	}
13487 
13488 	/* Track the max number of EQEs processed in 1 intr */
13489 	if (ecount > eq->EQ_max_eqe)
13490 		eq->EQ_max_eqe = ecount;
13491 
13492 
13493 	if (unlikely(ecount == 0)) {
13494 		eq->EQ_no_entry++;
13495 
13496 		if (phba->intr_type == MSIX)
13497 			/* MSI-X treated interrupt served as no EQ share INT */
13498 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13499 					"9145 MSI-X interrupt with no EQE\n");
13500 		else {
13501 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13502 					"9146 ISR interrupt with no EQE\n");
13503 			/* Non MSI-X treated on interrupt as EQ share INT */
13504 			return IRQ_NONE;
13505 		}
13506 	}
13507 	/* Always clear and re-arm the fast-path EQ */
13508 	lpfc_sli4_eq_release(eq, LPFC_QUEUE_REARM);
13509 	return IRQ_HANDLED;
13510 }
13511 
13512 /**
13513  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
13514  * @irq: Interrupt number.
13515  * @dev_id: The device context pointer.
13516  *
13517  * This function is directly called from the PCI layer as an interrupt
13518  * service routine when device with SLI-4 interface spec is enabled with
13519  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13520  * ring event in the HBA. However, when the device is enabled with either
13521  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13522  * device-level interrupt handler. When the PCI slot is in error recovery
13523  * or the HBA is undergoing initialization, the interrupt handler will not
13524  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13525  * the intrrupt context. This function is called without any lock held.
13526  * It gets the hbalock to access and update SLI data structures. Note that,
13527  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
13528  * equal to that of FCP CQ index.
13529  *
13530  * The link attention and ELS ring attention events are handled
13531  * by the worker thread. The interrupt handler signals the worker thread
13532  * and returns for these events. This function is called without any lock
13533  * held. It gets the hbalock to access and update SLI data structures.
13534  *
13535  * This function returns IRQ_HANDLED when interrupt is handled else it
13536  * returns IRQ_NONE.
13537  **/
13538 irqreturn_t
13539 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
13540 {
13541 	struct lpfc_hba *phba;
13542 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
13543 	struct lpfc_queue *fpeq;
13544 	struct lpfc_eqe *eqe;
13545 	unsigned long iflag;
13546 	int ecount = 0;
13547 	int hba_eqidx;
13548 
13549 	/* Get the driver's phba structure from the dev_id */
13550 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
13551 	phba = hba_eq_hdl->phba;
13552 	hba_eqidx = hba_eq_hdl->idx;
13553 
13554 	if (unlikely(!phba))
13555 		return IRQ_NONE;
13556 	if (unlikely(!phba->sli4_hba.hba_eq))
13557 		return IRQ_NONE;
13558 
13559 	/* Get to the EQ struct associated with this vector */
13560 	fpeq = phba->sli4_hba.hba_eq[hba_eqidx];
13561 	if (unlikely(!fpeq))
13562 		return IRQ_NONE;
13563 
13564 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
13565 	if (phba->ktime_on)
13566 		fpeq->isr_timestamp = ktime_get_ns();
13567 #endif
13568 
13569 	if (lpfc_fcp_look_ahead) {
13570 		if (atomic_dec_and_test(&hba_eq_hdl->hba_eq_in_use))
13571 			lpfc_sli4_eq_clr_intr(fpeq);
13572 		else {
13573 			atomic_inc(&hba_eq_hdl->hba_eq_in_use);
13574 			return IRQ_NONE;
13575 		}
13576 	}
13577 
13578 	/* Check device state for handling interrupt */
13579 	if (unlikely(lpfc_intr_state_check(phba))) {
13580 		fpeq->EQ_badstate++;
13581 		/* Check again for link_state with lock held */
13582 		spin_lock_irqsave(&phba->hbalock, iflag);
13583 		if (phba->link_state < LPFC_LINK_DOWN)
13584 			/* Flush, clear interrupt, and rearm the EQ */
13585 			lpfc_sli4_eq_flush(phba, fpeq);
13586 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13587 		if (lpfc_fcp_look_ahead)
13588 			atomic_inc(&hba_eq_hdl->hba_eq_in_use);
13589 		return IRQ_NONE;
13590 	}
13591 
13592 	/*
13593 	 * Process all the event on FCP fast-path EQ
13594 	 */
13595 	while ((eqe = lpfc_sli4_eq_get(fpeq))) {
13596 		if (eqe == NULL)
13597 			break;
13598 
13599 		lpfc_sli4_hba_handle_eqe(phba, eqe, hba_eqidx);
13600 		if (!(++ecount % fpeq->entry_repost))
13601 			lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_NOARM);
13602 		fpeq->EQ_processed++;
13603 	}
13604 
13605 	/* Track the max number of EQEs processed in 1 intr */
13606 	if (ecount > fpeq->EQ_max_eqe)
13607 		fpeq->EQ_max_eqe = ecount;
13608 
13609 	/* Always clear and re-arm the fast-path EQ */
13610 	lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_REARM);
13611 
13612 	if (unlikely(ecount == 0)) {
13613 		fpeq->EQ_no_entry++;
13614 
13615 		if (lpfc_fcp_look_ahead) {
13616 			atomic_inc(&hba_eq_hdl->hba_eq_in_use);
13617 			return IRQ_NONE;
13618 		}
13619 
13620 		if (phba->intr_type == MSIX)
13621 			/* MSI-X treated interrupt served as no EQ share INT */
13622 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13623 					"0358 MSI-X interrupt with no EQE\n");
13624 		else
13625 			/* Non MSI-X treated on interrupt as EQ share INT */
13626 			return IRQ_NONE;
13627 	}
13628 
13629 	if (lpfc_fcp_look_ahead)
13630 		atomic_inc(&hba_eq_hdl->hba_eq_in_use);
13631 
13632 	return IRQ_HANDLED;
13633 } /* lpfc_sli4_fp_intr_handler */
13634 
13635 /**
13636  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
13637  * @irq: Interrupt number.
13638  * @dev_id: The device context pointer.
13639  *
13640  * This function is the device-level interrupt handler to device with SLI-4
13641  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
13642  * interrupt mode is enabled and there is an event in the HBA which requires
13643  * driver attention. This function invokes the slow-path interrupt attention
13644  * handling function and fast-path interrupt attention handling function in
13645  * turn to process the relevant HBA attention events. This function is called
13646  * without any lock held. It gets the hbalock to access and update SLI data
13647  * structures.
13648  *
13649  * This function returns IRQ_HANDLED when interrupt is handled, else it
13650  * returns IRQ_NONE.
13651  **/
13652 irqreturn_t
13653 lpfc_sli4_intr_handler(int irq, void *dev_id)
13654 {
13655 	struct lpfc_hba  *phba;
13656 	irqreturn_t hba_irq_rc;
13657 	bool hba_handled = false;
13658 	int qidx;
13659 
13660 	/* Get the driver's phba structure from the dev_id */
13661 	phba = (struct lpfc_hba *)dev_id;
13662 
13663 	if (unlikely(!phba))
13664 		return IRQ_NONE;
13665 
13666 	/*
13667 	 * Invoke fast-path host attention interrupt handling as appropriate.
13668 	 */
13669 	for (qidx = 0; qidx < phba->io_channel_irqs; qidx++) {
13670 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
13671 					&phba->sli4_hba.hba_eq_hdl[qidx]);
13672 		if (hba_irq_rc == IRQ_HANDLED)
13673 			hba_handled |= true;
13674 	}
13675 
13676 	if (phba->cfg_fof) {
13677 		hba_irq_rc = lpfc_sli4_fof_intr_handler(irq,
13678 					&phba->sli4_hba.hba_eq_hdl[qidx]);
13679 		if (hba_irq_rc == IRQ_HANDLED)
13680 			hba_handled |= true;
13681 	}
13682 
13683 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
13684 } /* lpfc_sli4_intr_handler */
13685 
13686 /**
13687  * lpfc_sli4_queue_free - free a queue structure and associated memory
13688  * @queue: The queue structure to free.
13689  *
13690  * This function frees a queue structure and the DMAable memory used for
13691  * the host resident queue. This function must be called after destroying the
13692  * queue on the HBA.
13693  **/
13694 void
13695 lpfc_sli4_queue_free(struct lpfc_queue *queue)
13696 {
13697 	struct lpfc_dmabuf *dmabuf;
13698 
13699 	if (!queue)
13700 		return;
13701 
13702 	while (!list_empty(&queue->page_list)) {
13703 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
13704 				 list);
13705 		dma_free_coherent(&queue->phba->pcidev->dev, SLI4_PAGE_SIZE,
13706 				  dmabuf->virt, dmabuf->phys);
13707 		kfree(dmabuf);
13708 	}
13709 	if (queue->rqbp) {
13710 		lpfc_free_rq_buffer(queue->phba, queue);
13711 		kfree(queue->rqbp);
13712 	}
13713 	kfree(queue->pring);
13714 	kfree(queue);
13715 	return;
13716 }
13717 
13718 /**
13719  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
13720  * @phba: The HBA that this queue is being created on.
13721  * @entry_size: The size of each queue entry for this queue.
13722  * @entry count: The number of entries that this queue will handle.
13723  *
13724  * This function allocates a queue structure and the DMAable memory used for
13725  * the host resident queue. This function must be called before creating the
13726  * queue on the HBA.
13727  **/
13728 struct lpfc_queue *
13729 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t entry_size,
13730 		      uint32_t entry_count)
13731 {
13732 	struct lpfc_queue *queue;
13733 	struct lpfc_dmabuf *dmabuf;
13734 	int x, total_qe_count;
13735 	void *dma_pointer;
13736 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13737 
13738 	if (!phba->sli4_hba.pc_sli4_params.supported)
13739 		hw_page_size = SLI4_PAGE_SIZE;
13740 
13741 	queue = kzalloc(sizeof(struct lpfc_queue) +
13742 			(sizeof(union sli4_qe) * entry_count), GFP_KERNEL);
13743 	if (!queue)
13744 		return NULL;
13745 	queue->page_count = (ALIGN(entry_size * entry_count,
13746 			hw_page_size))/hw_page_size;
13747 
13748 	/* If needed, Adjust page count to match the max the adapter supports */
13749 	if (queue->page_count > phba->sli4_hba.pc_sli4_params.wqpcnt)
13750 		queue->page_count = phba->sli4_hba.pc_sli4_params.wqpcnt;
13751 
13752 	INIT_LIST_HEAD(&queue->list);
13753 	INIT_LIST_HEAD(&queue->wq_list);
13754 	INIT_LIST_HEAD(&queue->page_list);
13755 	INIT_LIST_HEAD(&queue->child_list);
13756 	for (x = 0, total_qe_count = 0; x < queue->page_count; x++) {
13757 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
13758 		if (!dmabuf)
13759 			goto out_fail;
13760 		dmabuf->virt = dma_zalloc_coherent(&phba->pcidev->dev,
13761 						   hw_page_size, &dmabuf->phys,
13762 						   GFP_KERNEL);
13763 		if (!dmabuf->virt) {
13764 			kfree(dmabuf);
13765 			goto out_fail;
13766 		}
13767 		dmabuf->buffer_tag = x;
13768 		list_add_tail(&dmabuf->list, &queue->page_list);
13769 		/* initialize queue's entry array */
13770 		dma_pointer = dmabuf->virt;
13771 		for (; total_qe_count < entry_count &&
13772 		     dma_pointer < (hw_page_size + dmabuf->virt);
13773 		     total_qe_count++, dma_pointer += entry_size) {
13774 			queue->qe[total_qe_count].address = dma_pointer;
13775 		}
13776 	}
13777 	queue->entry_size = entry_size;
13778 	queue->entry_count = entry_count;
13779 
13780 	/*
13781 	 * entry_repost is calculated based on the number of entries in the
13782 	 * queue. This works out except for RQs. If buffers are NOT initially
13783 	 * posted for every RQE, entry_repost should be adjusted accordingly.
13784 	 */
13785 	queue->entry_repost = (entry_count >> 3);
13786 	if (queue->entry_repost < LPFC_QUEUE_MIN_REPOST)
13787 		queue->entry_repost = LPFC_QUEUE_MIN_REPOST;
13788 	queue->phba = phba;
13789 
13790 	return queue;
13791 out_fail:
13792 	lpfc_sli4_queue_free(queue);
13793 	return NULL;
13794 }
13795 
13796 /**
13797  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
13798  * @phba: HBA structure that indicates port to create a queue on.
13799  * @pci_barset: PCI BAR set flag.
13800  *
13801  * This function shall perform iomap of the specified PCI BAR address to host
13802  * memory address if not already done so and return it. The returned host
13803  * memory address can be NULL.
13804  */
13805 static void __iomem *
13806 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
13807 {
13808 	if (!phba->pcidev)
13809 		return NULL;
13810 
13811 	switch (pci_barset) {
13812 	case WQ_PCI_BAR_0_AND_1:
13813 		return phba->pci_bar0_memmap_p;
13814 	case WQ_PCI_BAR_2_AND_3:
13815 		return phba->pci_bar2_memmap_p;
13816 	case WQ_PCI_BAR_4_AND_5:
13817 		return phba->pci_bar4_memmap_p;
13818 	default:
13819 		break;
13820 	}
13821 	return NULL;
13822 }
13823 
13824 /**
13825  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on FCP EQs
13826  * @phba: HBA structure that indicates port to create a queue on.
13827  * @startq: The starting FCP EQ to modify
13828  *
13829  * This function sends an MODIFY_EQ_DELAY mailbox command to the HBA.
13830  *
13831  * The @phba struct is used to send mailbox command to HBA. The @startq
13832  * is used to get the starting FCP EQ to change.
13833  * This function is asynchronous and will wait for the mailbox
13834  * command to finish before continuing.
13835  *
13836  * On success this function will return a zero. If unable to allocate enough
13837  * memory this function will return -ENOMEM. If the queue create mailbox command
13838  * fails this function will return -ENXIO.
13839  **/
13840 int
13841 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq)
13842 {
13843 	struct lpfc_mbx_modify_eq_delay *eq_delay;
13844 	LPFC_MBOXQ_t *mbox;
13845 	struct lpfc_queue *eq;
13846 	int cnt, rc, length, status = 0;
13847 	uint32_t shdr_status, shdr_add_status;
13848 	uint32_t result;
13849 	int qidx;
13850 	union lpfc_sli4_cfg_shdr *shdr;
13851 	uint16_t dmult;
13852 
13853 	if (startq >= phba->io_channel_irqs)
13854 		return 0;
13855 
13856 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13857 	if (!mbox)
13858 		return -ENOMEM;
13859 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
13860 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13861 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13862 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
13863 			 length, LPFC_SLI4_MBX_EMBED);
13864 	eq_delay = &mbox->u.mqe.un.eq_delay;
13865 
13866 	/* Calculate delay multiper from maximum interrupt per second */
13867 	result = phba->cfg_fcp_imax / phba->io_channel_irqs;
13868 	if (result > LPFC_DMULT_CONST || result == 0)
13869 		dmult = 0;
13870 	else
13871 		dmult = LPFC_DMULT_CONST/result - 1;
13872 
13873 	cnt = 0;
13874 	for (qidx = startq; qidx < phba->io_channel_irqs; qidx++) {
13875 		eq = phba->sli4_hba.hba_eq[qidx];
13876 		if (!eq)
13877 			continue;
13878 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
13879 		eq_delay->u.request.eq[cnt].phase = 0;
13880 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
13881 		cnt++;
13882 		if (cnt >= LPFC_MAX_EQ_DELAY)
13883 			break;
13884 	}
13885 	eq_delay->u.request.num_eq = cnt;
13886 
13887 	mbox->vport = phba->pport;
13888 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13889 	mbox->context1 = NULL;
13890 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13891 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
13892 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13893 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13894 	if (shdr_status || shdr_add_status || rc) {
13895 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13896 				"2512 MODIFY_EQ_DELAY mailbox failed with "
13897 				"status x%x add_status x%x, mbx status x%x\n",
13898 				shdr_status, shdr_add_status, rc);
13899 		status = -ENXIO;
13900 	}
13901 	mempool_free(mbox, phba->mbox_mem_pool);
13902 	return status;
13903 }
13904 
13905 /**
13906  * lpfc_eq_create - Create an Event Queue on the HBA
13907  * @phba: HBA structure that indicates port to create a queue on.
13908  * @eq: The queue structure to use to create the event queue.
13909  * @imax: The maximum interrupt per second limit.
13910  *
13911  * This function creates an event queue, as detailed in @eq, on a port,
13912  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
13913  *
13914  * The @phba struct is used to send mailbox command to HBA. The @eq struct
13915  * is used to get the entry count and entry size that are necessary to
13916  * determine the number of pages to allocate and use for this queue. This
13917  * function will send the EQ_CREATE mailbox command to the HBA to setup the
13918  * event queue. This function is asynchronous and will wait for the mailbox
13919  * command to finish before continuing.
13920  *
13921  * On success this function will return a zero. If unable to allocate enough
13922  * memory this function will return -ENOMEM. If the queue create mailbox command
13923  * fails this function will return -ENXIO.
13924  **/
13925 int
13926 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
13927 {
13928 	struct lpfc_mbx_eq_create *eq_create;
13929 	LPFC_MBOXQ_t *mbox;
13930 	int rc, length, status = 0;
13931 	struct lpfc_dmabuf *dmabuf;
13932 	uint32_t shdr_status, shdr_add_status;
13933 	union lpfc_sli4_cfg_shdr *shdr;
13934 	uint16_t dmult;
13935 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13936 
13937 	/* sanity check on queue memory */
13938 	if (!eq)
13939 		return -ENODEV;
13940 	if (!phba->sli4_hba.pc_sli4_params.supported)
13941 		hw_page_size = SLI4_PAGE_SIZE;
13942 
13943 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13944 	if (!mbox)
13945 		return -ENOMEM;
13946 	length = (sizeof(struct lpfc_mbx_eq_create) -
13947 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13948 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13949 			 LPFC_MBOX_OPCODE_EQ_CREATE,
13950 			 length, LPFC_SLI4_MBX_EMBED);
13951 	eq_create = &mbox->u.mqe.un.eq_create;
13952 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
13953 	       eq->page_count);
13954 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
13955 	       LPFC_EQE_SIZE);
13956 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
13957 	/* don't setup delay multiplier using EQ_CREATE */
13958 	dmult = 0;
13959 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
13960 	       dmult);
13961 	switch (eq->entry_count) {
13962 	default:
13963 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13964 				"0360 Unsupported EQ count. (%d)\n",
13965 				eq->entry_count);
13966 		if (eq->entry_count < 256)
13967 			return -EINVAL;
13968 		/* otherwise default to smallest count (drop through) */
13969 	case 256:
13970 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13971 		       LPFC_EQ_CNT_256);
13972 		break;
13973 	case 512:
13974 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13975 		       LPFC_EQ_CNT_512);
13976 		break;
13977 	case 1024:
13978 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13979 		       LPFC_EQ_CNT_1024);
13980 		break;
13981 	case 2048:
13982 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13983 		       LPFC_EQ_CNT_2048);
13984 		break;
13985 	case 4096:
13986 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13987 		       LPFC_EQ_CNT_4096);
13988 		break;
13989 	}
13990 	list_for_each_entry(dmabuf, &eq->page_list, list) {
13991 		memset(dmabuf->virt, 0, hw_page_size);
13992 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13993 					putPaddrLow(dmabuf->phys);
13994 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13995 					putPaddrHigh(dmabuf->phys);
13996 	}
13997 	mbox->vport = phba->pport;
13998 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13999 	mbox->context1 = NULL;
14000 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14001 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
14002 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14003 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14004 	if (shdr_status || shdr_add_status || rc) {
14005 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14006 				"2500 EQ_CREATE mailbox failed with "
14007 				"status x%x add_status x%x, mbx status x%x\n",
14008 				shdr_status, shdr_add_status, rc);
14009 		status = -ENXIO;
14010 	}
14011 	eq->type = LPFC_EQ;
14012 	eq->subtype = LPFC_NONE;
14013 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
14014 	if (eq->queue_id == 0xFFFF)
14015 		status = -ENXIO;
14016 	eq->host_index = 0;
14017 	eq->hba_index = 0;
14018 
14019 	mempool_free(mbox, phba->mbox_mem_pool);
14020 	return status;
14021 }
14022 
14023 /**
14024  * lpfc_cq_create - Create a Completion Queue on the HBA
14025  * @phba: HBA structure that indicates port to create a queue on.
14026  * @cq: The queue structure to use to create the completion queue.
14027  * @eq: The event queue to bind this completion queue to.
14028  *
14029  * This function creates a completion queue, as detailed in @wq, on a port,
14030  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
14031  *
14032  * The @phba struct is used to send mailbox command to HBA. The @cq struct
14033  * is used to get the entry count and entry size that are necessary to
14034  * determine the number of pages to allocate and use for this queue. The @eq
14035  * is used to indicate which event queue to bind this completion queue to. This
14036  * function will send the CQ_CREATE mailbox command to the HBA to setup the
14037  * completion queue. This function is asynchronous and will wait for the mailbox
14038  * command to finish before continuing.
14039  *
14040  * On success this function will return a zero. If unable to allocate enough
14041  * memory this function will return -ENOMEM. If the queue create mailbox command
14042  * fails this function will return -ENXIO.
14043  **/
14044 int
14045 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
14046 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
14047 {
14048 	struct lpfc_mbx_cq_create *cq_create;
14049 	struct lpfc_dmabuf *dmabuf;
14050 	LPFC_MBOXQ_t *mbox;
14051 	int rc, length, status = 0;
14052 	uint32_t shdr_status, shdr_add_status;
14053 	union lpfc_sli4_cfg_shdr *shdr;
14054 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14055 
14056 	/* sanity check on queue memory */
14057 	if (!cq || !eq)
14058 		return -ENODEV;
14059 	if (!phba->sli4_hba.pc_sli4_params.supported)
14060 		hw_page_size = SLI4_PAGE_SIZE;
14061 
14062 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14063 	if (!mbox)
14064 		return -ENOMEM;
14065 	length = (sizeof(struct lpfc_mbx_cq_create) -
14066 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14067 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14068 			 LPFC_MBOX_OPCODE_CQ_CREATE,
14069 			 length, LPFC_SLI4_MBX_EMBED);
14070 	cq_create = &mbox->u.mqe.un.cq_create;
14071 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
14072 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
14073 		    cq->page_count);
14074 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
14075 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
14076 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
14077 	       phba->sli4_hba.pc_sli4_params.cqv);
14078 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
14079 		/* FW only supports 1. Should be PAGE_SIZE/SLI4_PAGE_SIZE */
14080 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request, 1);
14081 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
14082 		       eq->queue_id);
14083 	} else {
14084 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
14085 		       eq->queue_id);
14086 	}
14087 	switch (cq->entry_count) {
14088 	default:
14089 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14090 				"0361 Unsupported CQ count: "
14091 				"entry cnt %d sz %d pg cnt %d repost %d\n",
14092 				cq->entry_count, cq->entry_size,
14093 				cq->page_count, cq->entry_repost);
14094 		if (cq->entry_count < 256) {
14095 			status = -EINVAL;
14096 			goto out;
14097 		}
14098 		/* otherwise default to smallest count (drop through) */
14099 	case 256:
14100 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
14101 		       LPFC_CQ_CNT_256);
14102 		break;
14103 	case 512:
14104 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
14105 		       LPFC_CQ_CNT_512);
14106 		break;
14107 	case 1024:
14108 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
14109 		       LPFC_CQ_CNT_1024);
14110 		break;
14111 	}
14112 	list_for_each_entry(dmabuf, &cq->page_list, list) {
14113 		memset(dmabuf->virt, 0, hw_page_size);
14114 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
14115 					putPaddrLow(dmabuf->phys);
14116 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
14117 					putPaddrHigh(dmabuf->phys);
14118 	}
14119 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14120 
14121 	/* The IOCTL status is embedded in the mailbox subheader. */
14122 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14123 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14124 	if (shdr_status || shdr_add_status || rc) {
14125 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14126 				"2501 CQ_CREATE mailbox failed with "
14127 				"status x%x add_status x%x, mbx status x%x\n",
14128 				shdr_status, shdr_add_status, rc);
14129 		status = -ENXIO;
14130 		goto out;
14131 	}
14132 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
14133 	if (cq->queue_id == 0xFFFF) {
14134 		status = -ENXIO;
14135 		goto out;
14136 	}
14137 	/* link the cq onto the parent eq child list */
14138 	list_add_tail(&cq->list, &eq->child_list);
14139 	/* Set up completion queue's type and subtype */
14140 	cq->type = type;
14141 	cq->subtype = subtype;
14142 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
14143 	cq->assoc_qid = eq->queue_id;
14144 	cq->host_index = 0;
14145 	cq->hba_index = 0;
14146 
14147 out:
14148 	mempool_free(mbox, phba->mbox_mem_pool);
14149 	return status;
14150 }
14151 
14152 /**
14153  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
14154  * @phba: HBA structure that indicates port to create a queue on.
14155  * @cqp: The queue structure array to use to create the completion queues.
14156  * @eqp: The event queue array to bind these completion queues to.
14157  *
14158  * This function creates a set of  completion queue, s to support MRQ
14159  * as detailed in @cqp, on a port,
14160  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
14161  *
14162  * The @phba struct is used to send mailbox command to HBA. The @cq struct
14163  * is used to get the entry count and entry size that are necessary to
14164  * determine the number of pages to allocate and use for this queue. The @eq
14165  * is used to indicate which event queue to bind this completion queue to. This
14166  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
14167  * completion queue. This function is asynchronous and will wait for the mailbox
14168  * command to finish before continuing.
14169  *
14170  * On success this function will return a zero. If unable to allocate enough
14171  * memory this function will return -ENOMEM. If the queue create mailbox command
14172  * fails this function will return -ENXIO.
14173  **/
14174 int
14175 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
14176 		   struct lpfc_queue **eqp, uint32_t type, uint32_t subtype)
14177 {
14178 	struct lpfc_queue *cq;
14179 	struct lpfc_queue *eq;
14180 	struct lpfc_mbx_cq_create_set *cq_set;
14181 	struct lpfc_dmabuf *dmabuf;
14182 	LPFC_MBOXQ_t *mbox;
14183 	int rc, length, alloclen, status = 0;
14184 	int cnt, idx, numcq, page_idx = 0;
14185 	uint32_t shdr_status, shdr_add_status;
14186 	union lpfc_sli4_cfg_shdr *shdr;
14187 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14188 
14189 	/* sanity check on queue memory */
14190 	numcq = phba->cfg_nvmet_mrq;
14191 	if (!cqp || !eqp || !numcq)
14192 		return -ENODEV;
14193 	if (!phba->sli4_hba.pc_sli4_params.supported)
14194 		hw_page_size = SLI4_PAGE_SIZE;
14195 
14196 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14197 	if (!mbox)
14198 		return -ENOMEM;
14199 
14200 	length = sizeof(struct lpfc_mbx_cq_create_set);
14201 	length += ((numcq * cqp[0]->page_count) *
14202 		   sizeof(struct dma_address));
14203 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14204 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
14205 			LPFC_SLI4_MBX_NEMBED);
14206 	if (alloclen < length) {
14207 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14208 				"3098 Allocated DMA memory size (%d) is "
14209 				"less than the requested DMA memory size "
14210 				"(%d)\n", alloclen, length);
14211 		status = -ENOMEM;
14212 		goto out;
14213 	}
14214 	cq_set = mbox->sge_array->addr[0];
14215 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
14216 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
14217 
14218 	for (idx = 0; idx < numcq; idx++) {
14219 		cq = cqp[idx];
14220 		eq = eqp[idx];
14221 		if (!cq || !eq) {
14222 			status = -ENOMEM;
14223 			goto out;
14224 		}
14225 
14226 		switch (idx) {
14227 		case 0:
14228 			bf_set(lpfc_mbx_cq_create_set_page_size,
14229 			       &cq_set->u.request,
14230 			       (hw_page_size / SLI4_PAGE_SIZE));
14231 			bf_set(lpfc_mbx_cq_create_set_num_pages,
14232 			       &cq_set->u.request, cq->page_count);
14233 			bf_set(lpfc_mbx_cq_create_set_evt,
14234 			       &cq_set->u.request, 1);
14235 			bf_set(lpfc_mbx_cq_create_set_valid,
14236 			       &cq_set->u.request, 1);
14237 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
14238 			       &cq_set->u.request, 0);
14239 			bf_set(lpfc_mbx_cq_create_set_num_cq,
14240 			       &cq_set->u.request, numcq);
14241 			switch (cq->entry_count) {
14242 			default:
14243 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14244 						"3118 Bad CQ count. (%d)\n",
14245 						cq->entry_count);
14246 				if (cq->entry_count < 256) {
14247 					status = -EINVAL;
14248 					goto out;
14249 				}
14250 				/* otherwise default to smallest (drop thru) */
14251 			case 256:
14252 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
14253 				       &cq_set->u.request, LPFC_CQ_CNT_256);
14254 				break;
14255 			case 512:
14256 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
14257 				       &cq_set->u.request, LPFC_CQ_CNT_512);
14258 				break;
14259 			case 1024:
14260 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
14261 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
14262 				break;
14263 			}
14264 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
14265 			       &cq_set->u.request, eq->queue_id);
14266 			break;
14267 		case 1:
14268 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
14269 			       &cq_set->u.request, eq->queue_id);
14270 			break;
14271 		case 2:
14272 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
14273 			       &cq_set->u.request, eq->queue_id);
14274 			break;
14275 		case 3:
14276 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
14277 			       &cq_set->u.request, eq->queue_id);
14278 			break;
14279 		case 4:
14280 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
14281 			       &cq_set->u.request, eq->queue_id);
14282 			break;
14283 		case 5:
14284 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
14285 			       &cq_set->u.request, eq->queue_id);
14286 			break;
14287 		case 6:
14288 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
14289 			       &cq_set->u.request, eq->queue_id);
14290 			break;
14291 		case 7:
14292 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
14293 			       &cq_set->u.request, eq->queue_id);
14294 			break;
14295 		case 8:
14296 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
14297 			       &cq_set->u.request, eq->queue_id);
14298 			break;
14299 		case 9:
14300 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
14301 			       &cq_set->u.request, eq->queue_id);
14302 			break;
14303 		case 10:
14304 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
14305 			       &cq_set->u.request, eq->queue_id);
14306 			break;
14307 		case 11:
14308 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
14309 			       &cq_set->u.request, eq->queue_id);
14310 			break;
14311 		case 12:
14312 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
14313 			       &cq_set->u.request, eq->queue_id);
14314 			break;
14315 		case 13:
14316 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
14317 			       &cq_set->u.request, eq->queue_id);
14318 			break;
14319 		case 14:
14320 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
14321 			       &cq_set->u.request, eq->queue_id);
14322 			break;
14323 		case 15:
14324 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
14325 			       &cq_set->u.request, eq->queue_id);
14326 			break;
14327 		}
14328 
14329 		/* link the cq onto the parent eq child list */
14330 		list_add_tail(&cq->list, &eq->child_list);
14331 		/* Set up completion queue's type and subtype */
14332 		cq->type = type;
14333 		cq->subtype = subtype;
14334 		cq->assoc_qid = eq->queue_id;
14335 		cq->host_index = 0;
14336 		cq->hba_index = 0;
14337 
14338 		rc = 0;
14339 		list_for_each_entry(dmabuf, &cq->page_list, list) {
14340 			memset(dmabuf->virt, 0, hw_page_size);
14341 			cnt = page_idx + dmabuf->buffer_tag;
14342 			cq_set->u.request.page[cnt].addr_lo =
14343 					putPaddrLow(dmabuf->phys);
14344 			cq_set->u.request.page[cnt].addr_hi =
14345 					putPaddrHigh(dmabuf->phys);
14346 			rc++;
14347 		}
14348 		page_idx += rc;
14349 	}
14350 
14351 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14352 
14353 	/* The IOCTL status is embedded in the mailbox subheader. */
14354 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14355 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14356 	if (shdr_status || shdr_add_status || rc) {
14357 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14358 				"3119 CQ_CREATE_SET mailbox failed with "
14359 				"status x%x add_status x%x, mbx status x%x\n",
14360 				shdr_status, shdr_add_status, rc);
14361 		status = -ENXIO;
14362 		goto out;
14363 	}
14364 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
14365 	if (rc == 0xFFFF) {
14366 		status = -ENXIO;
14367 		goto out;
14368 	}
14369 
14370 	for (idx = 0; idx < numcq; idx++) {
14371 		cq = cqp[idx];
14372 		cq->queue_id = rc + idx;
14373 	}
14374 
14375 out:
14376 	lpfc_sli4_mbox_cmd_free(phba, mbox);
14377 	return status;
14378 }
14379 
14380 /**
14381  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
14382  * @phba: HBA structure that indicates port to create a queue on.
14383  * @mq: The queue structure to use to create the mailbox queue.
14384  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
14385  * @cq: The completion queue to associate with this cq.
14386  *
14387  * This function provides failback (fb) functionality when the
14388  * mq_create_ext fails on older FW generations.  It's purpose is identical
14389  * to mq_create_ext otherwise.
14390  *
14391  * This routine cannot fail as all attributes were previously accessed and
14392  * initialized in mq_create_ext.
14393  **/
14394 static void
14395 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
14396 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
14397 {
14398 	struct lpfc_mbx_mq_create *mq_create;
14399 	struct lpfc_dmabuf *dmabuf;
14400 	int length;
14401 
14402 	length = (sizeof(struct lpfc_mbx_mq_create) -
14403 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14404 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14405 			 LPFC_MBOX_OPCODE_MQ_CREATE,
14406 			 length, LPFC_SLI4_MBX_EMBED);
14407 	mq_create = &mbox->u.mqe.un.mq_create;
14408 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
14409 	       mq->page_count);
14410 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
14411 	       cq->queue_id);
14412 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
14413 	switch (mq->entry_count) {
14414 	case 16:
14415 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
14416 		       LPFC_MQ_RING_SIZE_16);
14417 		break;
14418 	case 32:
14419 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
14420 		       LPFC_MQ_RING_SIZE_32);
14421 		break;
14422 	case 64:
14423 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
14424 		       LPFC_MQ_RING_SIZE_64);
14425 		break;
14426 	case 128:
14427 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
14428 		       LPFC_MQ_RING_SIZE_128);
14429 		break;
14430 	}
14431 	list_for_each_entry(dmabuf, &mq->page_list, list) {
14432 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
14433 			putPaddrLow(dmabuf->phys);
14434 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
14435 			putPaddrHigh(dmabuf->phys);
14436 	}
14437 }
14438 
14439 /**
14440  * lpfc_mq_create - Create a mailbox Queue on the HBA
14441  * @phba: HBA structure that indicates port to create a queue on.
14442  * @mq: The queue structure to use to create the mailbox queue.
14443  * @cq: The completion queue to associate with this cq.
14444  * @subtype: The queue's subtype.
14445  *
14446  * This function creates a mailbox queue, as detailed in @mq, on a port,
14447  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
14448  *
14449  * The @phba struct is used to send mailbox command to HBA. The @cq struct
14450  * is used to get the entry count and entry size that are necessary to
14451  * determine the number of pages to allocate and use for this queue. This
14452  * function will send the MQ_CREATE mailbox command to the HBA to setup the
14453  * mailbox queue. This function is asynchronous and will wait for the mailbox
14454  * command to finish before continuing.
14455  *
14456  * On success this function will return a zero. If unable to allocate enough
14457  * memory this function will return -ENOMEM. If the queue create mailbox command
14458  * fails this function will return -ENXIO.
14459  **/
14460 int32_t
14461 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
14462 	       struct lpfc_queue *cq, uint32_t subtype)
14463 {
14464 	struct lpfc_mbx_mq_create *mq_create;
14465 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
14466 	struct lpfc_dmabuf *dmabuf;
14467 	LPFC_MBOXQ_t *mbox;
14468 	int rc, length, status = 0;
14469 	uint32_t shdr_status, shdr_add_status;
14470 	union lpfc_sli4_cfg_shdr *shdr;
14471 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14472 
14473 	/* sanity check on queue memory */
14474 	if (!mq || !cq)
14475 		return -ENODEV;
14476 	if (!phba->sli4_hba.pc_sli4_params.supported)
14477 		hw_page_size = SLI4_PAGE_SIZE;
14478 
14479 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14480 	if (!mbox)
14481 		return -ENOMEM;
14482 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
14483 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14484 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14485 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
14486 			 length, LPFC_SLI4_MBX_EMBED);
14487 
14488 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
14489 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
14490 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
14491 	       &mq_create_ext->u.request, mq->page_count);
14492 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
14493 	       &mq_create_ext->u.request, 1);
14494 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
14495 	       &mq_create_ext->u.request, 1);
14496 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
14497 	       &mq_create_ext->u.request, 1);
14498 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
14499 	       &mq_create_ext->u.request, 1);
14500 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
14501 	       &mq_create_ext->u.request, 1);
14502 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
14503 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
14504 	       phba->sli4_hba.pc_sli4_params.mqv);
14505 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
14506 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
14507 		       cq->queue_id);
14508 	else
14509 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
14510 		       cq->queue_id);
14511 	switch (mq->entry_count) {
14512 	default:
14513 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14514 				"0362 Unsupported MQ count. (%d)\n",
14515 				mq->entry_count);
14516 		if (mq->entry_count < 16) {
14517 			status = -EINVAL;
14518 			goto out;
14519 		}
14520 		/* otherwise default to smallest count (drop through) */
14521 	case 16:
14522 		bf_set(lpfc_mq_context_ring_size,
14523 		       &mq_create_ext->u.request.context,
14524 		       LPFC_MQ_RING_SIZE_16);
14525 		break;
14526 	case 32:
14527 		bf_set(lpfc_mq_context_ring_size,
14528 		       &mq_create_ext->u.request.context,
14529 		       LPFC_MQ_RING_SIZE_32);
14530 		break;
14531 	case 64:
14532 		bf_set(lpfc_mq_context_ring_size,
14533 		       &mq_create_ext->u.request.context,
14534 		       LPFC_MQ_RING_SIZE_64);
14535 		break;
14536 	case 128:
14537 		bf_set(lpfc_mq_context_ring_size,
14538 		       &mq_create_ext->u.request.context,
14539 		       LPFC_MQ_RING_SIZE_128);
14540 		break;
14541 	}
14542 	list_for_each_entry(dmabuf, &mq->page_list, list) {
14543 		memset(dmabuf->virt, 0, hw_page_size);
14544 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
14545 					putPaddrLow(dmabuf->phys);
14546 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
14547 					putPaddrHigh(dmabuf->phys);
14548 	}
14549 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14550 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
14551 			      &mq_create_ext->u.response);
14552 	if (rc != MBX_SUCCESS) {
14553 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14554 				"2795 MQ_CREATE_EXT failed with "
14555 				"status x%x. Failback to MQ_CREATE.\n",
14556 				rc);
14557 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
14558 		mq_create = &mbox->u.mqe.un.mq_create;
14559 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14560 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
14561 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
14562 				      &mq_create->u.response);
14563 	}
14564 
14565 	/* The IOCTL status is embedded in the mailbox subheader. */
14566 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14567 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14568 	if (shdr_status || shdr_add_status || rc) {
14569 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14570 				"2502 MQ_CREATE mailbox failed with "
14571 				"status x%x add_status x%x, mbx status x%x\n",
14572 				shdr_status, shdr_add_status, rc);
14573 		status = -ENXIO;
14574 		goto out;
14575 	}
14576 	if (mq->queue_id == 0xFFFF) {
14577 		status = -ENXIO;
14578 		goto out;
14579 	}
14580 	mq->type = LPFC_MQ;
14581 	mq->assoc_qid = cq->queue_id;
14582 	mq->subtype = subtype;
14583 	mq->host_index = 0;
14584 	mq->hba_index = 0;
14585 
14586 	/* link the mq onto the parent cq child list */
14587 	list_add_tail(&mq->list, &cq->child_list);
14588 out:
14589 	mempool_free(mbox, phba->mbox_mem_pool);
14590 	return status;
14591 }
14592 
14593 /**
14594  * lpfc_wq_create - Create a Work Queue on the HBA
14595  * @phba: HBA structure that indicates port to create a queue on.
14596  * @wq: The queue structure to use to create the work queue.
14597  * @cq: The completion queue to bind this work queue to.
14598  * @subtype: The subtype of the work queue indicating its functionality.
14599  *
14600  * This function creates a work queue, as detailed in @wq, on a port, described
14601  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
14602  *
14603  * The @phba struct is used to send mailbox command to HBA. The @wq struct
14604  * is used to get the entry count and entry size that are necessary to
14605  * determine the number of pages to allocate and use for this queue. The @cq
14606  * is used to indicate which completion queue to bind this work queue to. This
14607  * function will send the WQ_CREATE mailbox command to the HBA to setup the
14608  * work queue. This function is asynchronous and will wait for the mailbox
14609  * command to finish before continuing.
14610  *
14611  * On success this function will return a zero. If unable to allocate enough
14612  * memory this function will return -ENOMEM. If the queue create mailbox command
14613  * fails this function will return -ENXIO.
14614  **/
14615 int
14616 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
14617 	       struct lpfc_queue *cq, uint32_t subtype)
14618 {
14619 	struct lpfc_mbx_wq_create *wq_create;
14620 	struct lpfc_dmabuf *dmabuf;
14621 	LPFC_MBOXQ_t *mbox;
14622 	int rc, length, status = 0;
14623 	uint32_t shdr_status, shdr_add_status;
14624 	union lpfc_sli4_cfg_shdr *shdr;
14625 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14626 	struct dma_address *page;
14627 	void __iomem *bar_memmap_p;
14628 	uint32_t db_offset;
14629 	uint16_t pci_barset;
14630 
14631 	/* sanity check on queue memory */
14632 	if (!wq || !cq)
14633 		return -ENODEV;
14634 	if (!phba->sli4_hba.pc_sli4_params.supported)
14635 		hw_page_size = SLI4_PAGE_SIZE;
14636 
14637 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14638 	if (!mbox)
14639 		return -ENOMEM;
14640 	length = (sizeof(struct lpfc_mbx_wq_create) -
14641 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14642 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14643 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
14644 			 length, LPFC_SLI4_MBX_EMBED);
14645 	wq_create = &mbox->u.mqe.un.wq_create;
14646 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
14647 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
14648 		    wq->page_count);
14649 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
14650 		    cq->queue_id);
14651 
14652 	/* wqv is the earliest version supported, NOT the latest */
14653 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
14654 	       phba->sli4_hba.pc_sli4_params.wqv);
14655 
14656 	switch (phba->sli4_hba.pc_sli4_params.wqv) {
14657 	case LPFC_Q_CREATE_VERSION_0:
14658 		switch (wq->entry_size) {
14659 		default:
14660 		case 64:
14661 			/* Nothing to do, version 0 ONLY supports 64 byte */
14662 			page = wq_create->u.request.page;
14663 			break;
14664 		case 128:
14665 			if (!(phba->sli4_hba.pc_sli4_params.wqsize &
14666 			    LPFC_WQ_SZ128_SUPPORT)) {
14667 				status = -ERANGE;
14668 				goto out;
14669 			}
14670 			/* If we get here the HBA MUST also support V1 and
14671 			 * we MUST use it
14672 			 */
14673 			bf_set(lpfc_mbox_hdr_version, &shdr->request,
14674 			       LPFC_Q_CREATE_VERSION_1);
14675 
14676 			bf_set(lpfc_mbx_wq_create_wqe_count,
14677 			       &wq_create->u.request_1, wq->entry_count);
14678 			bf_set(lpfc_mbx_wq_create_wqe_size,
14679 			       &wq_create->u.request_1,
14680 			       LPFC_WQ_WQE_SIZE_128);
14681 			bf_set(lpfc_mbx_wq_create_page_size,
14682 			       &wq_create->u.request_1,
14683 			       LPFC_WQ_PAGE_SIZE_4096);
14684 			page = wq_create->u.request_1.page;
14685 			break;
14686 		}
14687 		break;
14688 	case LPFC_Q_CREATE_VERSION_1:
14689 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
14690 		       wq->entry_count);
14691 		switch (wq->entry_size) {
14692 		default:
14693 		case 64:
14694 			bf_set(lpfc_mbx_wq_create_wqe_size,
14695 			       &wq_create->u.request_1,
14696 			       LPFC_WQ_WQE_SIZE_64);
14697 			break;
14698 		case 128:
14699 			if (!(phba->sli4_hba.pc_sli4_params.wqsize &
14700 				LPFC_WQ_SZ128_SUPPORT)) {
14701 				status = -ERANGE;
14702 				goto out;
14703 			}
14704 			bf_set(lpfc_mbx_wq_create_wqe_size,
14705 			       &wq_create->u.request_1,
14706 			       LPFC_WQ_WQE_SIZE_128);
14707 			break;
14708 		}
14709 		bf_set(lpfc_mbx_wq_create_page_size,
14710 		       &wq_create->u.request_1,
14711 		       LPFC_WQ_PAGE_SIZE_4096);
14712 		page = wq_create->u.request_1.page;
14713 		break;
14714 	default:
14715 		status = -ERANGE;
14716 		goto out;
14717 	}
14718 
14719 	list_for_each_entry(dmabuf, &wq->page_list, list) {
14720 		memset(dmabuf->virt, 0, hw_page_size);
14721 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
14722 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
14723 	}
14724 
14725 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
14726 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
14727 
14728 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14729 	/* The IOCTL status is embedded in the mailbox subheader. */
14730 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14731 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14732 	if (shdr_status || shdr_add_status || rc) {
14733 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14734 				"2503 WQ_CREATE mailbox failed with "
14735 				"status x%x add_status x%x, mbx status x%x\n",
14736 				shdr_status, shdr_add_status, rc);
14737 		status = -ENXIO;
14738 		goto out;
14739 	}
14740 	wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id, &wq_create->u.response);
14741 	if (wq->queue_id == 0xFFFF) {
14742 		status = -ENXIO;
14743 		goto out;
14744 	}
14745 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
14746 		wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
14747 				       &wq_create->u.response);
14748 		if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
14749 		    (wq->db_format != LPFC_DB_RING_FORMAT)) {
14750 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14751 					"3265 WQ[%d] doorbell format not "
14752 					"supported: x%x\n", wq->queue_id,
14753 					wq->db_format);
14754 			status = -EINVAL;
14755 			goto out;
14756 		}
14757 		pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
14758 				    &wq_create->u.response);
14759 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
14760 		if (!bar_memmap_p) {
14761 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14762 					"3263 WQ[%d] failed to memmap pci "
14763 					"barset:x%x\n", wq->queue_id,
14764 					pci_barset);
14765 			status = -ENOMEM;
14766 			goto out;
14767 		}
14768 		db_offset = wq_create->u.response.doorbell_offset;
14769 		if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
14770 		    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
14771 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14772 					"3252 WQ[%d] doorbell offset not "
14773 					"supported: x%x\n", wq->queue_id,
14774 					db_offset);
14775 			status = -EINVAL;
14776 			goto out;
14777 		}
14778 		wq->db_regaddr = bar_memmap_p + db_offset;
14779 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14780 				"3264 WQ[%d]: barset:x%x, offset:x%x, "
14781 				"format:x%x\n", wq->queue_id, pci_barset,
14782 				db_offset, wq->db_format);
14783 	} else {
14784 		wq->db_format = LPFC_DB_LIST_FORMAT;
14785 		wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
14786 	}
14787 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
14788 	if (wq->pring == NULL) {
14789 		status = -ENOMEM;
14790 		goto out;
14791 	}
14792 	wq->type = LPFC_WQ;
14793 	wq->assoc_qid = cq->queue_id;
14794 	wq->subtype = subtype;
14795 	wq->host_index = 0;
14796 	wq->hba_index = 0;
14797 	wq->entry_repost = LPFC_RELEASE_NOTIFICATION_INTERVAL;
14798 
14799 	/* link the wq onto the parent cq child list */
14800 	list_add_tail(&wq->list, &cq->child_list);
14801 out:
14802 	mempool_free(mbox, phba->mbox_mem_pool);
14803 	return status;
14804 }
14805 
14806 /**
14807  * lpfc_rq_adjust_repost - Adjust entry_repost for an RQ
14808  * @phba: HBA structure that indicates port to create a queue on.
14809  * @rq:   The queue structure to use for the receive queue.
14810  * @qno:  The associated HBQ number
14811  *
14812  *
14813  * For SLI4 we need to adjust the RQ repost value based on
14814  * the number of buffers that are initially posted to the RQ.
14815  */
14816 void
14817 lpfc_rq_adjust_repost(struct lpfc_hba *phba, struct lpfc_queue *rq, int qno)
14818 {
14819 	uint32_t cnt;
14820 
14821 	/* sanity check on queue memory */
14822 	if (!rq)
14823 		return;
14824 	cnt = lpfc_hbq_defs[qno]->entry_count;
14825 
14826 	/* Recalc repost for RQs based on buffers initially posted */
14827 	cnt = (cnt >> 3);
14828 	if (cnt < LPFC_QUEUE_MIN_REPOST)
14829 		cnt = LPFC_QUEUE_MIN_REPOST;
14830 
14831 	rq->entry_repost = cnt;
14832 }
14833 
14834 /**
14835  * lpfc_rq_create - Create a Receive Queue on the HBA
14836  * @phba: HBA structure that indicates port to create a queue on.
14837  * @hrq: The queue structure to use to create the header receive queue.
14838  * @drq: The queue structure to use to create the data receive queue.
14839  * @cq: The completion queue to bind this work queue to.
14840  *
14841  * This function creates a receive buffer queue pair , as detailed in @hrq and
14842  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
14843  * to the HBA.
14844  *
14845  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
14846  * struct is used to get the entry count that is necessary to determine the
14847  * number of pages to use for this queue. The @cq is used to indicate which
14848  * completion queue to bind received buffers that are posted to these queues to.
14849  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
14850  * receive queue pair. This function is asynchronous and will wait for the
14851  * mailbox command to finish before continuing.
14852  *
14853  * On success this function will return a zero. If unable to allocate enough
14854  * memory this function will return -ENOMEM. If the queue create mailbox command
14855  * fails this function will return -ENXIO.
14856  **/
14857 int
14858 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
14859 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
14860 {
14861 	struct lpfc_mbx_rq_create *rq_create;
14862 	struct lpfc_dmabuf *dmabuf;
14863 	LPFC_MBOXQ_t *mbox;
14864 	int rc, length, status = 0;
14865 	uint32_t shdr_status, shdr_add_status;
14866 	union lpfc_sli4_cfg_shdr *shdr;
14867 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14868 	void __iomem *bar_memmap_p;
14869 	uint32_t db_offset;
14870 	uint16_t pci_barset;
14871 
14872 	/* sanity check on queue memory */
14873 	if (!hrq || !drq || !cq)
14874 		return -ENODEV;
14875 	if (!phba->sli4_hba.pc_sli4_params.supported)
14876 		hw_page_size = SLI4_PAGE_SIZE;
14877 
14878 	if (hrq->entry_count != drq->entry_count)
14879 		return -EINVAL;
14880 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14881 	if (!mbox)
14882 		return -ENOMEM;
14883 	length = (sizeof(struct lpfc_mbx_rq_create) -
14884 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14885 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14886 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
14887 			 length, LPFC_SLI4_MBX_EMBED);
14888 	rq_create = &mbox->u.mqe.un.rq_create;
14889 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
14890 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
14891 	       phba->sli4_hba.pc_sli4_params.rqv);
14892 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
14893 		bf_set(lpfc_rq_context_rqe_count_1,
14894 		       &rq_create->u.request.context,
14895 		       hrq->entry_count);
14896 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
14897 		bf_set(lpfc_rq_context_rqe_size,
14898 		       &rq_create->u.request.context,
14899 		       LPFC_RQE_SIZE_8);
14900 		bf_set(lpfc_rq_context_page_size,
14901 		       &rq_create->u.request.context,
14902 		       LPFC_RQ_PAGE_SIZE_4096);
14903 	} else {
14904 		switch (hrq->entry_count) {
14905 		default:
14906 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14907 					"2535 Unsupported RQ count. (%d)\n",
14908 					hrq->entry_count);
14909 			if (hrq->entry_count < 512) {
14910 				status = -EINVAL;
14911 				goto out;
14912 			}
14913 			/* otherwise default to smallest count (drop through) */
14914 		case 512:
14915 			bf_set(lpfc_rq_context_rqe_count,
14916 			       &rq_create->u.request.context,
14917 			       LPFC_RQ_RING_SIZE_512);
14918 			break;
14919 		case 1024:
14920 			bf_set(lpfc_rq_context_rqe_count,
14921 			       &rq_create->u.request.context,
14922 			       LPFC_RQ_RING_SIZE_1024);
14923 			break;
14924 		case 2048:
14925 			bf_set(lpfc_rq_context_rqe_count,
14926 			       &rq_create->u.request.context,
14927 			       LPFC_RQ_RING_SIZE_2048);
14928 			break;
14929 		case 4096:
14930 			bf_set(lpfc_rq_context_rqe_count,
14931 			       &rq_create->u.request.context,
14932 			       LPFC_RQ_RING_SIZE_4096);
14933 			break;
14934 		}
14935 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
14936 		       LPFC_HDR_BUF_SIZE);
14937 	}
14938 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
14939 	       cq->queue_id);
14940 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
14941 	       hrq->page_count);
14942 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
14943 		memset(dmabuf->virt, 0, hw_page_size);
14944 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
14945 					putPaddrLow(dmabuf->phys);
14946 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
14947 					putPaddrHigh(dmabuf->phys);
14948 	}
14949 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
14950 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
14951 
14952 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14953 	/* The IOCTL status is embedded in the mailbox subheader. */
14954 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14955 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14956 	if (shdr_status || shdr_add_status || rc) {
14957 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14958 				"2504 RQ_CREATE mailbox failed with "
14959 				"status x%x add_status x%x, mbx status x%x\n",
14960 				shdr_status, shdr_add_status, rc);
14961 		status = -ENXIO;
14962 		goto out;
14963 	}
14964 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
14965 	if (hrq->queue_id == 0xFFFF) {
14966 		status = -ENXIO;
14967 		goto out;
14968 	}
14969 
14970 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
14971 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
14972 					&rq_create->u.response);
14973 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
14974 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
14975 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14976 					"3262 RQ [%d] doorbell format not "
14977 					"supported: x%x\n", hrq->queue_id,
14978 					hrq->db_format);
14979 			status = -EINVAL;
14980 			goto out;
14981 		}
14982 
14983 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
14984 				    &rq_create->u.response);
14985 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
14986 		if (!bar_memmap_p) {
14987 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14988 					"3269 RQ[%d] failed to memmap pci "
14989 					"barset:x%x\n", hrq->queue_id,
14990 					pci_barset);
14991 			status = -ENOMEM;
14992 			goto out;
14993 		}
14994 
14995 		db_offset = rq_create->u.response.doorbell_offset;
14996 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
14997 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
14998 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14999 					"3270 RQ[%d] doorbell offset not "
15000 					"supported: x%x\n", hrq->queue_id,
15001 					db_offset);
15002 			status = -EINVAL;
15003 			goto out;
15004 		}
15005 		hrq->db_regaddr = bar_memmap_p + db_offset;
15006 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15007 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
15008 				"format:x%x\n", hrq->queue_id, pci_barset,
15009 				db_offset, hrq->db_format);
15010 	} else {
15011 		hrq->db_format = LPFC_DB_RING_FORMAT;
15012 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
15013 	}
15014 	hrq->type = LPFC_HRQ;
15015 	hrq->assoc_qid = cq->queue_id;
15016 	hrq->subtype = subtype;
15017 	hrq->host_index = 0;
15018 	hrq->hba_index = 0;
15019 
15020 	/* now create the data queue */
15021 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15022 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
15023 			 length, LPFC_SLI4_MBX_EMBED);
15024 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15025 	       phba->sli4_hba.pc_sli4_params.rqv);
15026 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
15027 		bf_set(lpfc_rq_context_rqe_count_1,
15028 		       &rq_create->u.request.context, hrq->entry_count);
15029 		rq_create->u.request.context.buffer_size = LPFC_DATA_BUF_SIZE;
15030 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
15031 		       LPFC_RQE_SIZE_8);
15032 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
15033 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
15034 	} else {
15035 		switch (drq->entry_count) {
15036 		default:
15037 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15038 					"2536 Unsupported RQ count. (%d)\n",
15039 					drq->entry_count);
15040 			if (drq->entry_count < 512) {
15041 				status = -EINVAL;
15042 				goto out;
15043 			}
15044 			/* otherwise default to smallest count (drop through) */
15045 		case 512:
15046 			bf_set(lpfc_rq_context_rqe_count,
15047 			       &rq_create->u.request.context,
15048 			       LPFC_RQ_RING_SIZE_512);
15049 			break;
15050 		case 1024:
15051 			bf_set(lpfc_rq_context_rqe_count,
15052 			       &rq_create->u.request.context,
15053 			       LPFC_RQ_RING_SIZE_1024);
15054 			break;
15055 		case 2048:
15056 			bf_set(lpfc_rq_context_rqe_count,
15057 			       &rq_create->u.request.context,
15058 			       LPFC_RQ_RING_SIZE_2048);
15059 			break;
15060 		case 4096:
15061 			bf_set(lpfc_rq_context_rqe_count,
15062 			       &rq_create->u.request.context,
15063 			       LPFC_RQ_RING_SIZE_4096);
15064 			break;
15065 		}
15066 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
15067 		       LPFC_DATA_BUF_SIZE);
15068 	}
15069 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
15070 	       cq->queue_id);
15071 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
15072 	       drq->page_count);
15073 	list_for_each_entry(dmabuf, &drq->page_list, list) {
15074 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15075 					putPaddrLow(dmabuf->phys);
15076 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15077 					putPaddrHigh(dmabuf->phys);
15078 	}
15079 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
15080 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
15081 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15082 	/* The IOCTL status is embedded in the mailbox subheader. */
15083 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
15084 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15085 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15086 	if (shdr_status || shdr_add_status || rc) {
15087 		status = -ENXIO;
15088 		goto out;
15089 	}
15090 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
15091 	if (drq->queue_id == 0xFFFF) {
15092 		status = -ENXIO;
15093 		goto out;
15094 	}
15095 	drq->type = LPFC_DRQ;
15096 	drq->assoc_qid = cq->queue_id;
15097 	drq->subtype = subtype;
15098 	drq->host_index = 0;
15099 	drq->hba_index = 0;
15100 
15101 	/* link the header and data RQs onto the parent cq child list */
15102 	list_add_tail(&hrq->list, &cq->child_list);
15103 	list_add_tail(&drq->list, &cq->child_list);
15104 
15105 out:
15106 	mempool_free(mbox, phba->mbox_mem_pool);
15107 	return status;
15108 }
15109 
15110 /**
15111  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
15112  * @phba: HBA structure that indicates port to create a queue on.
15113  * @hrqp: The queue structure array to use to create the header receive queues.
15114  * @drqp: The queue structure array to use to create the data receive queues.
15115  * @cqp: The completion queue array to bind these receive queues to.
15116  *
15117  * This function creates a receive buffer queue pair , as detailed in @hrq and
15118  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
15119  * to the HBA.
15120  *
15121  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
15122  * struct is used to get the entry count that is necessary to determine the
15123  * number of pages to use for this queue. The @cq is used to indicate which
15124  * completion queue to bind received buffers that are posted to these queues to.
15125  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
15126  * receive queue pair. This function is asynchronous and will wait for the
15127  * mailbox command to finish before continuing.
15128  *
15129  * On success this function will return a zero. If unable to allocate enough
15130  * memory this function will return -ENOMEM. If the queue create mailbox command
15131  * fails this function will return -ENXIO.
15132  **/
15133 int
15134 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
15135 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
15136 		uint32_t subtype)
15137 {
15138 	struct lpfc_queue *hrq, *drq, *cq;
15139 	struct lpfc_mbx_rq_create_v2 *rq_create;
15140 	struct lpfc_dmabuf *dmabuf;
15141 	LPFC_MBOXQ_t *mbox;
15142 	int rc, length, alloclen, status = 0;
15143 	int cnt, idx, numrq, page_idx = 0;
15144 	uint32_t shdr_status, shdr_add_status;
15145 	union lpfc_sli4_cfg_shdr *shdr;
15146 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15147 
15148 	numrq = phba->cfg_nvmet_mrq;
15149 	/* sanity check on array memory */
15150 	if (!hrqp || !drqp || !cqp || !numrq)
15151 		return -ENODEV;
15152 	if (!phba->sli4_hba.pc_sli4_params.supported)
15153 		hw_page_size = SLI4_PAGE_SIZE;
15154 
15155 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15156 	if (!mbox)
15157 		return -ENOMEM;
15158 
15159 	length = sizeof(struct lpfc_mbx_rq_create_v2);
15160 	length += ((2 * numrq * hrqp[0]->page_count) *
15161 		   sizeof(struct dma_address));
15162 
15163 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15164 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
15165 				    LPFC_SLI4_MBX_NEMBED);
15166 	if (alloclen < length) {
15167 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15168 				"3099 Allocated DMA memory size (%d) is "
15169 				"less than the requested DMA memory size "
15170 				"(%d)\n", alloclen, length);
15171 		status = -ENOMEM;
15172 		goto out;
15173 	}
15174 
15175 
15176 
15177 	rq_create = mbox->sge_array->addr[0];
15178 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
15179 
15180 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
15181 	cnt = 0;
15182 
15183 	for (idx = 0; idx < numrq; idx++) {
15184 		hrq = hrqp[idx];
15185 		drq = drqp[idx];
15186 		cq  = cqp[idx];
15187 
15188 		if (hrq->entry_count != drq->entry_count) {
15189 			status = -EINVAL;
15190 			goto out;
15191 		}
15192 
15193 		/* sanity check on queue memory */
15194 		if (!hrq || !drq || !cq) {
15195 			status = -ENODEV;
15196 			goto out;
15197 		}
15198 
15199 		if (idx == 0) {
15200 			bf_set(lpfc_mbx_rq_create_num_pages,
15201 			       &rq_create->u.request,
15202 			       hrq->page_count);
15203 			bf_set(lpfc_mbx_rq_create_rq_cnt,
15204 			       &rq_create->u.request, (numrq * 2));
15205 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
15206 			       1);
15207 			bf_set(lpfc_rq_context_base_cq,
15208 			       &rq_create->u.request.context,
15209 			       cq->queue_id);
15210 			bf_set(lpfc_rq_context_data_size,
15211 			       &rq_create->u.request.context,
15212 			       LPFC_DATA_BUF_SIZE);
15213 			bf_set(lpfc_rq_context_hdr_size,
15214 			       &rq_create->u.request.context,
15215 			       LPFC_HDR_BUF_SIZE);
15216 			bf_set(lpfc_rq_context_rqe_count_1,
15217 			       &rq_create->u.request.context,
15218 			       hrq->entry_count);
15219 			bf_set(lpfc_rq_context_rqe_size,
15220 			       &rq_create->u.request.context,
15221 			       LPFC_RQE_SIZE_8);
15222 			bf_set(lpfc_rq_context_page_size,
15223 			       &rq_create->u.request.context,
15224 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
15225 		}
15226 		rc = 0;
15227 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
15228 			memset(dmabuf->virt, 0, hw_page_size);
15229 			cnt = page_idx + dmabuf->buffer_tag;
15230 			rq_create->u.request.page[cnt].addr_lo =
15231 					putPaddrLow(dmabuf->phys);
15232 			rq_create->u.request.page[cnt].addr_hi =
15233 					putPaddrHigh(dmabuf->phys);
15234 			rc++;
15235 		}
15236 		page_idx += rc;
15237 
15238 		rc = 0;
15239 		list_for_each_entry(dmabuf, &drq->page_list, list) {
15240 			memset(dmabuf->virt, 0, hw_page_size);
15241 			cnt = page_idx + dmabuf->buffer_tag;
15242 			rq_create->u.request.page[cnt].addr_lo =
15243 					putPaddrLow(dmabuf->phys);
15244 			rq_create->u.request.page[cnt].addr_hi =
15245 					putPaddrHigh(dmabuf->phys);
15246 			rc++;
15247 		}
15248 		page_idx += rc;
15249 
15250 		hrq->db_format = LPFC_DB_RING_FORMAT;
15251 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
15252 		hrq->type = LPFC_HRQ;
15253 		hrq->assoc_qid = cq->queue_id;
15254 		hrq->subtype = subtype;
15255 		hrq->host_index = 0;
15256 		hrq->hba_index = 0;
15257 
15258 		drq->db_format = LPFC_DB_RING_FORMAT;
15259 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
15260 		drq->type = LPFC_DRQ;
15261 		drq->assoc_qid = cq->queue_id;
15262 		drq->subtype = subtype;
15263 		drq->host_index = 0;
15264 		drq->hba_index = 0;
15265 
15266 		list_add_tail(&hrq->list, &cq->child_list);
15267 		list_add_tail(&drq->list, &cq->child_list);
15268 	}
15269 
15270 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15271 	/* The IOCTL status is embedded in the mailbox subheader. */
15272 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15273 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15274 	if (shdr_status || shdr_add_status || rc) {
15275 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15276 				"3120 RQ_CREATE mailbox failed with "
15277 				"status x%x add_status x%x, mbx status x%x\n",
15278 				shdr_status, shdr_add_status, rc);
15279 		status = -ENXIO;
15280 		goto out;
15281 	}
15282 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
15283 	if (rc == 0xFFFF) {
15284 		status = -ENXIO;
15285 		goto out;
15286 	}
15287 
15288 	/* Initialize all RQs with associated queue id */
15289 	for (idx = 0; idx < numrq; idx++) {
15290 		hrq = hrqp[idx];
15291 		hrq->queue_id = rc + (2 * idx);
15292 		drq = drqp[idx];
15293 		drq->queue_id = rc + (2 * idx) + 1;
15294 	}
15295 
15296 out:
15297 	lpfc_sli4_mbox_cmd_free(phba, mbox);
15298 	return status;
15299 }
15300 
15301 /**
15302  * lpfc_eq_destroy - Destroy an event Queue on the HBA
15303  * @eq: The queue structure associated with the queue to destroy.
15304  *
15305  * This function destroys a queue, as detailed in @eq by sending an mailbox
15306  * command, specific to the type of queue, to the HBA.
15307  *
15308  * The @eq struct is used to get the queue ID of the queue to destroy.
15309  *
15310  * On success this function will return a zero. If the queue destroy mailbox
15311  * command fails this function will return -ENXIO.
15312  **/
15313 int
15314 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
15315 {
15316 	LPFC_MBOXQ_t *mbox;
15317 	int rc, length, status = 0;
15318 	uint32_t shdr_status, shdr_add_status;
15319 	union lpfc_sli4_cfg_shdr *shdr;
15320 
15321 	/* sanity check on queue memory */
15322 	if (!eq)
15323 		return -ENODEV;
15324 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
15325 	if (!mbox)
15326 		return -ENOMEM;
15327 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
15328 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15329 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15330 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
15331 			 length, LPFC_SLI4_MBX_EMBED);
15332 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
15333 	       eq->queue_id);
15334 	mbox->vport = eq->phba->pport;
15335 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15336 
15337 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
15338 	/* The IOCTL status is embedded in the mailbox subheader. */
15339 	shdr = (union lpfc_sli4_cfg_shdr *)
15340 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
15341 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15342 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15343 	if (shdr_status || shdr_add_status || rc) {
15344 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15345 				"2505 EQ_DESTROY mailbox failed with "
15346 				"status x%x add_status x%x, mbx status x%x\n",
15347 				shdr_status, shdr_add_status, rc);
15348 		status = -ENXIO;
15349 	}
15350 
15351 	/* Remove eq from any list */
15352 	list_del_init(&eq->list);
15353 	mempool_free(mbox, eq->phba->mbox_mem_pool);
15354 	return status;
15355 }
15356 
15357 /**
15358  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
15359  * @cq: The queue structure associated with the queue to destroy.
15360  *
15361  * This function destroys a queue, as detailed in @cq by sending an mailbox
15362  * command, specific to the type of queue, to the HBA.
15363  *
15364  * The @cq struct is used to get the queue ID of the queue to destroy.
15365  *
15366  * On success this function will return a zero. If the queue destroy mailbox
15367  * command fails this function will return -ENXIO.
15368  **/
15369 int
15370 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
15371 {
15372 	LPFC_MBOXQ_t *mbox;
15373 	int rc, length, status = 0;
15374 	uint32_t shdr_status, shdr_add_status;
15375 	union lpfc_sli4_cfg_shdr *shdr;
15376 
15377 	/* sanity check on queue memory */
15378 	if (!cq)
15379 		return -ENODEV;
15380 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
15381 	if (!mbox)
15382 		return -ENOMEM;
15383 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
15384 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15385 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15386 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
15387 			 length, LPFC_SLI4_MBX_EMBED);
15388 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
15389 	       cq->queue_id);
15390 	mbox->vport = cq->phba->pport;
15391 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15392 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
15393 	/* The IOCTL status is embedded in the mailbox subheader. */
15394 	shdr = (union lpfc_sli4_cfg_shdr *)
15395 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
15396 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15397 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15398 	if (shdr_status || shdr_add_status || rc) {
15399 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15400 				"2506 CQ_DESTROY mailbox failed with "
15401 				"status x%x add_status x%x, mbx status x%x\n",
15402 				shdr_status, shdr_add_status, rc);
15403 		status = -ENXIO;
15404 	}
15405 	/* Remove cq from any list */
15406 	list_del_init(&cq->list);
15407 	mempool_free(mbox, cq->phba->mbox_mem_pool);
15408 	return status;
15409 }
15410 
15411 /**
15412  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
15413  * @qm: The queue structure associated with the queue to destroy.
15414  *
15415  * This function destroys a queue, as detailed in @mq by sending an mailbox
15416  * command, specific to the type of queue, to the HBA.
15417  *
15418  * The @mq struct is used to get the queue ID of the queue to destroy.
15419  *
15420  * On success this function will return a zero. If the queue destroy mailbox
15421  * command fails this function will return -ENXIO.
15422  **/
15423 int
15424 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
15425 {
15426 	LPFC_MBOXQ_t *mbox;
15427 	int rc, length, status = 0;
15428 	uint32_t shdr_status, shdr_add_status;
15429 	union lpfc_sli4_cfg_shdr *shdr;
15430 
15431 	/* sanity check on queue memory */
15432 	if (!mq)
15433 		return -ENODEV;
15434 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
15435 	if (!mbox)
15436 		return -ENOMEM;
15437 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
15438 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15439 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15440 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
15441 			 length, LPFC_SLI4_MBX_EMBED);
15442 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
15443 	       mq->queue_id);
15444 	mbox->vport = mq->phba->pport;
15445 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15446 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
15447 	/* The IOCTL status is embedded in the mailbox subheader. */
15448 	shdr = (union lpfc_sli4_cfg_shdr *)
15449 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
15450 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15451 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15452 	if (shdr_status || shdr_add_status || rc) {
15453 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15454 				"2507 MQ_DESTROY mailbox failed with "
15455 				"status x%x add_status x%x, mbx status x%x\n",
15456 				shdr_status, shdr_add_status, rc);
15457 		status = -ENXIO;
15458 	}
15459 	/* Remove mq from any list */
15460 	list_del_init(&mq->list);
15461 	mempool_free(mbox, mq->phba->mbox_mem_pool);
15462 	return status;
15463 }
15464 
15465 /**
15466  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
15467  * @wq: The queue structure associated with the queue to destroy.
15468  *
15469  * This function destroys a queue, as detailed in @wq by sending an mailbox
15470  * command, specific to the type of queue, to the HBA.
15471  *
15472  * The @wq struct is used to get the queue ID of the queue to destroy.
15473  *
15474  * On success this function will return a zero. If the queue destroy mailbox
15475  * command fails this function will return -ENXIO.
15476  **/
15477 int
15478 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
15479 {
15480 	LPFC_MBOXQ_t *mbox;
15481 	int rc, length, status = 0;
15482 	uint32_t shdr_status, shdr_add_status;
15483 	union lpfc_sli4_cfg_shdr *shdr;
15484 
15485 	/* sanity check on queue memory */
15486 	if (!wq)
15487 		return -ENODEV;
15488 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
15489 	if (!mbox)
15490 		return -ENOMEM;
15491 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
15492 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15493 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15494 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
15495 			 length, LPFC_SLI4_MBX_EMBED);
15496 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
15497 	       wq->queue_id);
15498 	mbox->vport = wq->phba->pport;
15499 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15500 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
15501 	shdr = (union lpfc_sli4_cfg_shdr *)
15502 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
15503 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15504 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15505 	if (shdr_status || shdr_add_status || rc) {
15506 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15507 				"2508 WQ_DESTROY mailbox failed with "
15508 				"status x%x add_status x%x, mbx status x%x\n",
15509 				shdr_status, shdr_add_status, rc);
15510 		status = -ENXIO;
15511 	}
15512 	/* Remove wq from any list */
15513 	list_del_init(&wq->list);
15514 	mempool_free(mbox, wq->phba->mbox_mem_pool);
15515 	return status;
15516 }
15517 
15518 /**
15519  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
15520  * @rq: The queue structure associated with the queue to destroy.
15521  *
15522  * This function destroys a queue, as detailed in @rq by sending an mailbox
15523  * command, specific to the type of queue, to the HBA.
15524  *
15525  * The @rq struct is used to get the queue ID of the queue to destroy.
15526  *
15527  * On success this function will return a zero. If the queue destroy mailbox
15528  * command fails this function will return -ENXIO.
15529  **/
15530 int
15531 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
15532 		struct lpfc_queue *drq)
15533 {
15534 	LPFC_MBOXQ_t *mbox;
15535 	int rc, length, status = 0;
15536 	uint32_t shdr_status, shdr_add_status;
15537 	union lpfc_sli4_cfg_shdr *shdr;
15538 
15539 	/* sanity check on queue memory */
15540 	if (!hrq || !drq)
15541 		return -ENODEV;
15542 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
15543 	if (!mbox)
15544 		return -ENOMEM;
15545 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
15546 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15547 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15548 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
15549 			 length, LPFC_SLI4_MBX_EMBED);
15550 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
15551 	       hrq->queue_id);
15552 	mbox->vport = hrq->phba->pport;
15553 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15554 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
15555 	/* The IOCTL status is embedded in the mailbox subheader. */
15556 	shdr = (union lpfc_sli4_cfg_shdr *)
15557 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
15558 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15559 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15560 	if (shdr_status || shdr_add_status || rc) {
15561 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15562 				"2509 RQ_DESTROY mailbox failed with "
15563 				"status x%x add_status x%x, mbx status x%x\n",
15564 				shdr_status, shdr_add_status, rc);
15565 		if (rc != MBX_TIMEOUT)
15566 			mempool_free(mbox, hrq->phba->mbox_mem_pool);
15567 		return -ENXIO;
15568 	}
15569 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
15570 	       drq->queue_id);
15571 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
15572 	shdr = (union lpfc_sli4_cfg_shdr *)
15573 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
15574 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15575 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15576 	if (shdr_status || shdr_add_status || rc) {
15577 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15578 				"2510 RQ_DESTROY mailbox failed with "
15579 				"status x%x add_status x%x, mbx status x%x\n",
15580 				shdr_status, shdr_add_status, rc);
15581 		status = -ENXIO;
15582 	}
15583 	list_del_init(&hrq->list);
15584 	list_del_init(&drq->list);
15585 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
15586 	return status;
15587 }
15588 
15589 /**
15590  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
15591  * @phba: The virtual port for which this call being executed.
15592  * @pdma_phys_addr0: Physical address of the 1st SGL page.
15593  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
15594  * @xritag: the xritag that ties this io to the SGL pages.
15595  *
15596  * This routine will post the sgl pages for the IO that has the xritag
15597  * that is in the iocbq structure. The xritag is assigned during iocbq
15598  * creation and persists for as long as the driver is loaded.
15599  * if the caller has fewer than 256 scatter gather segments to map then
15600  * pdma_phys_addr1 should be 0.
15601  * If the caller needs to map more than 256 scatter gather segment then
15602  * pdma_phys_addr1 should be a valid physical address.
15603  * physical address for SGLs must be 64 byte aligned.
15604  * If you are going to map 2 SGL's then the first one must have 256 entries
15605  * the second sgl can have between 1 and 256 entries.
15606  *
15607  * Return codes:
15608  * 	0 - Success
15609  * 	-ENXIO, -ENOMEM - Failure
15610  **/
15611 int
15612 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
15613 		dma_addr_t pdma_phys_addr0,
15614 		dma_addr_t pdma_phys_addr1,
15615 		uint16_t xritag)
15616 {
15617 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
15618 	LPFC_MBOXQ_t *mbox;
15619 	int rc;
15620 	uint32_t shdr_status, shdr_add_status;
15621 	uint32_t mbox_tmo;
15622 	union lpfc_sli4_cfg_shdr *shdr;
15623 
15624 	if (xritag == NO_XRI) {
15625 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15626 				"0364 Invalid param:\n");
15627 		return -EINVAL;
15628 	}
15629 
15630 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15631 	if (!mbox)
15632 		return -ENOMEM;
15633 
15634 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15635 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
15636 			sizeof(struct lpfc_mbx_post_sgl_pages) -
15637 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
15638 
15639 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
15640 				&mbox->u.mqe.un.post_sgl_pages;
15641 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
15642 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
15643 
15644 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
15645 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
15646 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
15647 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
15648 
15649 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
15650 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
15651 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
15652 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
15653 	if (!phba->sli4_hba.intr_enable)
15654 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15655 	else {
15656 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
15657 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
15658 	}
15659 	/* The IOCTL status is embedded in the mailbox subheader. */
15660 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
15661 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15662 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15663 	if (rc != MBX_TIMEOUT)
15664 		mempool_free(mbox, phba->mbox_mem_pool);
15665 	if (shdr_status || shdr_add_status || rc) {
15666 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15667 				"2511 POST_SGL mailbox failed with "
15668 				"status x%x add_status x%x, mbx status x%x\n",
15669 				shdr_status, shdr_add_status, rc);
15670 	}
15671 	return 0;
15672 }
15673 
15674 /**
15675  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
15676  * @phba: pointer to lpfc hba data structure.
15677  *
15678  * This routine is invoked to post rpi header templates to the
15679  * HBA consistent with the SLI-4 interface spec.  This routine
15680  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
15681  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
15682  *
15683  * Returns
15684  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
15685  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
15686  **/
15687 static uint16_t
15688 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
15689 {
15690 	unsigned long xri;
15691 
15692 	/*
15693 	 * Fetch the next logical xri.  Because this index is logical,
15694 	 * the driver starts at 0 each time.
15695 	 */
15696 	spin_lock_irq(&phba->hbalock);
15697 	xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
15698 				 phba->sli4_hba.max_cfg_param.max_xri, 0);
15699 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
15700 		spin_unlock_irq(&phba->hbalock);
15701 		return NO_XRI;
15702 	} else {
15703 		set_bit(xri, phba->sli4_hba.xri_bmask);
15704 		phba->sli4_hba.max_cfg_param.xri_used++;
15705 	}
15706 	spin_unlock_irq(&phba->hbalock);
15707 	return xri;
15708 }
15709 
15710 /**
15711  * lpfc_sli4_free_xri - Release an xri for reuse.
15712  * @phba: pointer to lpfc hba data structure.
15713  *
15714  * This routine is invoked to release an xri to the pool of
15715  * available rpis maintained by the driver.
15716  **/
15717 static void
15718 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
15719 {
15720 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
15721 		phba->sli4_hba.max_cfg_param.xri_used--;
15722 	}
15723 }
15724 
15725 /**
15726  * lpfc_sli4_free_xri - Release an xri for reuse.
15727  * @phba: pointer to lpfc hba data structure.
15728  *
15729  * This routine is invoked to release an xri to the pool of
15730  * available rpis maintained by the driver.
15731  **/
15732 void
15733 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
15734 {
15735 	spin_lock_irq(&phba->hbalock);
15736 	__lpfc_sli4_free_xri(phba, xri);
15737 	spin_unlock_irq(&phba->hbalock);
15738 }
15739 
15740 /**
15741  * lpfc_sli4_next_xritag - Get an xritag for the io
15742  * @phba: Pointer to HBA context object.
15743  *
15744  * This function gets an xritag for the iocb. If there is no unused xritag
15745  * it will return 0xffff.
15746  * The function returns the allocated xritag if successful, else returns zero.
15747  * Zero is not a valid xritag.
15748  * The caller is not required to hold any lock.
15749  **/
15750 uint16_t
15751 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
15752 {
15753 	uint16_t xri_index;
15754 
15755 	xri_index = lpfc_sli4_alloc_xri(phba);
15756 	if (xri_index == NO_XRI)
15757 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15758 				"2004 Failed to allocate XRI.last XRITAG is %d"
15759 				" Max XRI is %d, Used XRI is %d\n",
15760 				xri_index,
15761 				phba->sli4_hba.max_cfg_param.max_xri,
15762 				phba->sli4_hba.max_cfg_param.xri_used);
15763 	return xri_index;
15764 }
15765 
15766 /**
15767  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
15768  * @phba: pointer to lpfc hba data structure.
15769  * @post_sgl_list: pointer to els sgl entry list.
15770  * @count: number of els sgl entries on the list.
15771  *
15772  * This routine is invoked to post a block of driver's sgl pages to the
15773  * HBA using non-embedded mailbox command. No Lock is held. This routine
15774  * is only called when the driver is loading and after all IO has been
15775  * stopped.
15776  **/
15777 static int
15778 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
15779 			    struct list_head *post_sgl_list,
15780 			    int post_cnt)
15781 {
15782 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
15783 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
15784 	struct sgl_page_pairs *sgl_pg_pairs;
15785 	void *viraddr;
15786 	LPFC_MBOXQ_t *mbox;
15787 	uint32_t reqlen, alloclen, pg_pairs;
15788 	uint32_t mbox_tmo;
15789 	uint16_t xritag_start = 0;
15790 	int rc = 0;
15791 	uint32_t shdr_status, shdr_add_status;
15792 	union lpfc_sli4_cfg_shdr *shdr;
15793 
15794 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
15795 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
15796 	if (reqlen > SLI4_PAGE_SIZE) {
15797 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15798 				"2559 Block sgl registration required DMA "
15799 				"size (%d) great than a page\n", reqlen);
15800 		return -ENOMEM;
15801 	}
15802 
15803 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15804 	if (!mbox)
15805 		return -ENOMEM;
15806 
15807 	/* Allocate DMA memory and set up the non-embedded mailbox command */
15808 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15809 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
15810 			 LPFC_SLI4_MBX_NEMBED);
15811 
15812 	if (alloclen < reqlen) {
15813 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15814 				"0285 Allocated DMA memory size (%d) is "
15815 				"less than the requested DMA memory "
15816 				"size (%d)\n", alloclen, reqlen);
15817 		lpfc_sli4_mbox_cmd_free(phba, mbox);
15818 		return -ENOMEM;
15819 	}
15820 	/* Set up the SGL pages in the non-embedded DMA pages */
15821 	viraddr = mbox->sge_array->addr[0];
15822 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
15823 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
15824 
15825 	pg_pairs = 0;
15826 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
15827 		/* Set up the sge entry */
15828 		sgl_pg_pairs->sgl_pg0_addr_lo =
15829 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
15830 		sgl_pg_pairs->sgl_pg0_addr_hi =
15831 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
15832 		sgl_pg_pairs->sgl_pg1_addr_lo =
15833 				cpu_to_le32(putPaddrLow(0));
15834 		sgl_pg_pairs->sgl_pg1_addr_hi =
15835 				cpu_to_le32(putPaddrHigh(0));
15836 
15837 		/* Keep the first xritag on the list */
15838 		if (pg_pairs == 0)
15839 			xritag_start = sglq_entry->sli4_xritag;
15840 		sgl_pg_pairs++;
15841 		pg_pairs++;
15842 	}
15843 
15844 	/* Complete initialization and perform endian conversion. */
15845 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
15846 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
15847 	sgl->word0 = cpu_to_le32(sgl->word0);
15848 
15849 	if (!phba->sli4_hba.intr_enable)
15850 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15851 	else {
15852 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
15853 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
15854 	}
15855 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
15856 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15857 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15858 	if (rc != MBX_TIMEOUT)
15859 		lpfc_sli4_mbox_cmd_free(phba, mbox);
15860 	if (shdr_status || shdr_add_status || rc) {
15861 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15862 				"2513 POST_SGL_BLOCK mailbox command failed "
15863 				"status x%x add_status x%x mbx status x%x\n",
15864 				shdr_status, shdr_add_status, rc);
15865 		rc = -ENXIO;
15866 	}
15867 	return rc;
15868 }
15869 
15870 /**
15871  * lpfc_sli4_post_scsi_sgl_block - post a block of scsi sgl list to firmware
15872  * @phba: pointer to lpfc hba data structure.
15873  * @sblist: pointer to scsi buffer list.
15874  * @count: number of scsi buffers on the list.
15875  *
15876  * This routine is invoked to post a block of @count scsi sgl pages from a
15877  * SCSI buffer list @sblist to the HBA using non-embedded mailbox command.
15878  * No Lock is held.
15879  *
15880  **/
15881 int
15882 lpfc_sli4_post_scsi_sgl_block(struct lpfc_hba *phba,
15883 			      struct list_head *sblist,
15884 			      int count)
15885 {
15886 	struct lpfc_scsi_buf *psb;
15887 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
15888 	struct sgl_page_pairs *sgl_pg_pairs;
15889 	void *viraddr;
15890 	LPFC_MBOXQ_t *mbox;
15891 	uint32_t reqlen, alloclen, pg_pairs;
15892 	uint32_t mbox_tmo;
15893 	uint16_t xritag_start = 0;
15894 	int rc = 0;
15895 	uint32_t shdr_status, shdr_add_status;
15896 	dma_addr_t pdma_phys_bpl1;
15897 	union lpfc_sli4_cfg_shdr *shdr;
15898 
15899 	/* Calculate the requested length of the dma memory */
15900 	reqlen = count * sizeof(struct sgl_page_pairs) +
15901 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
15902 	if (reqlen > SLI4_PAGE_SIZE) {
15903 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
15904 				"0217 Block sgl registration required DMA "
15905 				"size (%d) great than a page\n", reqlen);
15906 		return -ENOMEM;
15907 	}
15908 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15909 	if (!mbox) {
15910 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15911 				"0283 Failed to allocate mbox cmd memory\n");
15912 		return -ENOMEM;
15913 	}
15914 
15915 	/* Allocate DMA memory and set up the non-embedded mailbox command */
15916 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15917 				LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
15918 				LPFC_SLI4_MBX_NEMBED);
15919 
15920 	if (alloclen < reqlen) {
15921 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15922 				"2561 Allocated DMA memory size (%d) is "
15923 				"less than the requested DMA memory "
15924 				"size (%d)\n", alloclen, reqlen);
15925 		lpfc_sli4_mbox_cmd_free(phba, mbox);
15926 		return -ENOMEM;
15927 	}
15928 
15929 	/* Get the first SGE entry from the non-embedded DMA memory */
15930 	viraddr = mbox->sge_array->addr[0];
15931 
15932 	/* Set up the SGL pages in the non-embedded DMA pages */
15933 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
15934 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
15935 
15936 	pg_pairs = 0;
15937 	list_for_each_entry(psb, sblist, list) {
15938 		/* Set up the sge entry */
15939 		sgl_pg_pairs->sgl_pg0_addr_lo =
15940 			cpu_to_le32(putPaddrLow(psb->dma_phys_bpl));
15941 		sgl_pg_pairs->sgl_pg0_addr_hi =
15942 			cpu_to_le32(putPaddrHigh(psb->dma_phys_bpl));
15943 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
15944 			pdma_phys_bpl1 = psb->dma_phys_bpl + SGL_PAGE_SIZE;
15945 		else
15946 			pdma_phys_bpl1 = 0;
15947 		sgl_pg_pairs->sgl_pg1_addr_lo =
15948 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
15949 		sgl_pg_pairs->sgl_pg1_addr_hi =
15950 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
15951 		/* Keep the first xritag on the list */
15952 		if (pg_pairs == 0)
15953 			xritag_start = psb->cur_iocbq.sli4_xritag;
15954 		sgl_pg_pairs++;
15955 		pg_pairs++;
15956 	}
15957 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
15958 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
15959 	/* Perform endian conversion if necessary */
15960 	sgl->word0 = cpu_to_le32(sgl->word0);
15961 
15962 	if (!phba->sli4_hba.intr_enable)
15963 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15964 	else {
15965 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
15966 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
15967 	}
15968 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
15969 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15970 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15971 	if (rc != MBX_TIMEOUT)
15972 		lpfc_sli4_mbox_cmd_free(phba, mbox);
15973 	if (shdr_status || shdr_add_status || rc) {
15974 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15975 				"2564 POST_SGL_BLOCK mailbox command failed "
15976 				"status x%x add_status x%x mbx status x%x\n",
15977 				shdr_status, shdr_add_status, rc);
15978 		rc = -ENXIO;
15979 	}
15980 	return rc;
15981 }
15982 
15983 static char *lpfc_rctl_names[] = FC_RCTL_NAMES_INIT;
15984 static char *lpfc_type_names[] = FC_TYPE_NAMES_INIT;
15985 
15986 /**
15987  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
15988  * @phba: pointer to lpfc_hba struct that the frame was received on
15989  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
15990  *
15991  * This function checks the fields in the @fc_hdr to see if the FC frame is a
15992  * valid type of frame that the LPFC driver will handle. This function will
15993  * return a zero if the frame is a valid frame or a non zero value when the
15994  * frame does not pass the check.
15995  **/
15996 static int
15997 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
15998 {
15999 	/*  make rctl_names static to save stack space */
16000 	struct fc_vft_header *fc_vft_hdr;
16001 	uint32_t *header = (uint32_t *) fc_hdr;
16002 
16003 	switch (fc_hdr->fh_r_ctl) {
16004 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
16005 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
16006 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
16007 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
16008 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
16009 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
16010 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
16011 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
16012 	case FC_RCTL_ELS_REQ:	/* extended link services request */
16013 	case FC_RCTL_ELS_REP:	/* extended link services reply */
16014 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
16015 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
16016 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
16017 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
16018 	case FC_RCTL_BA_RMC: 	/* remove connection */
16019 	case FC_RCTL_BA_ACC:	/* basic accept */
16020 	case FC_RCTL_BA_RJT:	/* basic reject */
16021 	case FC_RCTL_BA_PRMT:
16022 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
16023 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
16024 	case FC_RCTL_P_RJT:	/* port reject */
16025 	case FC_RCTL_F_RJT:	/* fabric reject */
16026 	case FC_RCTL_P_BSY:	/* port busy */
16027 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
16028 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
16029 	case FC_RCTL_LCR:	/* link credit reset */
16030 	case FC_RCTL_END:	/* end */
16031 		break;
16032 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
16033 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
16034 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
16035 		return lpfc_fc_frame_check(phba, fc_hdr);
16036 	default:
16037 		goto drop;
16038 	}
16039 	switch (fc_hdr->fh_type) {
16040 	case FC_TYPE_BLS:
16041 	case FC_TYPE_ELS:
16042 	case FC_TYPE_FCP:
16043 	case FC_TYPE_CT:
16044 	case FC_TYPE_NVME:
16045 		break;
16046 	case FC_TYPE_IP:
16047 	case FC_TYPE_ILS:
16048 	default:
16049 		goto drop;
16050 	}
16051 
16052 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
16053 			"2538 Received frame rctl:%s (x%x), type:%s (x%x), "
16054 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
16055 			lpfc_rctl_names[fc_hdr->fh_r_ctl], fc_hdr->fh_r_ctl,
16056 			lpfc_type_names[fc_hdr->fh_type], fc_hdr->fh_type,
16057 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
16058 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
16059 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
16060 			be32_to_cpu(header[6]));
16061 	return 0;
16062 drop:
16063 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
16064 			"2539 Dropped frame rctl:%s type:%s\n",
16065 			lpfc_rctl_names[fc_hdr->fh_r_ctl],
16066 			lpfc_type_names[fc_hdr->fh_type]);
16067 	return 1;
16068 }
16069 
16070 /**
16071  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
16072  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
16073  *
16074  * This function processes the FC header to retrieve the VFI from the VF
16075  * header, if one exists. This function will return the VFI if one exists
16076  * or 0 if no VSAN Header exists.
16077  **/
16078 static uint32_t
16079 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
16080 {
16081 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
16082 
16083 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
16084 		return 0;
16085 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
16086 }
16087 
16088 /**
16089  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
16090  * @phba: Pointer to the HBA structure to search for the vport on
16091  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
16092  * @fcfi: The FC Fabric ID that the frame came from
16093  *
16094  * This function searches the @phba for a vport that matches the content of the
16095  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
16096  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
16097  * returns the matching vport pointer or NULL if unable to match frame to a
16098  * vport.
16099  **/
16100 static struct lpfc_vport *
16101 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
16102 		       uint16_t fcfi, uint32_t did)
16103 {
16104 	struct lpfc_vport **vports;
16105 	struct lpfc_vport *vport = NULL;
16106 	int i;
16107 
16108 	if (did == Fabric_DID)
16109 		return phba->pport;
16110 	if ((phba->pport->fc_flag & FC_PT2PT) &&
16111 		!(phba->link_state == LPFC_HBA_READY))
16112 		return phba->pport;
16113 
16114 	vports = lpfc_create_vport_work_array(phba);
16115 	if (vports != NULL) {
16116 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
16117 			if (phba->fcf.fcfi == fcfi &&
16118 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
16119 			    vports[i]->fc_myDID == did) {
16120 				vport = vports[i];
16121 				break;
16122 			}
16123 		}
16124 	}
16125 	lpfc_destroy_vport_work_array(phba, vports);
16126 	return vport;
16127 }
16128 
16129 /**
16130  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
16131  * @vport: The vport to work on.
16132  *
16133  * This function updates the receive sequence time stamp for this vport. The
16134  * receive sequence time stamp indicates the time that the last frame of the
16135  * the sequence that has been idle for the longest amount of time was received.
16136  * the driver uses this time stamp to indicate if any received sequences have
16137  * timed out.
16138  **/
16139 static void
16140 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
16141 {
16142 	struct lpfc_dmabuf *h_buf;
16143 	struct hbq_dmabuf *dmabuf = NULL;
16144 
16145 	/* get the oldest sequence on the rcv list */
16146 	h_buf = list_get_first(&vport->rcv_buffer_list,
16147 			       struct lpfc_dmabuf, list);
16148 	if (!h_buf)
16149 		return;
16150 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
16151 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
16152 }
16153 
16154 /**
16155  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
16156  * @vport: The vport that the received sequences were sent to.
16157  *
16158  * This function cleans up all outstanding received sequences. This is called
16159  * by the driver when a link event or user action invalidates all the received
16160  * sequences.
16161  **/
16162 void
16163 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
16164 {
16165 	struct lpfc_dmabuf *h_buf, *hnext;
16166 	struct lpfc_dmabuf *d_buf, *dnext;
16167 	struct hbq_dmabuf *dmabuf = NULL;
16168 
16169 	/* start with the oldest sequence on the rcv list */
16170 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
16171 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
16172 		list_del_init(&dmabuf->hbuf.list);
16173 		list_for_each_entry_safe(d_buf, dnext,
16174 					 &dmabuf->dbuf.list, list) {
16175 			list_del_init(&d_buf->list);
16176 			lpfc_in_buf_free(vport->phba, d_buf);
16177 		}
16178 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
16179 	}
16180 }
16181 
16182 /**
16183  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
16184  * @vport: The vport that the received sequences were sent to.
16185  *
16186  * This function determines whether any received sequences have timed out by
16187  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
16188  * indicates that there is at least one timed out sequence this routine will
16189  * go through the received sequences one at a time from most inactive to most
16190  * active to determine which ones need to be cleaned up. Once it has determined
16191  * that a sequence needs to be cleaned up it will simply free up the resources
16192  * without sending an abort.
16193  **/
16194 void
16195 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
16196 {
16197 	struct lpfc_dmabuf *h_buf, *hnext;
16198 	struct lpfc_dmabuf *d_buf, *dnext;
16199 	struct hbq_dmabuf *dmabuf = NULL;
16200 	unsigned long timeout;
16201 	int abort_count = 0;
16202 
16203 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
16204 		   vport->rcv_buffer_time_stamp);
16205 	if (list_empty(&vport->rcv_buffer_list) ||
16206 	    time_before(jiffies, timeout))
16207 		return;
16208 	/* start with the oldest sequence on the rcv list */
16209 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
16210 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
16211 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
16212 			   dmabuf->time_stamp);
16213 		if (time_before(jiffies, timeout))
16214 			break;
16215 		abort_count++;
16216 		list_del_init(&dmabuf->hbuf.list);
16217 		list_for_each_entry_safe(d_buf, dnext,
16218 					 &dmabuf->dbuf.list, list) {
16219 			list_del_init(&d_buf->list);
16220 			lpfc_in_buf_free(vport->phba, d_buf);
16221 		}
16222 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
16223 	}
16224 	if (abort_count)
16225 		lpfc_update_rcv_time_stamp(vport);
16226 }
16227 
16228 /**
16229  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
16230  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
16231  *
16232  * This function searches through the existing incomplete sequences that have
16233  * been sent to this @vport. If the frame matches one of the incomplete
16234  * sequences then the dbuf in the @dmabuf is added to the list of frames that
16235  * make up that sequence. If no sequence is found that matches this frame then
16236  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
16237  * This function returns a pointer to the first dmabuf in the sequence list that
16238  * the frame was linked to.
16239  **/
16240 static struct hbq_dmabuf *
16241 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
16242 {
16243 	struct fc_frame_header *new_hdr;
16244 	struct fc_frame_header *temp_hdr;
16245 	struct lpfc_dmabuf *d_buf;
16246 	struct lpfc_dmabuf *h_buf;
16247 	struct hbq_dmabuf *seq_dmabuf = NULL;
16248 	struct hbq_dmabuf *temp_dmabuf = NULL;
16249 	uint8_t	found = 0;
16250 
16251 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
16252 	dmabuf->time_stamp = jiffies;
16253 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
16254 
16255 	/* Use the hdr_buf to find the sequence that this frame belongs to */
16256 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
16257 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
16258 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
16259 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
16260 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
16261 			continue;
16262 		/* found a pending sequence that matches this frame */
16263 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
16264 		break;
16265 	}
16266 	if (!seq_dmabuf) {
16267 		/*
16268 		 * This indicates first frame received for this sequence.
16269 		 * Queue the buffer on the vport's rcv_buffer_list.
16270 		 */
16271 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
16272 		lpfc_update_rcv_time_stamp(vport);
16273 		return dmabuf;
16274 	}
16275 	temp_hdr = seq_dmabuf->hbuf.virt;
16276 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
16277 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
16278 		list_del_init(&seq_dmabuf->hbuf.list);
16279 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
16280 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
16281 		lpfc_update_rcv_time_stamp(vport);
16282 		return dmabuf;
16283 	}
16284 	/* move this sequence to the tail to indicate a young sequence */
16285 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
16286 	seq_dmabuf->time_stamp = jiffies;
16287 	lpfc_update_rcv_time_stamp(vport);
16288 	if (list_empty(&seq_dmabuf->dbuf.list)) {
16289 		temp_hdr = dmabuf->hbuf.virt;
16290 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
16291 		return seq_dmabuf;
16292 	}
16293 	/* find the correct place in the sequence to insert this frame */
16294 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
16295 	while (!found) {
16296 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
16297 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
16298 		/*
16299 		 * If the frame's sequence count is greater than the frame on
16300 		 * the list then insert the frame right after this frame
16301 		 */
16302 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
16303 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
16304 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
16305 			found = 1;
16306 			break;
16307 		}
16308 
16309 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
16310 			break;
16311 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
16312 	}
16313 
16314 	if (found)
16315 		return seq_dmabuf;
16316 	return NULL;
16317 }
16318 
16319 /**
16320  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
16321  * @vport: pointer to a vitural port
16322  * @dmabuf: pointer to a dmabuf that describes the FC sequence
16323  *
16324  * This function tries to abort from the partially assembed sequence, described
16325  * by the information from basic abbort @dmabuf. It checks to see whether such
16326  * partially assembled sequence held by the driver. If so, it shall free up all
16327  * the frames from the partially assembled sequence.
16328  *
16329  * Return
16330  * true  -- if there is matching partially assembled sequence present and all
16331  *          the frames freed with the sequence;
16332  * false -- if there is no matching partially assembled sequence present so
16333  *          nothing got aborted in the lower layer driver
16334  **/
16335 static bool
16336 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
16337 			    struct hbq_dmabuf *dmabuf)
16338 {
16339 	struct fc_frame_header *new_hdr;
16340 	struct fc_frame_header *temp_hdr;
16341 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
16342 	struct hbq_dmabuf *seq_dmabuf = NULL;
16343 
16344 	/* Use the hdr_buf to find the sequence that matches this frame */
16345 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
16346 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
16347 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
16348 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
16349 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
16350 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
16351 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
16352 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
16353 			continue;
16354 		/* found a pending sequence that matches this frame */
16355 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
16356 		break;
16357 	}
16358 
16359 	/* Free up all the frames from the partially assembled sequence */
16360 	if (seq_dmabuf) {
16361 		list_for_each_entry_safe(d_buf, n_buf,
16362 					 &seq_dmabuf->dbuf.list, list) {
16363 			list_del_init(&d_buf->list);
16364 			lpfc_in_buf_free(vport->phba, d_buf);
16365 		}
16366 		return true;
16367 	}
16368 	return false;
16369 }
16370 
16371 /**
16372  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
16373  * @vport: pointer to a vitural port
16374  * @dmabuf: pointer to a dmabuf that describes the FC sequence
16375  *
16376  * This function tries to abort from the assembed sequence from upper level
16377  * protocol, described by the information from basic abbort @dmabuf. It
16378  * checks to see whether such pending context exists at upper level protocol.
16379  * If so, it shall clean up the pending context.
16380  *
16381  * Return
16382  * true  -- if there is matching pending context of the sequence cleaned
16383  *          at ulp;
16384  * false -- if there is no matching pending context of the sequence present
16385  *          at ulp.
16386  **/
16387 static bool
16388 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
16389 {
16390 	struct lpfc_hba *phba = vport->phba;
16391 	int handled;
16392 
16393 	/* Accepting abort at ulp with SLI4 only */
16394 	if (phba->sli_rev < LPFC_SLI_REV4)
16395 		return false;
16396 
16397 	/* Register all caring upper level protocols to attend abort */
16398 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
16399 	if (handled)
16400 		return true;
16401 
16402 	return false;
16403 }
16404 
16405 /**
16406  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
16407  * @phba: Pointer to HBA context object.
16408  * @cmd_iocbq: pointer to the command iocbq structure.
16409  * @rsp_iocbq: pointer to the response iocbq structure.
16410  *
16411  * This function handles the sequence abort response iocb command complete
16412  * event. It properly releases the memory allocated to the sequence abort
16413  * accept iocb.
16414  **/
16415 static void
16416 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
16417 			     struct lpfc_iocbq *cmd_iocbq,
16418 			     struct lpfc_iocbq *rsp_iocbq)
16419 {
16420 	struct lpfc_nodelist *ndlp;
16421 
16422 	if (cmd_iocbq) {
16423 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
16424 		lpfc_nlp_put(ndlp);
16425 		lpfc_nlp_not_used(ndlp);
16426 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
16427 	}
16428 
16429 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
16430 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
16431 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16432 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
16433 			rsp_iocbq->iocb.ulpStatus,
16434 			rsp_iocbq->iocb.un.ulpWord[4]);
16435 }
16436 
16437 /**
16438  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
16439  * @phba: Pointer to HBA context object.
16440  * @xri: xri id in transaction.
16441  *
16442  * This function validates the xri maps to the known range of XRIs allocated an
16443  * used by the driver.
16444  **/
16445 uint16_t
16446 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
16447 		      uint16_t xri)
16448 {
16449 	uint16_t i;
16450 
16451 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
16452 		if (xri == phba->sli4_hba.xri_ids[i])
16453 			return i;
16454 	}
16455 	return NO_XRI;
16456 }
16457 
16458 /**
16459  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
16460  * @phba: Pointer to HBA context object.
16461  * @fc_hdr: pointer to a FC frame header.
16462  *
16463  * This function sends a basic response to a previous unsol sequence abort
16464  * event after aborting the sequence handling.
16465  **/
16466 static void
16467 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
16468 			struct fc_frame_header *fc_hdr, bool aborted)
16469 {
16470 	struct lpfc_hba *phba = vport->phba;
16471 	struct lpfc_iocbq *ctiocb = NULL;
16472 	struct lpfc_nodelist *ndlp;
16473 	uint16_t oxid, rxid, xri, lxri;
16474 	uint32_t sid, fctl;
16475 	IOCB_t *icmd;
16476 	int rc;
16477 
16478 	if (!lpfc_is_link_up(phba))
16479 		return;
16480 
16481 	sid = sli4_sid_from_fc_hdr(fc_hdr);
16482 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
16483 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
16484 
16485 	ndlp = lpfc_findnode_did(vport, sid);
16486 	if (!ndlp) {
16487 		ndlp = mempool_alloc(phba->nlp_mem_pool, GFP_KERNEL);
16488 		if (!ndlp) {
16489 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
16490 					 "1268 Failed to allocate ndlp for "
16491 					 "oxid:x%x SID:x%x\n", oxid, sid);
16492 			return;
16493 		}
16494 		lpfc_nlp_init(vport, ndlp, sid);
16495 		/* Put ndlp onto pport node list */
16496 		lpfc_enqueue_node(vport, ndlp);
16497 	} else if (!NLP_CHK_NODE_ACT(ndlp)) {
16498 		/* re-setup ndlp without removing from node list */
16499 		ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
16500 		if (!ndlp) {
16501 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
16502 					 "3275 Failed to active ndlp found "
16503 					 "for oxid:x%x SID:x%x\n", oxid, sid);
16504 			return;
16505 		}
16506 	}
16507 
16508 	/* Allocate buffer for rsp iocb */
16509 	ctiocb = lpfc_sli_get_iocbq(phba);
16510 	if (!ctiocb)
16511 		return;
16512 
16513 	/* Extract the F_CTL field from FC_HDR */
16514 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
16515 
16516 	icmd = &ctiocb->iocb;
16517 	icmd->un.xseq64.bdl.bdeSize = 0;
16518 	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
16519 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
16520 	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
16521 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
16522 
16523 	/* Fill in the rest of iocb fields */
16524 	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
16525 	icmd->ulpBdeCount = 0;
16526 	icmd->ulpLe = 1;
16527 	icmd->ulpClass = CLASS3;
16528 	icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
16529 	ctiocb->context1 = lpfc_nlp_get(ndlp);
16530 
16531 	ctiocb->iocb_cmpl = NULL;
16532 	ctiocb->vport = phba->pport;
16533 	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
16534 	ctiocb->sli4_lxritag = NO_XRI;
16535 	ctiocb->sli4_xritag = NO_XRI;
16536 
16537 	if (fctl & FC_FC_EX_CTX)
16538 		/* Exchange responder sent the abort so we
16539 		 * own the oxid.
16540 		 */
16541 		xri = oxid;
16542 	else
16543 		xri = rxid;
16544 	lxri = lpfc_sli4_xri_inrange(phba, xri);
16545 	if (lxri != NO_XRI)
16546 		lpfc_set_rrq_active(phba, ndlp, lxri,
16547 			(xri == oxid) ? rxid : oxid, 0);
16548 	/* For BA_ABTS from exchange responder, if the logical xri with
16549 	 * the oxid maps to the FCP XRI range, the port no longer has
16550 	 * that exchange context, send a BLS_RJT. Override the IOCB for
16551 	 * a BA_RJT.
16552 	 */
16553 	if ((fctl & FC_FC_EX_CTX) &&
16554 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
16555 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
16556 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
16557 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
16558 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
16559 	}
16560 
16561 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
16562 	 * the driver no longer has that exchange, send a BLS_RJT. Override
16563 	 * the IOCB for a BA_RJT.
16564 	 */
16565 	if (aborted == false) {
16566 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
16567 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
16568 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
16569 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
16570 	}
16571 
16572 	if (fctl & FC_FC_EX_CTX) {
16573 		/* ABTS sent by responder to CT exchange, construction
16574 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
16575 		 * field and RX_ID from ABTS for RX_ID field.
16576 		 */
16577 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
16578 	} else {
16579 		/* ABTS sent by initiator to CT exchange, construction
16580 		 * of BA_ACC will need to allocate a new XRI as for the
16581 		 * XRI_TAG field.
16582 		 */
16583 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
16584 	}
16585 	bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
16586 	bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
16587 
16588 	/* Xmit CT abts response on exchange <xid> */
16589 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
16590 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
16591 			 icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
16592 
16593 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
16594 	if (rc == IOCB_ERROR) {
16595 		lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
16596 				 "2925 Failed to issue CT ABTS RSP x%x on "
16597 				 "xri x%x, Data x%x\n",
16598 				 icmd->un.xseq64.w5.hcsw.Rctl, oxid,
16599 				 phba->link_state);
16600 		lpfc_nlp_put(ndlp);
16601 		ctiocb->context1 = NULL;
16602 		lpfc_sli_release_iocbq(phba, ctiocb);
16603 	}
16604 }
16605 
16606 /**
16607  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
16608  * @vport: Pointer to the vport on which this sequence was received
16609  * @dmabuf: pointer to a dmabuf that describes the FC sequence
16610  *
16611  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
16612  * receive sequence is only partially assembed by the driver, it shall abort
16613  * the partially assembled frames for the sequence. Otherwise, if the
16614  * unsolicited receive sequence has been completely assembled and passed to
16615  * the Upper Layer Protocol (UPL), it then mark the per oxid status for the
16616  * unsolicited sequence has been aborted. After that, it will issue a basic
16617  * accept to accept the abort.
16618  **/
16619 static void
16620 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
16621 			     struct hbq_dmabuf *dmabuf)
16622 {
16623 	struct lpfc_hba *phba = vport->phba;
16624 	struct fc_frame_header fc_hdr;
16625 	uint32_t fctl;
16626 	bool aborted;
16627 
16628 	/* Make a copy of fc_hdr before the dmabuf being released */
16629 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
16630 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
16631 
16632 	if (fctl & FC_FC_EX_CTX) {
16633 		/* ABTS by responder to exchange, no cleanup needed */
16634 		aborted = true;
16635 	} else {
16636 		/* ABTS by initiator to exchange, need to do cleanup */
16637 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
16638 		if (aborted == false)
16639 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
16640 	}
16641 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
16642 
16643 	/* Respond with BA_ACC or BA_RJT accordingly */
16644 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
16645 }
16646 
16647 /**
16648  * lpfc_seq_complete - Indicates if a sequence is complete
16649  * @dmabuf: pointer to a dmabuf that describes the FC sequence
16650  *
16651  * This function checks the sequence, starting with the frame described by
16652  * @dmabuf, to see if all the frames associated with this sequence are present.
16653  * the frames associated with this sequence are linked to the @dmabuf using the
16654  * dbuf list. This function looks for two major things. 1) That the first frame
16655  * has a sequence count of zero. 2) There is a frame with last frame of sequence
16656  * set. 3) That there are no holes in the sequence count. The function will
16657  * return 1 when the sequence is complete, otherwise it will return 0.
16658  **/
16659 static int
16660 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
16661 {
16662 	struct fc_frame_header *hdr;
16663 	struct lpfc_dmabuf *d_buf;
16664 	struct hbq_dmabuf *seq_dmabuf;
16665 	uint32_t fctl;
16666 	int seq_count = 0;
16667 
16668 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
16669 	/* make sure first fame of sequence has a sequence count of zero */
16670 	if (hdr->fh_seq_cnt != seq_count)
16671 		return 0;
16672 	fctl = (hdr->fh_f_ctl[0] << 16 |
16673 		hdr->fh_f_ctl[1] << 8 |
16674 		hdr->fh_f_ctl[2]);
16675 	/* If last frame of sequence we can return success. */
16676 	if (fctl & FC_FC_END_SEQ)
16677 		return 1;
16678 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
16679 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
16680 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
16681 		/* If there is a hole in the sequence count then fail. */
16682 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
16683 			return 0;
16684 		fctl = (hdr->fh_f_ctl[0] << 16 |
16685 			hdr->fh_f_ctl[1] << 8 |
16686 			hdr->fh_f_ctl[2]);
16687 		/* If last frame of sequence we can return success. */
16688 		if (fctl & FC_FC_END_SEQ)
16689 			return 1;
16690 	}
16691 	return 0;
16692 }
16693 
16694 /**
16695  * lpfc_prep_seq - Prep sequence for ULP processing
16696  * @vport: Pointer to the vport on which this sequence was received
16697  * @dmabuf: pointer to a dmabuf that describes the FC sequence
16698  *
16699  * This function takes a sequence, described by a list of frames, and creates
16700  * a list of iocbq structures to describe the sequence. This iocbq list will be
16701  * used to issue to the generic unsolicited sequence handler. This routine
16702  * returns a pointer to the first iocbq in the list. If the function is unable
16703  * to allocate an iocbq then it throw out the received frames that were not
16704  * able to be described and return a pointer to the first iocbq. If unable to
16705  * allocate any iocbqs (including the first) this function will return NULL.
16706  **/
16707 static struct lpfc_iocbq *
16708 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
16709 {
16710 	struct hbq_dmabuf *hbq_buf;
16711 	struct lpfc_dmabuf *d_buf, *n_buf;
16712 	struct lpfc_iocbq *first_iocbq, *iocbq;
16713 	struct fc_frame_header *fc_hdr;
16714 	uint32_t sid;
16715 	uint32_t len, tot_len;
16716 	struct ulp_bde64 *pbde;
16717 
16718 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
16719 	/* remove from receive buffer list */
16720 	list_del_init(&seq_dmabuf->hbuf.list);
16721 	lpfc_update_rcv_time_stamp(vport);
16722 	/* get the Remote Port's SID */
16723 	sid = sli4_sid_from_fc_hdr(fc_hdr);
16724 	tot_len = 0;
16725 	/* Get an iocbq struct to fill in. */
16726 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
16727 	if (first_iocbq) {
16728 		/* Initialize the first IOCB. */
16729 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
16730 		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
16731 		first_iocbq->vport = vport;
16732 
16733 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
16734 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
16735 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
16736 			first_iocbq->iocb.un.rcvels.parmRo =
16737 				sli4_did_from_fc_hdr(fc_hdr);
16738 			first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
16739 		} else
16740 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
16741 		first_iocbq->iocb.ulpContext = NO_XRI;
16742 		first_iocbq->iocb.unsli3.rcvsli3.ox_id =
16743 			be16_to_cpu(fc_hdr->fh_ox_id);
16744 		/* iocbq is prepped for internal consumption.  Physical vpi. */
16745 		first_iocbq->iocb.unsli3.rcvsli3.vpi =
16746 			vport->phba->vpi_ids[vport->vpi];
16747 		/* put the first buffer into the first IOCBq */
16748 		tot_len = bf_get(lpfc_rcqe_length,
16749 				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
16750 
16751 		first_iocbq->context2 = &seq_dmabuf->dbuf;
16752 		first_iocbq->context3 = NULL;
16753 		first_iocbq->iocb.ulpBdeCount = 1;
16754 		if (tot_len > LPFC_DATA_BUF_SIZE)
16755 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
16756 							LPFC_DATA_BUF_SIZE;
16757 		else
16758 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
16759 
16760 		first_iocbq->iocb.un.rcvels.remoteID = sid;
16761 
16762 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
16763 	}
16764 	iocbq = first_iocbq;
16765 	/*
16766 	 * Each IOCBq can have two Buffers assigned, so go through the list
16767 	 * of buffers for this sequence and save two buffers in each IOCBq
16768 	 */
16769 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
16770 		if (!iocbq) {
16771 			lpfc_in_buf_free(vport->phba, d_buf);
16772 			continue;
16773 		}
16774 		if (!iocbq->context3) {
16775 			iocbq->context3 = d_buf;
16776 			iocbq->iocb.ulpBdeCount++;
16777 			/* We need to get the size out of the right CQE */
16778 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
16779 			len = bf_get(lpfc_rcqe_length,
16780 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
16781 			pbde = (struct ulp_bde64 *)
16782 					&iocbq->iocb.unsli3.sli3Words[4];
16783 			if (len > LPFC_DATA_BUF_SIZE)
16784 				pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
16785 			else
16786 				pbde->tus.f.bdeSize = len;
16787 
16788 			iocbq->iocb.unsli3.rcvsli3.acc_len += len;
16789 			tot_len += len;
16790 		} else {
16791 			iocbq = lpfc_sli_get_iocbq(vport->phba);
16792 			if (!iocbq) {
16793 				if (first_iocbq) {
16794 					first_iocbq->iocb.ulpStatus =
16795 							IOSTAT_FCP_RSP_ERROR;
16796 					first_iocbq->iocb.un.ulpWord[4] =
16797 							IOERR_NO_RESOURCES;
16798 				}
16799 				lpfc_in_buf_free(vport->phba, d_buf);
16800 				continue;
16801 			}
16802 			/* We need to get the size out of the right CQE */
16803 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
16804 			len = bf_get(lpfc_rcqe_length,
16805 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
16806 			iocbq->context2 = d_buf;
16807 			iocbq->context3 = NULL;
16808 			iocbq->iocb.ulpBdeCount = 1;
16809 			if (len > LPFC_DATA_BUF_SIZE)
16810 				iocbq->iocb.un.cont64[0].tus.f.bdeSize =
16811 							LPFC_DATA_BUF_SIZE;
16812 			else
16813 				iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
16814 
16815 			tot_len += len;
16816 			iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
16817 
16818 			iocbq->iocb.un.rcvels.remoteID = sid;
16819 			list_add_tail(&iocbq->list, &first_iocbq->list);
16820 		}
16821 	}
16822 	return first_iocbq;
16823 }
16824 
16825 static void
16826 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
16827 			  struct hbq_dmabuf *seq_dmabuf)
16828 {
16829 	struct fc_frame_header *fc_hdr;
16830 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
16831 	struct lpfc_hba *phba = vport->phba;
16832 
16833 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
16834 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
16835 	if (!iocbq) {
16836 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16837 				"2707 Ring %d handler: Failed to allocate "
16838 				"iocb Rctl x%x Type x%x received\n",
16839 				LPFC_ELS_RING,
16840 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
16841 		return;
16842 	}
16843 	if (!lpfc_complete_unsol_iocb(phba,
16844 				      phba->sli4_hba.els_wq->pring,
16845 				      iocbq, fc_hdr->fh_r_ctl,
16846 				      fc_hdr->fh_type))
16847 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16848 				"2540 Ring %d handler: unexpected Rctl "
16849 				"x%x Type x%x received\n",
16850 				LPFC_ELS_RING,
16851 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
16852 
16853 	/* Free iocb created in lpfc_prep_seq */
16854 	list_for_each_entry_safe(curr_iocb, next_iocb,
16855 		&iocbq->list, list) {
16856 		list_del_init(&curr_iocb->list);
16857 		lpfc_sli_release_iocbq(phba, curr_iocb);
16858 	}
16859 	lpfc_sli_release_iocbq(phba, iocbq);
16860 }
16861 
16862 /**
16863  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
16864  * @phba: Pointer to HBA context object.
16865  *
16866  * This function is called with no lock held. This function processes all
16867  * the received buffers and gives it to upper layers when a received buffer
16868  * indicates that it is the final frame in the sequence. The interrupt
16869  * service routine processes received buffers at interrupt contexts.
16870  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
16871  * appropriate receive function when the final frame in a sequence is received.
16872  **/
16873 void
16874 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
16875 				 struct hbq_dmabuf *dmabuf)
16876 {
16877 	struct hbq_dmabuf *seq_dmabuf;
16878 	struct fc_frame_header *fc_hdr;
16879 	struct lpfc_vport *vport;
16880 	uint32_t fcfi;
16881 	uint32_t did;
16882 
16883 	/* Process each received buffer */
16884 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
16885 
16886 	/* check to see if this a valid type of frame */
16887 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
16888 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
16889 		return;
16890 	}
16891 
16892 	if ((bf_get(lpfc_cqe_code,
16893 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
16894 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
16895 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
16896 	else
16897 		fcfi = bf_get(lpfc_rcqe_fcf_id,
16898 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
16899 
16900 	/* d_id this frame is directed to */
16901 	did = sli4_did_from_fc_hdr(fc_hdr);
16902 
16903 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
16904 	if (!vport) {
16905 		/* throw out the frame */
16906 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
16907 		return;
16908 	}
16909 
16910 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
16911 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
16912 		(did != Fabric_DID)) {
16913 		/*
16914 		 * Throw out the frame if we are not pt2pt.
16915 		 * The pt2pt protocol allows for discovery frames
16916 		 * to be received without a registered VPI.
16917 		 */
16918 		if (!(vport->fc_flag & FC_PT2PT) ||
16919 			(phba->link_state == LPFC_HBA_READY)) {
16920 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
16921 			return;
16922 		}
16923 	}
16924 
16925 	/* Handle the basic abort sequence (BA_ABTS) event */
16926 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
16927 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
16928 		return;
16929 	}
16930 
16931 	/* Link this frame */
16932 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
16933 	if (!seq_dmabuf) {
16934 		/* unable to add frame to vport - throw it out */
16935 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
16936 		return;
16937 	}
16938 	/* If not last frame in sequence continue processing frames. */
16939 	if (!lpfc_seq_complete(seq_dmabuf))
16940 		return;
16941 
16942 	/* Send the complete sequence to the upper layer protocol */
16943 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
16944 }
16945 
16946 /**
16947  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
16948  * @phba: pointer to lpfc hba data structure.
16949  *
16950  * This routine is invoked to post rpi header templates to the
16951  * HBA consistent with the SLI-4 interface spec.  This routine
16952  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
16953  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
16954  *
16955  * This routine does not require any locks.  It's usage is expected
16956  * to be driver load or reset recovery when the driver is
16957  * sequential.
16958  *
16959  * Return codes
16960  * 	0 - successful
16961  *      -EIO - The mailbox failed to complete successfully.
16962  * 	When this error occurs, the driver is not guaranteed
16963  *	to have any rpi regions posted to the device and
16964  *	must either attempt to repost the regions or take a
16965  *	fatal error.
16966  **/
16967 int
16968 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
16969 {
16970 	struct lpfc_rpi_hdr *rpi_page;
16971 	uint32_t rc = 0;
16972 	uint16_t lrpi = 0;
16973 
16974 	/* SLI4 ports that support extents do not require RPI headers. */
16975 	if (!phba->sli4_hba.rpi_hdrs_in_use)
16976 		goto exit;
16977 	if (phba->sli4_hba.extents_in_use)
16978 		return -EIO;
16979 
16980 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
16981 		/*
16982 		 * Assign the rpi headers a physical rpi only if the driver
16983 		 * has not initialized those resources.  A port reset only
16984 		 * needs the headers posted.
16985 		 */
16986 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
16987 		    LPFC_RPI_RSRC_RDY)
16988 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
16989 
16990 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
16991 		if (rc != MBX_SUCCESS) {
16992 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16993 					"2008 Error %d posting all rpi "
16994 					"headers\n", rc);
16995 			rc = -EIO;
16996 			break;
16997 		}
16998 	}
16999 
17000  exit:
17001 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
17002 	       LPFC_RPI_RSRC_RDY);
17003 	return rc;
17004 }
17005 
17006 /**
17007  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
17008  * @phba: pointer to lpfc hba data structure.
17009  * @rpi_page:  pointer to the rpi memory region.
17010  *
17011  * This routine is invoked to post a single rpi header to the
17012  * HBA consistent with the SLI-4 interface spec.  This memory region
17013  * maps up to 64 rpi context regions.
17014  *
17015  * Return codes
17016  * 	0 - successful
17017  * 	-ENOMEM - No available memory
17018  *      -EIO - The mailbox failed to complete successfully.
17019  **/
17020 int
17021 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
17022 {
17023 	LPFC_MBOXQ_t *mboxq;
17024 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
17025 	uint32_t rc = 0;
17026 	uint32_t shdr_status, shdr_add_status;
17027 	union lpfc_sli4_cfg_shdr *shdr;
17028 
17029 	/* SLI4 ports that support extents do not require RPI headers. */
17030 	if (!phba->sli4_hba.rpi_hdrs_in_use)
17031 		return rc;
17032 	if (phba->sli4_hba.extents_in_use)
17033 		return -EIO;
17034 
17035 	/* The port is notified of the header region via a mailbox command. */
17036 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17037 	if (!mboxq) {
17038 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17039 				"2001 Unable to allocate memory for issuing "
17040 				"SLI_CONFIG_SPECIAL mailbox command\n");
17041 		return -ENOMEM;
17042 	}
17043 
17044 	/* Post all rpi memory regions to the port. */
17045 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
17046 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
17047 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
17048 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
17049 			 sizeof(struct lpfc_sli4_cfg_mhdr),
17050 			 LPFC_SLI4_MBX_EMBED);
17051 
17052 
17053 	/* Post the physical rpi to the port for this rpi header. */
17054 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
17055 	       rpi_page->start_rpi);
17056 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
17057 	       hdr_tmpl, rpi_page->page_count);
17058 
17059 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
17060 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
17061 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
17062 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
17063 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17064 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17065 	if (rc != MBX_TIMEOUT)
17066 		mempool_free(mboxq, phba->mbox_mem_pool);
17067 	if (shdr_status || shdr_add_status || rc) {
17068 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17069 				"2514 POST_RPI_HDR mailbox failed with "
17070 				"status x%x add_status x%x, mbx status x%x\n",
17071 				shdr_status, shdr_add_status, rc);
17072 		rc = -ENXIO;
17073 	}
17074 	return rc;
17075 }
17076 
17077 /**
17078  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
17079  * @phba: pointer to lpfc hba data structure.
17080  *
17081  * This routine is invoked to post rpi header templates to the
17082  * HBA consistent with the SLI-4 interface spec.  This routine
17083  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
17084  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
17085  *
17086  * Returns
17087  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
17088  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
17089  **/
17090 int
17091 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
17092 {
17093 	unsigned long rpi;
17094 	uint16_t max_rpi, rpi_limit;
17095 	uint16_t rpi_remaining, lrpi = 0;
17096 	struct lpfc_rpi_hdr *rpi_hdr;
17097 	unsigned long iflag;
17098 
17099 	/*
17100 	 * Fetch the next logical rpi.  Because this index is logical,
17101 	 * the  driver starts at 0 each time.
17102 	 */
17103 	spin_lock_irqsave(&phba->hbalock, iflag);
17104 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
17105 	rpi_limit = phba->sli4_hba.next_rpi;
17106 
17107 	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
17108 	if (rpi >= rpi_limit)
17109 		rpi = LPFC_RPI_ALLOC_ERROR;
17110 	else {
17111 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
17112 		phba->sli4_hba.max_cfg_param.rpi_used++;
17113 		phba->sli4_hba.rpi_count++;
17114 	}
17115 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
17116 			"0001 rpi:%x max:%x lim:%x\n",
17117 			(int) rpi, max_rpi, rpi_limit);
17118 
17119 	/*
17120 	 * Don't try to allocate more rpi header regions if the device limit
17121 	 * has been exhausted.
17122 	 */
17123 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
17124 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
17125 		spin_unlock_irqrestore(&phba->hbalock, iflag);
17126 		return rpi;
17127 	}
17128 
17129 	/*
17130 	 * RPI header postings are not required for SLI4 ports capable of
17131 	 * extents.
17132 	 */
17133 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
17134 		spin_unlock_irqrestore(&phba->hbalock, iflag);
17135 		return rpi;
17136 	}
17137 
17138 	/*
17139 	 * If the driver is running low on rpi resources, allocate another
17140 	 * page now.  Note that the next_rpi value is used because
17141 	 * it represents how many are actually in use whereas max_rpi notes
17142 	 * how many are supported max by the device.
17143 	 */
17144 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
17145 	spin_unlock_irqrestore(&phba->hbalock, iflag);
17146 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
17147 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
17148 		if (!rpi_hdr) {
17149 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17150 					"2002 Error Could not grow rpi "
17151 					"count\n");
17152 		} else {
17153 			lrpi = rpi_hdr->start_rpi;
17154 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
17155 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
17156 		}
17157 	}
17158 
17159 	return rpi;
17160 }
17161 
17162 /**
17163  * lpfc_sli4_free_rpi - Release an rpi for reuse.
17164  * @phba: pointer to lpfc hba data structure.
17165  *
17166  * This routine is invoked to release an rpi to the pool of
17167  * available rpis maintained by the driver.
17168  **/
17169 static void
17170 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
17171 {
17172 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
17173 		phba->sli4_hba.rpi_count--;
17174 		phba->sli4_hba.max_cfg_param.rpi_used--;
17175 	}
17176 }
17177 
17178 /**
17179  * lpfc_sli4_free_rpi - Release an rpi for reuse.
17180  * @phba: pointer to lpfc hba data structure.
17181  *
17182  * This routine is invoked to release an rpi to the pool of
17183  * available rpis maintained by the driver.
17184  **/
17185 void
17186 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
17187 {
17188 	spin_lock_irq(&phba->hbalock);
17189 	__lpfc_sli4_free_rpi(phba, rpi);
17190 	spin_unlock_irq(&phba->hbalock);
17191 }
17192 
17193 /**
17194  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
17195  * @phba: pointer to lpfc hba data structure.
17196  *
17197  * This routine is invoked to remove the memory region that
17198  * provided rpi via a bitmask.
17199  **/
17200 void
17201 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
17202 {
17203 	kfree(phba->sli4_hba.rpi_bmask);
17204 	kfree(phba->sli4_hba.rpi_ids);
17205 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
17206 }
17207 
17208 /**
17209  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
17210  * @phba: pointer to lpfc hba data structure.
17211  *
17212  * This routine is invoked to remove the memory region that
17213  * provided rpi via a bitmask.
17214  **/
17215 int
17216 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
17217 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
17218 {
17219 	LPFC_MBOXQ_t *mboxq;
17220 	struct lpfc_hba *phba = ndlp->phba;
17221 	int rc;
17222 
17223 	/* The port is notified of the header region via a mailbox command. */
17224 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17225 	if (!mboxq)
17226 		return -ENOMEM;
17227 
17228 	/* Post all rpi memory regions to the port. */
17229 	lpfc_resume_rpi(mboxq, ndlp);
17230 	if (cmpl) {
17231 		mboxq->mbox_cmpl = cmpl;
17232 		mboxq->context1 = arg;
17233 		mboxq->context2 = ndlp;
17234 	} else
17235 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17236 	mboxq->vport = ndlp->vport;
17237 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
17238 	if (rc == MBX_NOT_FINISHED) {
17239 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17240 				"2010 Resume RPI Mailbox failed "
17241 				"status %d, mbxStatus x%x\n", rc,
17242 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
17243 		mempool_free(mboxq, phba->mbox_mem_pool);
17244 		return -EIO;
17245 	}
17246 	return 0;
17247 }
17248 
17249 /**
17250  * lpfc_sli4_init_vpi - Initialize a vpi with the port
17251  * @vport: Pointer to the vport for which the vpi is being initialized
17252  *
17253  * This routine is invoked to activate a vpi with the port.
17254  *
17255  * Returns:
17256  *    0 success
17257  *    -Evalue otherwise
17258  **/
17259 int
17260 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
17261 {
17262 	LPFC_MBOXQ_t *mboxq;
17263 	int rc = 0;
17264 	int retval = MBX_SUCCESS;
17265 	uint32_t mbox_tmo;
17266 	struct lpfc_hba *phba = vport->phba;
17267 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17268 	if (!mboxq)
17269 		return -ENOMEM;
17270 	lpfc_init_vpi(phba, mboxq, vport->vpi);
17271 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
17272 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
17273 	if (rc != MBX_SUCCESS) {
17274 		lpfc_printf_vlog(vport, KERN_ERR, LOG_SLI,
17275 				"2022 INIT VPI Mailbox failed "
17276 				"status %d, mbxStatus x%x\n", rc,
17277 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
17278 		retval = -EIO;
17279 	}
17280 	if (rc != MBX_TIMEOUT)
17281 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
17282 
17283 	return retval;
17284 }
17285 
17286 /**
17287  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
17288  * @phba: pointer to lpfc hba data structure.
17289  * @mboxq: Pointer to mailbox object.
17290  *
17291  * This routine is invoked to manually add a single FCF record. The caller
17292  * must pass a completely initialized FCF_Record.  This routine takes
17293  * care of the nonembedded mailbox operations.
17294  **/
17295 static void
17296 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
17297 {
17298 	void *virt_addr;
17299 	union lpfc_sli4_cfg_shdr *shdr;
17300 	uint32_t shdr_status, shdr_add_status;
17301 
17302 	virt_addr = mboxq->sge_array->addr[0];
17303 	/* The IOCTL status is embedded in the mailbox subheader. */
17304 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
17305 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17306 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17307 
17308 	if ((shdr_status || shdr_add_status) &&
17309 		(shdr_status != STATUS_FCF_IN_USE))
17310 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17311 			"2558 ADD_FCF_RECORD mailbox failed with "
17312 			"status x%x add_status x%x\n",
17313 			shdr_status, shdr_add_status);
17314 
17315 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
17316 }
17317 
17318 /**
17319  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
17320  * @phba: pointer to lpfc hba data structure.
17321  * @fcf_record:  pointer to the initialized fcf record to add.
17322  *
17323  * This routine is invoked to manually add a single FCF record. The caller
17324  * must pass a completely initialized FCF_Record.  This routine takes
17325  * care of the nonembedded mailbox operations.
17326  **/
17327 int
17328 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
17329 {
17330 	int rc = 0;
17331 	LPFC_MBOXQ_t *mboxq;
17332 	uint8_t *bytep;
17333 	void *virt_addr;
17334 	struct lpfc_mbx_sge sge;
17335 	uint32_t alloc_len, req_len;
17336 	uint32_t fcfindex;
17337 
17338 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17339 	if (!mboxq) {
17340 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17341 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
17342 		return -ENOMEM;
17343 	}
17344 
17345 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
17346 		  sizeof(uint32_t);
17347 
17348 	/* Allocate DMA memory and set up the non-embedded mailbox command */
17349 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
17350 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
17351 				     req_len, LPFC_SLI4_MBX_NEMBED);
17352 	if (alloc_len < req_len) {
17353 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17354 			"2523 Allocated DMA memory size (x%x) is "
17355 			"less than the requested DMA memory "
17356 			"size (x%x)\n", alloc_len, req_len);
17357 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
17358 		return -ENOMEM;
17359 	}
17360 
17361 	/*
17362 	 * Get the first SGE entry from the non-embedded DMA memory.  This
17363 	 * routine only uses a single SGE.
17364 	 */
17365 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
17366 	virt_addr = mboxq->sge_array->addr[0];
17367 	/*
17368 	 * Configure the FCF record for FCFI 0.  This is the driver's
17369 	 * hardcoded default and gets used in nonFIP mode.
17370 	 */
17371 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
17372 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
17373 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
17374 
17375 	/*
17376 	 * Copy the fcf_index and the FCF Record Data. The data starts after
17377 	 * the FCoE header plus word10. The data copy needs to be endian
17378 	 * correct.
17379 	 */
17380 	bytep += sizeof(uint32_t);
17381 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
17382 	mboxq->vport = phba->pport;
17383 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
17384 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
17385 	if (rc == MBX_NOT_FINISHED) {
17386 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17387 			"2515 ADD_FCF_RECORD mailbox failed with "
17388 			"status 0x%x\n", rc);
17389 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
17390 		rc = -EIO;
17391 	} else
17392 		rc = 0;
17393 
17394 	return rc;
17395 }
17396 
17397 /**
17398  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
17399  * @phba: pointer to lpfc hba data structure.
17400  * @fcf_record:  pointer to the fcf record to write the default data.
17401  * @fcf_index: FCF table entry index.
17402  *
17403  * This routine is invoked to build the driver's default FCF record.  The
17404  * values used are hardcoded.  This routine handles memory initialization.
17405  *
17406  **/
17407 void
17408 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
17409 				struct fcf_record *fcf_record,
17410 				uint16_t fcf_index)
17411 {
17412 	memset(fcf_record, 0, sizeof(struct fcf_record));
17413 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
17414 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
17415 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
17416 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
17417 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
17418 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
17419 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
17420 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
17421 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
17422 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
17423 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
17424 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
17425 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
17426 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
17427 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
17428 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
17429 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
17430 	/* Set the VLAN bit map */
17431 	if (phba->valid_vlan) {
17432 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
17433 			= 1 << (phba->vlan_id % 8);
17434 	}
17435 }
17436 
17437 /**
17438  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
17439  * @phba: pointer to lpfc hba data structure.
17440  * @fcf_index: FCF table entry offset.
17441  *
17442  * This routine is invoked to scan the entire FCF table by reading FCF
17443  * record and processing it one at a time starting from the @fcf_index
17444  * for initial FCF discovery or fast FCF failover rediscovery.
17445  *
17446  * Return 0 if the mailbox command is submitted successfully, none 0
17447  * otherwise.
17448  **/
17449 int
17450 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
17451 {
17452 	int rc = 0, error;
17453 	LPFC_MBOXQ_t *mboxq;
17454 
17455 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
17456 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
17457 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17458 	if (!mboxq) {
17459 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17460 				"2000 Failed to allocate mbox for "
17461 				"READ_FCF cmd\n");
17462 		error = -ENOMEM;
17463 		goto fail_fcf_scan;
17464 	}
17465 	/* Construct the read FCF record mailbox command */
17466 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
17467 	if (rc) {
17468 		error = -EINVAL;
17469 		goto fail_fcf_scan;
17470 	}
17471 	/* Issue the mailbox command asynchronously */
17472 	mboxq->vport = phba->pport;
17473 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
17474 
17475 	spin_lock_irq(&phba->hbalock);
17476 	phba->hba_flag |= FCF_TS_INPROG;
17477 	spin_unlock_irq(&phba->hbalock);
17478 
17479 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
17480 	if (rc == MBX_NOT_FINISHED)
17481 		error = -EIO;
17482 	else {
17483 		/* Reset eligible FCF count for new scan */
17484 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
17485 			phba->fcf.eligible_fcf_cnt = 0;
17486 		error = 0;
17487 	}
17488 fail_fcf_scan:
17489 	if (error) {
17490 		if (mboxq)
17491 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
17492 		/* FCF scan failed, clear FCF_TS_INPROG flag */
17493 		spin_lock_irq(&phba->hbalock);
17494 		phba->hba_flag &= ~FCF_TS_INPROG;
17495 		spin_unlock_irq(&phba->hbalock);
17496 	}
17497 	return error;
17498 }
17499 
17500 /**
17501  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
17502  * @phba: pointer to lpfc hba data structure.
17503  * @fcf_index: FCF table entry offset.
17504  *
17505  * This routine is invoked to read an FCF record indicated by @fcf_index
17506  * and to use it for FLOGI roundrobin FCF failover.
17507  *
17508  * Return 0 if the mailbox command is submitted successfully, none 0
17509  * otherwise.
17510  **/
17511 int
17512 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
17513 {
17514 	int rc = 0, error;
17515 	LPFC_MBOXQ_t *mboxq;
17516 
17517 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17518 	if (!mboxq) {
17519 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
17520 				"2763 Failed to allocate mbox for "
17521 				"READ_FCF cmd\n");
17522 		error = -ENOMEM;
17523 		goto fail_fcf_read;
17524 	}
17525 	/* Construct the read FCF record mailbox command */
17526 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
17527 	if (rc) {
17528 		error = -EINVAL;
17529 		goto fail_fcf_read;
17530 	}
17531 	/* Issue the mailbox command asynchronously */
17532 	mboxq->vport = phba->pport;
17533 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
17534 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
17535 	if (rc == MBX_NOT_FINISHED)
17536 		error = -EIO;
17537 	else
17538 		error = 0;
17539 
17540 fail_fcf_read:
17541 	if (error && mboxq)
17542 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
17543 	return error;
17544 }
17545 
17546 /**
17547  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
17548  * @phba: pointer to lpfc hba data structure.
17549  * @fcf_index: FCF table entry offset.
17550  *
17551  * This routine is invoked to read an FCF record indicated by @fcf_index to
17552  * determine whether it's eligible for FLOGI roundrobin failover list.
17553  *
17554  * Return 0 if the mailbox command is submitted successfully, none 0
17555  * otherwise.
17556  **/
17557 int
17558 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
17559 {
17560 	int rc = 0, error;
17561 	LPFC_MBOXQ_t *mboxq;
17562 
17563 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17564 	if (!mboxq) {
17565 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
17566 				"2758 Failed to allocate mbox for "
17567 				"READ_FCF cmd\n");
17568 				error = -ENOMEM;
17569 				goto fail_fcf_read;
17570 	}
17571 	/* Construct the read FCF record mailbox command */
17572 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
17573 	if (rc) {
17574 		error = -EINVAL;
17575 		goto fail_fcf_read;
17576 	}
17577 	/* Issue the mailbox command asynchronously */
17578 	mboxq->vport = phba->pport;
17579 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
17580 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
17581 	if (rc == MBX_NOT_FINISHED)
17582 		error = -EIO;
17583 	else
17584 		error = 0;
17585 
17586 fail_fcf_read:
17587 	if (error && mboxq)
17588 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
17589 	return error;
17590 }
17591 
17592 /**
17593  * lpfc_check_next_fcf_pri_level
17594  * phba pointer to the lpfc_hba struct for this port.
17595  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
17596  * routine when the rr_bmask is empty. The FCF indecies are put into the
17597  * rr_bmask based on their priority level. Starting from the highest priority
17598  * to the lowest. The most likely FCF candidate will be in the highest
17599  * priority group. When this routine is called it searches the fcf_pri list for
17600  * next lowest priority group and repopulates the rr_bmask with only those
17601  * fcf_indexes.
17602  * returns:
17603  * 1=success 0=failure
17604  **/
17605 static int
17606 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
17607 {
17608 	uint16_t next_fcf_pri;
17609 	uint16_t last_index;
17610 	struct lpfc_fcf_pri *fcf_pri;
17611 	int rc;
17612 	int ret = 0;
17613 
17614 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
17615 			LPFC_SLI4_FCF_TBL_INDX_MAX);
17616 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
17617 			"3060 Last IDX %d\n", last_index);
17618 
17619 	/* Verify the priority list has 2 or more entries */
17620 	spin_lock_irq(&phba->hbalock);
17621 	if (list_empty(&phba->fcf.fcf_pri_list) ||
17622 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
17623 		spin_unlock_irq(&phba->hbalock);
17624 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
17625 			"3061 Last IDX %d\n", last_index);
17626 		return 0; /* Empty rr list */
17627 	}
17628 	spin_unlock_irq(&phba->hbalock);
17629 
17630 	next_fcf_pri = 0;
17631 	/*
17632 	 * Clear the rr_bmask and set all of the bits that are at this
17633 	 * priority.
17634 	 */
17635 	memset(phba->fcf.fcf_rr_bmask, 0,
17636 			sizeof(*phba->fcf.fcf_rr_bmask));
17637 	spin_lock_irq(&phba->hbalock);
17638 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
17639 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
17640 			continue;
17641 		/*
17642 		 * the 1st priority that has not FLOGI failed
17643 		 * will be the highest.
17644 		 */
17645 		if (!next_fcf_pri)
17646 			next_fcf_pri = fcf_pri->fcf_rec.priority;
17647 		spin_unlock_irq(&phba->hbalock);
17648 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
17649 			rc = lpfc_sli4_fcf_rr_index_set(phba,
17650 						fcf_pri->fcf_rec.fcf_index);
17651 			if (rc)
17652 				return 0;
17653 		}
17654 		spin_lock_irq(&phba->hbalock);
17655 	}
17656 	/*
17657 	 * if next_fcf_pri was not set above and the list is not empty then
17658 	 * we have failed flogis on all of them. So reset flogi failed
17659 	 * and start at the beginning.
17660 	 */
17661 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
17662 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
17663 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
17664 			/*
17665 			 * the 1st priority that has not FLOGI failed
17666 			 * will be the highest.
17667 			 */
17668 			if (!next_fcf_pri)
17669 				next_fcf_pri = fcf_pri->fcf_rec.priority;
17670 			spin_unlock_irq(&phba->hbalock);
17671 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
17672 				rc = lpfc_sli4_fcf_rr_index_set(phba,
17673 						fcf_pri->fcf_rec.fcf_index);
17674 				if (rc)
17675 					return 0;
17676 			}
17677 			spin_lock_irq(&phba->hbalock);
17678 		}
17679 	} else
17680 		ret = 1;
17681 	spin_unlock_irq(&phba->hbalock);
17682 
17683 	return ret;
17684 }
17685 /**
17686  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
17687  * @phba: pointer to lpfc hba data structure.
17688  *
17689  * This routine is to get the next eligible FCF record index in a round
17690  * robin fashion. If the next eligible FCF record index equals to the
17691  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
17692  * shall be returned, otherwise, the next eligible FCF record's index
17693  * shall be returned.
17694  **/
17695 uint16_t
17696 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
17697 {
17698 	uint16_t next_fcf_index;
17699 
17700 initial_priority:
17701 	/* Search start from next bit of currently registered FCF index */
17702 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
17703 
17704 next_priority:
17705 	/* Determine the next fcf index to check */
17706 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
17707 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
17708 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
17709 				       next_fcf_index);
17710 
17711 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
17712 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
17713 		/*
17714 		 * If we have wrapped then we need to clear the bits that
17715 		 * have been tested so that we can detect when we should
17716 		 * change the priority level.
17717 		 */
17718 		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
17719 					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
17720 	}
17721 
17722 
17723 	/* Check roundrobin failover list empty condition */
17724 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
17725 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
17726 		/*
17727 		 * If next fcf index is not found check if there are lower
17728 		 * Priority level fcf's in the fcf_priority list.
17729 		 * Set up the rr_bmask with all of the avaiable fcf bits
17730 		 * at that level and continue the selection process.
17731 		 */
17732 		if (lpfc_check_next_fcf_pri_level(phba))
17733 			goto initial_priority;
17734 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
17735 				"2844 No roundrobin failover FCF available\n");
17736 		if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX)
17737 			return LPFC_FCOE_FCF_NEXT_NONE;
17738 		else {
17739 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
17740 				"3063 Only FCF available idx %d, flag %x\n",
17741 				next_fcf_index,
17742 			phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag);
17743 			return next_fcf_index;
17744 		}
17745 	}
17746 
17747 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
17748 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
17749 		LPFC_FCF_FLOGI_FAILED) {
17750 		if (list_is_singular(&phba->fcf.fcf_pri_list))
17751 			return LPFC_FCOE_FCF_NEXT_NONE;
17752 
17753 		goto next_priority;
17754 	}
17755 
17756 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
17757 			"2845 Get next roundrobin failover FCF (x%x)\n",
17758 			next_fcf_index);
17759 
17760 	return next_fcf_index;
17761 }
17762 
17763 /**
17764  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
17765  * @phba: pointer to lpfc hba data structure.
17766  *
17767  * This routine sets the FCF record index in to the eligible bmask for
17768  * roundrobin failover search. It checks to make sure that the index
17769  * does not go beyond the range of the driver allocated bmask dimension
17770  * before setting the bit.
17771  *
17772  * Returns 0 if the index bit successfully set, otherwise, it returns
17773  * -EINVAL.
17774  **/
17775 int
17776 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
17777 {
17778 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
17779 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
17780 				"2610 FCF (x%x) reached driver's book "
17781 				"keeping dimension:x%x\n",
17782 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
17783 		return -EINVAL;
17784 	}
17785 	/* Set the eligible FCF record index bmask */
17786 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
17787 
17788 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
17789 			"2790 Set FCF (x%x) to roundrobin FCF failover "
17790 			"bmask\n", fcf_index);
17791 
17792 	return 0;
17793 }
17794 
17795 /**
17796  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
17797  * @phba: pointer to lpfc hba data structure.
17798  *
17799  * This routine clears the FCF record index from the eligible bmask for
17800  * roundrobin failover search. It checks to make sure that the index
17801  * does not go beyond the range of the driver allocated bmask dimension
17802  * before clearing the bit.
17803  **/
17804 void
17805 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
17806 {
17807 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
17808 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
17809 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
17810 				"2762 FCF (x%x) reached driver's book "
17811 				"keeping dimension:x%x\n",
17812 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
17813 		return;
17814 	}
17815 	/* Clear the eligible FCF record index bmask */
17816 	spin_lock_irq(&phba->hbalock);
17817 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
17818 				 list) {
17819 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
17820 			list_del_init(&fcf_pri->list);
17821 			break;
17822 		}
17823 	}
17824 	spin_unlock_irq(&phba->hbalock);
17825 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
17826 
17827 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
17828 			"2791 Clear FCF (x%x) from roundrobin failover "
17829 			"bmask\n", fcf_index);
17830 }
17831 
17832 /**
17833  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
17834  * @phba: pointer to lpfc hba data structure.
17835  *
17836  * This routine is the completion routine for the rediscover FCF table mailbox
17837  * command. If the mailbox command returned failure, it will try to stop the
17838  * FCF rediscover wait timer.
17839  **/
17840 static void
17841 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
17842 {
17843 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
17844 	uint32_t shdr_status, shdr_add_status;
17845 
17846 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
17847 
17848 	shdr_status = bf_get(lpfc_mbox_hdr_status,
17849 			     &redisc_fcf->header.cfg_shdr.response);
17850 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
17851 			     &redisc_fcf->header.cfg_shdr.response);
17852 	if (shdr_status || shdr_add_status) {
17853 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
17854 				"2746 Requesting for FCF rediscovery failed "
17855 				"status x%x add_status x%x\n",
17856 				shdr_status, shdr_add_status);
17857 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
17858 			spin_lock_irq(&phba->hbalock);
17859 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
17860 			spin_unlock_irq(&phba->hbalock);
17861 			/*
17862 			 * CVL event triggered FCF rediscover request failed,
17863 			 * last resort to re-try current registered FCF entry.
17864 			 */
17865 			lpfc_retry_pport_discovery(phba);
17866 		} else {
17867 			spin_lock_irq(&phba->hbalock);
17868 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
17869 			spin_unlock_irq(&phba->hbalock);
17870 			/*
17871 			 * DEAD FCF event triggered FCF rediscover request
17872 			 * failed, last resort to fail over as a link down
17873 			 * to FCF registration.
17874 			 */
17875 			lpfc_sli4_fcf_dead_failthrough(phba);
17876 		}
17877 	} else {
17878 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
17879 				"2775 Start FCF rediscover quiescent timer\n");
17880 		/*
17881 		 * Start FCF rediscovery wait timer for pending FCF
17882 		 * before rescan FCF record table.
17883 		 */
17884 		lpfc_fcf_redisc_wait_start_timer(phba);
17885 	}
17886 
17887 	mempool_free(mbox, phba->mbox_mem_pool);
17888 }
17889 
17890 /**
17891  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
17892  * @phba: pointer to lpfc hba data structure.
17893  *
17894  * This routine is invoked to request for rediscovery of the entire FCF table
17895  * by the port.
17896  **/
17897 int
17898 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
17899 {
17900 	LPFC_MBOXQ_t *mbox;
17901 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
17902 	int rc, length;
17903 
17904 	/* Cancel retry delay timers to all vports before FCF rediscover */
17905 	lpfc_cancel_all_vport_retry_delay_timer(phba);
17906 
17907 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17908 	if (!mbox) {
17909 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17910 				"2745 Failed to allocate mbox for "
17911 				"requesting FCF rediscover.\n");
17912 		return -ENOMEM;
17913 	}
17914 
17915 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
17916 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17917 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17918 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
17919 			 length, LPFC_SLI4_MBX_EMBED);
17920 
17921 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
17922 	/* Set count to 0 for invalidating the entire FCF database */
17923 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
17924 
17925 	/* Issue the mailbox command asynchronously */
17926 	mbox->vport = phba->pport;
17927 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
17928 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
17929 
17930 	if (rc == MBX_NOT_FINISHED) {
17931 		mempool_free(mbox, phba->mbox_mem_pool);
17932 		return -EIO;
17933 	}
17934 	return 0;
17935 }
17936 
17937 /**
17938  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
17939  * @phba: pointer to lpfc hba data structure.
17940  *
17941  * This function is the failover routine as a last resort to the FCF DEAD
17942  * event when driver failed to perform fast FCF failover.
17943  **/
17944 void
17945 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
17946 {
17947 	uint32_t link_state;
17948 
17949 	/*
17950 	 * Last resort as FCF DEAD event failover will treat this as
17951 	 * a link down, but save the link state because we don't want
17952 	 * it to be changed to Link Down unless it is already down.
17953 	 */
17954 	link_state = phba->link_state;
17955 	lpfc_linkdown(phba);
17956 	phba->link_state = link_state;
17957 
17958 	/* Unregister FCF if no devices connected to it */
17959 	lpfc_unregister_unused_fcf(phba);
17960 }
17961 
17962 /**
17963  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
17964  * @phba: pointer to lpfc hba data structure.
17965  * @rgn23_data: pointer to configure region 23 data.
17966  *
17967  * This function gets SLI3 port configure region 23 data through memory dump
17968  * mailbox command. When it successfully retrieves data, the size of the data
17969  * will be returned, otherwise, 0 will be returned.
17970  **/
17971 static uint32_t
17972 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
17973 {
17974 	LPFC_MBOXQ_t *pmb = NULL;
17975 	MAILBOX_t *mb;
17976 	uint32_t offset = 0;
17977 	int rc;
17978 
17979 	if (!rgn23_data)
17980 		return 0;
17981 
17982 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17983 	if (!pmb) {
17984 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17985 				"2600 failed to allocate mailbox memory\n");
17986 		return 0;
17987 	}
17988 	mb = &pmb->u.mb;
17989 
17990 	do {
17991 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
17992 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
17993 
17994 		if (rc != MBX_SUCCESS) {
17995 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17996 					"2601 failed to read config "
17997 					"region 23, rc 0x%x Status 0x%x\n",
17998 					rc, mb->mbxStatus);
17999 			mb->un.varDmp.word_cnt = 0;
18000 		}
18001 		/*
18002 		 * dump mem may return a zero when finished or we got a
18003 		 * mailbox error, either way we are done.
18004 		 */
18005 		if (mb->un.varDmp.word_cnt == 0)
18006 			break;
18007 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
18008 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
18009 
18010 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
18011 				       rgn23_data + offset,
18012 				       mb->un.varDmp.word_cnt);
18013 		offset += mb->un.varDmp.word_cnt;
18014 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
18015 
18016 	mempool_free(pmb, phba->mbox_mem_pool);
18017 	return offset;
18018 }
18019 
18020 /**
18021  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
18022  * @phba: pointer to lpfc hba data structure.
18023  * @rgn23_data: pointer to configure region 23 data.
18024  *
18025  * This function gets SLI4 port configure region 23 data through memory dump
18026  * mailbox command. When it successfully retrieves data, the size of the data
18027  * will be returned, otherwise, 0 will be returned.
18028  **/
18029 static uint32_t
18030 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
18031 {
18032 	LPFC_MBOXQ_t *mboxq = NULL;
18033 	struct lpfc_dmabuf *mp = NULL;
18034 	struct lpfc_mqe *mqe;
18035 	uint32_t data_length = 0;
18036 	int rc;
18037 
18038 	if (!rgn23_data)
18039 		return 0;
18040 
18041 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18042 	if (!mboxq) {
18043 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18044 				"3105 failed to allocate mailbox memory\n");
18045 		return 0;
18046 	}
18047 
18048 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
18049 		goto out;
18050 	mqe = &mboxq->u.mqe;
18051 	mp = (struct lpfc_dmabuf *) mboxq->context1;
18052 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
18053 	if (rc)
18054 		goto out;
18055 	data_length = mqe->un.mb_words[5];
18056 	if (data_length == 0)
18057 		goto out;
18058 	if (data_length > DMP_RGN23_SIZE) {
18059 		data_length = 0;
18060 		goto out;
18061 	}
18062 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
18063 out:
18064 	mempool_free(mboxq, phba->mbox_mem_pool);
18065 	if (mp) {
18066 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
18067 		kfree(mp);
18068 	}
18069 	return data_length;
18070 }
18071 
18072 /**
18073  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
18074  * @phba: pointer to lpfc hba data structure.
18075  *
18076  * This function read region 23 and parse TLV for port status to
18077  * decide if the user disaled the port. If the TLV indicates the
18078  * port is disabled, the hba_flag is set accordingly.
18079  **/
18080 void
18081 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
18082 {
18083 	uint8_t *rgn23_data = NULL;
18084 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
18085 	uint32_t offset = 0;
18086 
18087 	/* Get adapter Region 23 data */
18088 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
18089 	if (!rgn23_data)
18090 		goto out;
18091 
18092 	if (phba->sli_rev < LPFC_SLI_REV4)
18093 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
18094 	else {
18095 		if_type = bf_get(lpfc_sli_intf_if_type,
18096 				 &phba->sli4_hba.sli_intf);
18097 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
18098 			goto out;
18099 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
18100 	}
18101 
18102 	if (!data_size)
18103 		goto out;
18104 
18105 	/* Check the region signature first */
18106 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
18107 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18108 			"2619 Config region 23 has bad signature\n");
18109 			goto out;
18110 	}
18111 	offset += 4;
18112 
18113 	/* Check the data structure version */
18114 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
18115 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18116 			"2620 Config region 23 has bad version\n");
18117 		goto out;
18118 	}
18119 	offset += 4;
18120 
18121 	/* Parse TLV entries in the region */
18122 	while (offset < data_size) {
18123 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
18124 			break;
18125 		/*
18126 		 * If the TLV is not driver specific TLV or driver id is
18127 		 * not linux driver id, skip the record.
18128 		 */
18129 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
18130 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
18131 		    (rgn23_data[offset + 3] != 0)) {
18132 			offset += rgn23_data[offset + 1] * 4 + 4;
18133 			continue;
18134 		}
18135 
18136 		/* Driver found a driver specific TLV in the config region */
18137 		sub_tlv_len = rgn23_data[offset + 1] * 4;
18138 		offset += 4;
18139 		tlv_offset = 0;
18140 
18141 		/*
18142 		 * Search for configured port state sub-TLV.
18143 		 */
18144 		while ((offset < data_size) &&
18145 			(tlv_offset < sub_tlv_len)) {
18146 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
18147 				offset += 4;
18148 				tlv_offset += 4;
18149 				break;
18150 			}
18151 			if (rgn23_data[offset] != PORT_STE_TYPE) {
18152 				offset += rgn23_data[offset + 1] * 4 + 4;
18153 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
18154 				continue;
18155 			}
18156 
18157 			/* This HBA contains PORT_STE configured */
18158 			if (!rgn23_data[offset + 2])
18159 				phba->hba_flag |= LINK_DISABLED;
18160 
18161 			goto out;
18162 		}
18163 	}
18164 
18165 out:
18166 	kfree(rgn23_data);
18167 	return;
18168 }
18169 
18170 /**
18171  * lpfc_wr_object - write an object to the firmware
18172  * @phba: HBA structure that indicates port to create a queue on.
18173  * @dmabuf_list: list of dmabufs to write to the port.
18174  * @size: the total byte value of the objects to write to the port.
18175  * @offset: the current offset to be used to start the transfer.
18176  *
18177  * This routine will create a wr_object mailbox command to send to the port.
18178  * the mailbox command will be constructed using the dma buffers described in
18179  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
18180  * BDEs that the imbedded mailbox can support. The @offset variable will be
18181  * used to indicate the starting offset of the transfer and will also return
18182  * the offset after the write object mailbox has completed. @size is used to
18183  * determine the end of the object and whether the eof bit should be set.
18184  *
18185  * Return 0 is successful and offset will contain the the new offset to use
18186  * for the next write.
18187  * Return negative value for error cases.
18188  **/
18189 int
18190 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
18191 	       uint32_t size, uint32_t *offset)
18192 {
18193 	struct lpfc_mbx_wr_object *wr_object;
18194 	LPFC_MBOXQ_t *mbox;
18195 	int rc = 0, i = 0;
18196 	uint32_t shdr_status, shdr_add_status;
18197 	uint32_t mbox_tmo;
18198 	union lpfc_sli4_cfg_shdr *shdr;
18199 	struct lpfc_dmabuf *dmabuf;
18200 	uint32_t written = 0;
18201 
18202 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18203 	if (!mbox)
18204 		return -ENOMEM;
18205 
18206 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
18207 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
18208 			sizeof(struct lpfc_mbx_wr_object) -
18209 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
18210 
18211 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
18212 	wr_object->u.request.write_offset = *offset;
18213 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
18214 	wr_object->u.request.object_name[0] =
18215 		cpu_to_le32(wr_object->u.request.object_name[0]);
18216 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
18217 	list_for_each_entry(dmabuf, dmabuf_list, list) {
18218 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
18219 			break;
18220 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
18221 		wr_object->u.request.bde[i].addrHigh =
18222 			putPaddrHigh(dmabuf->phys);
18223 		if (written + SLI4_PAGE_SIZE >= size) {
18224 			wr_object->u.request.bde[i].tus.f.bdeSize =
18225 				(size - written);
18226 			written += (size - written);
18227 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
18228 		} else {
18229 			wr_object->u.request.bde[i].tus.f.bdeSize =
18230 				SLI4_PAGE_SIZE;
18231 			written += SLI4_PAGE_SIZE;
18232 		}
18233 		i++;
18234 	}
18235 	wr_object->u.request.bde_count = i;
18236 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
18237 	if (!phba->sli4_hba.intr_enable)
18238 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18239 	else {
18240 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18241 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18242 	}
18243 	/* The IOCTL status is embedded in the mailbox subheader. */
18244 	shdr = (union lpfc_sli4_cfg_shdr *) &wr_object->header.cfg_shdr;
18245 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18246 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18247 	if (rc != MBX_TIMEOUT)
18248 		mempool_free(mbox, phba->mbox_mem_pool);
18249 	if (shdr_status || shdr_add_status || rc) {
18250 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18251 				"3025 Write Object mailbox failed with "
18252 				"status x%x add_status x%x, mbx status x%x\n",
18253 				shdr_status, shdr_add_status, rc);
18254 		rc = -ENXIO;
18255 	} else
18256 		*offset += wr_object->u.response.actual_write_length;
18257 	return rc;
18258 }
18259 
18260 /**
18261  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
18262  * @vport: pointer to vport data structure.
18263  *
18264  * This function iterate through the mailboxq and clean up all REG_LOGIN
18265  * and REG_VPI mailbox commands associated with the vport. This function
18266  * is called when driver want to restart discovery of the vport due to
18267  * a Clear Virtual Link event.
18268  **/
18269 void
18270 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
18271 {
18272 	struct lpfc_hba *phba = vport->phba;
18273 	LPFC_MBOXQ_t *mb, *nextmb;
18274 	struct lpfc_dmabuf *mp;
18275 	struct lpfc_nodelist *ndlp;
18276 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
18277 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
18278 	LIST_HEAD(mbox_cmd_list);
18279 	uint8_t restart_loop;
18280 
18281 	/* Clean up internally queued mailbox commands with the vport */
18282 	spin_lock_irq(&phba->hbalock);
18283 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
18284 		if (mb->vport != vport)
18285 			continue;
18286 
18287 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
18288 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
18289 			continue;
18290 
18291 		list_del(&mb->list);
18292 		list_add_tail(&mb->list, &mbox_cmd_list);
18293 	}
18294 	/* Clean up active mailbox command with the vport */
18295 	mb = phba->sli.mbox_active;
18296 	if (mb && (mb->vport == vport)) {
18297 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
18298 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
18299 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
18300 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
18301 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->context2;
18302 			/* Put reference count for delayed processing */
18303 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
18304 			/* Unregister the RPI when mailbox complete */
18305 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
18306 		}
18307 	}
18308 	/* Cleanup any mailbox completions which are not yet processed */
18309 	do {
18310 		restart_loop = 0;
18311 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
18312 			/*
18313 			 * If this mailox is already processed or it is
18314 			 * for another vport ignore it.
18315 			 */
18316 			if ((mb->vport != vport) ||
18317 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
18318 				continue;
18319 
18320 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
18321 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
18322 				continue;
18323 
18324 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
18325 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
18326 				ndlp = (struct lpfc_nodelist *)mb->context2;
18327 				/* Unregister the RPI when mailbox complete */
18328 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
18329 				restart_loop = 1;
18330 				spin_unlock_irq(&phba->hbalock);
18331 				spin_lock(shost->host_lock);
18332 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
18333 				spin_unlock(shost->host_lock);
18334 				spin_lock_irq(&phba->hbalock);
18335 				break;
18336 			}
18337 		}
18338 	} while (restart_loop);
18339 
18340 	spin_unlock_irq(&phba->hbalock);
18341 
18342 	/* Release the cleaned-up mailbox commands */
18343 	while (!list_empty(&mbox_cmd_list)) {
18344 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
18345 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
18346 			mp = (struct lpfc_dmabuf *) (mb->context1);
18347 			if (mp) {
18348 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
18349 				kfree(mp);
18350 			}
18351 			ndlp = (struct lpfc_nodelist *) mb->context2;
18352 			mb->context2 = NULL;
18353 			if (ndlp) {
18354 				spin_lock(shost->host_lock);
18355 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
18356 				spin_unlock(shost->host_lock);
18357 				lpfc_nlp_put(ndlp);
18358 			}
18359 		}
18360 		mempool_free(mb, phba->mbox_mem_pool);
18361 	}
18362 
18363 	/* Release the ndlp with the cleaned-up active mailbox command */
18364 	if (act_mbx_ndlp) {
18365 		spin_lock(shost->host_lock);
18366 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
18367 		spin_unlock(shost->host_lock);
18368 		lpfc_nlp_put(act_mbx_ndlp);
18369 	}
18370 }
18371 
18372 /**
18373  * lpfc_drain_txq - Drain the txq
18374  * @phba: Pointer to HBA context object.
18375  *
18376  * This function attempt to submit IOCBs on the txq
18377  * to the adapter.  For SLI4 adapters, the txq contains
18378  * ELS IOCBs that have been deferred because the there
18379  * are no SGLs.  This congestion can occur with large
18380  * vport counts during node discovery.
18381  **/
18382 
18383 uint32_t
18384 lpfc_drain_txq(struct lpfc_hba *phba)
18385 {
18386 	LIST_HEAD(completions);
18387 	struct lpfc_sli_ring *pring;
18388 	struct lpfc_iocbq *piocbq = NULL;
18389 	unsigned long iflags = 0;
18390 	char *fail_msg = NULL;
18391 	struct lpfc_sglq *sglq;
18392 	union lpfc_wqe128 wqe128;
18393 	union lpfc_wqe *wqe = (union lpfc_wqe *) &wqe128;
18394 	uint32_t txq_cnt = 0;
18395 
18396 	pring = lpfc_phba_elsring(phba);
18397 
18398 	spin_lock_irqsave(&pring->ring_lock, iflags);
18399 	list_for_each_entry(piocbq, &pring->txq, list) {
18400 		txq_cnt++;
18401 	}
18402 
18403 	if (txq_cnt > pring->txq_max)
18404 		pring->txq_max = txq_cnt;
18405 
18406 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
18407 
18408 	while (!list_empty(&pring->txq)) {
18409 		spin_lock_irqsave(&pring->ring_lock, iflags);
18410 
18411 		piocbq = lpfc_sli_ringtx_get(phba, pring);
18412 		if (!piocbq) {
18413 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
18414 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18415 				"2823 txq empty and txq_cnt is %d\n ",
18416 				txq_cnt);
18417 			break;
18418 		}
18419 		sglq = __lpfc_sli_get_els_sglq(phba, piocbq);
18420 		if (!sglq) {
18421 			__lpfc_sli_ringtx_put(phba, pring, piocbq);
18422 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
18423 			break;
18424 		}
18425 		txq_cnt--;
18426 
18427 		/* The xri and iocb resources secured,
18428 		 * attempt to issue request
18429 		 */
18430 		piocbq->sli4_lxritag = sglq->sli4_lxritag;
18431 		piocbq->sli4_xritag = sglq->sli4_xritag;
18432 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
18433 			fail_msg = "to convert bpl to sgl";
18434 		else if (lpfc_sli4_iocb2wqe(phba, piocbq, wqe))
18435 			fail_msg = "to convert iocb to wqe";
18436 		else if (lpfc_sli4_wq_put(phba->sli4_hba.els_wq, wqe))
18437 			fail_msg = " - Wq is full";
18438 		else
18439 			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
18440 
18441 		if (fail_msg) {
18442 			/* Failed means we can't issue and need to cancel */
18443 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18444 					"2822 IOCB failed %s iotag 0x%x "
18445 					"xri 0x%x\n",
18446 					fail_msg,
18447 					piocbq->iotag, piocbq->sli4_xritag);
18448 			list_add_tail(&piocbq->list, &completions);
18449 		}
18450 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
18451 	}
18452 
18453 	/* Cancel all the IOCBs that cannot be issued */
18454 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
18455 				IOERR_SLI_ABORTED);
18456 
18457 	return txq_cnt;
18458 }
18459 
18460 /**
18461  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
18462  * @phba: Pointer to HBA context object.
18463  * @pwqe: Pointer to command WQE.
18464  * @sglq: Pointer to the scatter gather queue object.
18465  *
18466  * This routine converts the bpl or bde that is in the WQE
18467  * to a sgl list for the sli4 hardware. The physical address
18468  * of the bpl/bde is converted back to a virtual address.
18469  * If the WQE contains a BPL then the list of BDE's is
18470  * converted to sli4_sge's. If the WQE contains a single
18471  * BDE then it is converted to a single sli_sge.
18472  * The WQE is still in cpu endianness so the contents of
18473  * the bpl can be used without byte swapping.
18474  *
18475  * Returns valid XRI = Success, NO_XRI = Failure.
18476  */
18477 static uint16_t
18478 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
18479 		 struct lpfc_sglq *sglq)
18480 {
18481 	uint16_t xritag = NO_XRI;
18482 	struct ulp_bde64 *bpl = NULL;
18483 	struct ulp_bde64 bde;
18484 	struct sli4_sge *sgl  = NULL;
18485 	struct lpfc_dmabuf *dmabuf;
18486 	union lpfc_wqe *wqe;
18487 	int numBdes = 0;
18488 	int i = 0;
18489 	uint32_t offset = 0; /* accumulated offset in the sg request list */
18490 	int inbound = 0; /* number of sg reply entries inbound from firmware */
18491 	uint32_t cmd;
18492 
18493 	if (!pwqeq || !sglq)
18494 		return xritag;
18495 
18496 	sgl  = (struct sli4_sge *)sglq->sgl;
18497 	wqe = &pwqeq->wqe;
18498 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
18499 
18500 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
18501 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
18502 		return sglq->sli4_xritag;
18503 	numBdes = pwqeq->rsvd2;
18504 	if (numBdes) {
18505 		/* The addrHigh and addrLow fields within the WQE
18506 		 * have not been byteswapped yet so there is no
18507 		 * need to swap them back.
18508 		 */
18509 		if (pwqeq->context3)
18510 			dmabuf = (struct lpfc_dmabuf *)pwqeq->context3;
18511 		else
18512 			return xritag;
18513 
18514 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
18515 		if (!bpl)
18516 			return xritag;
18517 
18518 		for (i = 0; i < numBdes; i++) {
18519 			/* Should already be byte swapped. */
18520 			sgl->addr_hi = bpl->addrHigh;
18521 			sgl->addr_lo = bpl->addrLow;
18522 
18523 			sgl->word2 = le32_to_cpu(sgl->word2);
18524 			if ((i+1) == numBdes)
18525 				bf_set(lpfc_sli4_sge_last, sgl, 1);
18526 			else
18527 				bf_set(lpfc_sli4_sge_last, sgl, 0);
18528 			/* swap the size field back to the cpu so we
18529 			 * can assign it to the sgl.
18530 			 */
18531 			bde.tus.w = le32_to_cpu(bpl->tus.w);
18532 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
18533 			/* The offsets in the sgl need to be accumulated
18534 			 * separately for the request and reply lists.
18535 			 * The request is always first, the reply follows.
18536 			 */
18537 			switch (cmd) {
18538 			case CMD_GEN_REQUEST64_WQE:
18539 				/* add up the reply sg entries */
18540 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
18541 					inbound++;
18542 				/* first inbound? reset the offset */
18543 				if (inbound == 1)
18544 					offset = 0;
18545 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
18546 				bf_set(lpfc_sli4_sge_type, sgl,
18547 					LPFC_SGE_TYPE_DATA);
18548 				offset += bde.tus.f.bdeSize;
18549 				break;
18550 			case CMD_FCP_TRSP64_WQE:
18551 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
18552 				bf_set(lpfc_sli4_sge_type, sgl,
18553 					LPFC_SGE_TYPE_DATA);
18554 				break;
18555 			case CMD_FCP_TSEND64_WQE:
18556 			case CMD_FCP_TRECEIVE64_WQE:
18557 				bf_set(lpfc_sli4_sge_type, sgl,
18558 					bpl->tus.f.bdeFlags);
18559 				if (i < 3)
18560 					offset = 0;
18561 				else
18562 					offset += bde.tus.f.bdeSize;
18563 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
18564 				break;
18565 			}
18566 			sgl->word2 = cpu_to_le32(sgl->word2);
18567 			bpl++;
18568 			sgl++;
18569 		}
18570 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
18571 		/* The addrHigh and addrLow fields of the BDE have not
18572 		 * been byteswapped yet so they need to be swapped
18573 		 * before putting them in the sgl.
18574 		 */
18575 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
18576 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
18577 		sgl->word2 = le32_to_cpu(sgl->word2);
18578 		bf_set(lpfc_sli4_sge_last, sgl, 1);
18579 		sgl->word2 = cpu_to_le32(sgl->word2);
18580 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
18581 	}
18582 	return sglq->sli4_xritag;
18583 }
18584 
18585 /**
18586  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
18587  * @phba: Pointer to HBA context object.
18588  * @ring_number: Base sli ring number
18589  * @pwqe: Pointer to command WQE.
18590  **/
18591 int
18592 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, uint32_t ring_number,
18593 		    struct lpfc_iocbq *pwqe)
18594 {
18595 	union lpfc_wqe *wqe = &pwqe->wqe;
18596 	struct lpfc_nvmet_rcv_ctx *ctxp;
18597 	struct lpfc_queue *wq;
18598 	struct lpfc_sglq *sglq;
18599 	struct lpfc_sli_ring *pring;
18600 	unsigned long iflags;
18601 
18602 	/* NVME_LS and NVME_LS ABTS requests. */
18603 	if (pwqe->iocb_flag & LPFC_IO_NVME_LS) {
18604 		pring =  phba->sli4_hba.nvmels_wq->pring;
18605 		spin_lock_irqsave(&pring->ring_lock, iflags);
18606 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
18607 		if (!sglq) {
18608 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
18609 			return WQE_BUSY;
18610 		}
18611 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
18612 		pwqe->sli4_xritag = sglq->sli4_xritag;
18613 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
18614 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
18615 			return WQE_ERROR;
18616 		}
18617 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
18618 		       pwqe->sli4_xritag);
18619 		if (lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe)) {
18620 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
18621 			return WQE_ERROR;
18622 		}
18623 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
18624 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
18625 		return 0;
18626 	}
18627 
18628 	/* NVME_FCREQ and NVME_ABTS requests */
18629 	if (pwqe->iocb_flag & LPFC_IO_NVME) {
18630 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
18631 		pring = phba->sli4_hba.nvme_wq[pwqe->hba_wqidx]->pring;
18632 
18633 		spin_lock_irqsave(&pring->ring_lock, iflags);
18634 		wq = phba->sli4_hba.nvme_wq[pwqe->hba_wqidx];
18635 		bf_set(wqe_cqid, &wqe->generic.wqe_com,
18636 		      phba->sli4_hba.nvme_cq[pwqe->hba_wqidx]->queue_id);
18637 		if (lpfc_sli4_wq_put(wq, wqe)) {
18638 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
18639 			return WQE_ERROR;
18640 		}
18641 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
18642 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
18643 		return 0;
18644 	}
18645 
18646 	/* NVMET requests */
18647 	if (pwqe->iocb_flag & LPFC_IO_NVMET) {
18648 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
18649 		pring = phba->sli4_hba.nvme_wq[pwqe->hba_wqidx]->pring;
18650 
18651 		spin_lock_irqsave(&pring->ring_lock, iflags);
18652 		ctxp = pwqe->context2;
18653 		sglq = ctxp->rqb_buffer->sglq;
18654 		if (pwqe->sli4_xritag ==  NO_XRI) {
18655 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
18656 			pwqe->sli4_xritag = sglq->sli4_xritag;
18657 		}
18658 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
18659 		       pwqe->sli4_xritag);
18660 		wq = phba->sli4_hba.nvme_wq[pwqe->hba_wqidx];
18661 		bf_set(wqe_cqid, &wqe->generic.wqe_com,
18662 		      phba->sli4_hba.nvme_cq[pwqe->hba_wqidx]->queue_id);
18663 		if (lpfc_sli4_wq_put(wq, wqe)) {
18664 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
18665 			return WQE_ERROR;
18666 		}
18667 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
18668 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
18669 		return 0;
18670 	}
18671 	return WQE_ERROR;
18672 }
18673