xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision a2cce7a9)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2004-2015 Emulex.  All rights reserved.           *
5  * EMULEX and SLI are trademarks of Emulex.                        *
6  * www.emulex.com                                                  *
7  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
8  *                                                                 *
9  * This program is free software; you can redistribute it and/or   *
10  * modify it under the terms of version 2 of the GNU General       *
11  * Public License as published by the Free Software Foundation.    *
12  * This program is distributed in the hope that it will be useful. *
13  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
14  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
15  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
16  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
17  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
18  * more details, a copy of which can be found in the file COPYING  *
19  * included with this package.                                     *
20  *******************************************************************/
21 
22 #include <linux/blkdev.h>
23 #include <linux/pci.h>
24 #include <linux/interrupt.h>
25 #include <linux/delay.h>
26 #include <linux/slab.h>
27 
28 #include <scsi/scsi.h>
29 #include <scsi/scsi_cmnd.h>
30 #include <scsi/scsi_device.h>
31 #include <scsi/scsi_host.h>
32 #include <scsi/scsi_transport_fc.h>
33 #include <scsi/fc/fc_fs.h>
34 #include <linux/aer.h>
35 
36 #include "lpfc_hw4.h"
37 #include "lpfc_hw.h"
38 #include "lpfc_sli.h"
39 #include "lpfc_sli4.h"
40 #include "lpfc_nl.h"
41 #include "lpfc_disc.h"
42 #include "lpfc_scsi.h"
43 #include "lpfc.h"
44 #include "lpfc_crtn.h"
45 #include "lpfc_logmsg.h"
46 #include "lpfc_compat.h"
47 #include "lpfc_debugfs.h"
48 #include "lpfc_vport.h"
49 
50 /* There are only four IOCB completion types. */
51 typedef enum _lpfc_iocb_type {
52 	LPFC_UNKNOWN_IOCB,
53 	LPFC_UNSOL_IOCB,
54 	LPFC_SOL_IOCB,
55 	LPFC_ABORT_IOCB
56 } lpfc_iocb_type;
57 
58 
59 /* Provide function prototypes local to this module. */
60 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
61 				  uint32_t);
62 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
63 			      uint8_t *, uint32_t *);
64 static struct lpfc_iocbq *lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *,
65 							 struct lpfc_iocbq *);
66 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
67 				      struct hbq_dmabuf *);
68 static int lpfc_sli4_fp_handle_wcqe(struct lpfc_hba *, struct lpfc_queue *,
69 				    struct lpfc_cqe *);
70 static int lpfc_sli4_post_els_sgl_list(struct lpfc_hba *, struct list_head *,
71 				       int);
72 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *, struct lpfc_eqe *,
73 			uint32_t);
74 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
75 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
76 
77 static IOCB_t *
78 lpfc_get_iocb_from_iocbq(struct lpfc_iocbq *iocbq)
79 {
80 	return &iocbq->iocb;
81 }
82 
83 /**
84  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
85  * @q: The Work Queue to operate on.
86  * @wqe: The work Queue Entry to put on the Work queue.
87  *
88  * This routine will copy the contents of @wqe to the next available entry on
89  * the @q. This function will then ring the Work Queue Doorbell to signal the
90  * HBA to start processing the Work Queue Entry. This function returns 0 if
91  * successful. If no entries are available on @q then this function will return
92  * -ENOMEM.
93  * The caller is expected to hold the hbalock when calling this routine.
94  **/
95 static uint32_t
96 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe *wqe)
97 {
98 	union lpfc_wqe *temp_wqe;
99 	struct lpfc_register doorbell;
100 	uint32_t host_index;
101 	uint32_t idx;
102 
103 	/* sanity check on queue memory */
104 	if (unlikely(!q))
105 		return -ENOMEM;
106 	temp_wqe = q->qe[q->host_index].wqe;
107 
108 	/* If the host has not yet processed the next entry then we are done */
109 	idx = ((q->host_index + 1) % q->entry_count);
110 	if (idx == q->hba_index) {
111 		q->WQ_overflow++;
112 		return -ENOMEM;
113 	}
114 	q->WQ_posted++;
115 	/* set consumption flag every once in a while */
116 	if (!((q->host_index + 1) % q->entry_repost))
117 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
118 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
119 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
120 	lpfc_sli_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
121 
122 	/* Update the host index before invoking device */
123 	host_index = q->host_index;
124 
125 	q->host_index = idx;
126 
127 	/* Ring Doorbell */
128 	doorbell.word0 = 0;
129 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
130 		bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
131 		bf_set(lpfc_wq_db_list_fm_index, &doorbell, host_index);
132 		bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
133 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
134 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
135 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
136 	} else {
137 		return -EINVAL;
138 	}
139 	writel(doorbell.word0, q->db_regaddr);
140 
141 	return 0;
142 }
143 
144 /**
145  * lpfc_sli4_wq_release - Updates internal hba index for WQ
146  * @q: The Work Queue to operate on.
147  * @index: The index to advance the hba index to.
148  *
149  * This routine will update the HBA index of a queue to reflect consumption of
150  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
151  * an entry the host calls this function to update the queue's internal
152  * pointers. This routine returns the number of entries that were consumed by
153  * the HBA.
154  **/
155 static uint32_t
156 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
157 {
158 	uint32_t released = 0;
159 
160 	/* sanity check on queue memory */
161 	if (unlikely(!q))
162 		return 0;
163 
164 	if (q->hba_index == index)
165 		return 0;
166 	do {
167 		q->hba_index = ((q->hba_index + 1) % q->entry_count);
168 		released++;
169 	} while (q->hba_index != index);
170 	return released;
171 }
172 
173 /**
174  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
175  * @q: The Mailbox Queue to operate on.
176  * @wqe: The Mailbox Queue Entry to put on the Work queue.
177  *
178  * This routine will copy the contents of @mqe to the next available entry on
179  * the @q. This function will then ring the Work Queue Doorbell to signal the
180  * HBA to start processing the Work Queue Entry. This function returns 0 if
181  * successful. If no entries are available on @q then this function will return
182  * -ENOMEM.
183  * The caller is expected to hold the hbalock when calling this routine.
184  **/
185 static uint32_t
186 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
187 {
188 	struct lpfc_mqe *temp_mqe;
189 	struct lpfc_register doorbell;
190 
191 	/* sanity check on queue memory */
192 	if (unlikely(!q))
193 		return -ENOMEM;
194 	temp_mqe = q->qe[q->host_index].mqe;
195 
196 	/* If the host has not yet processed the next entry then we are done */
197 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
198 		return -ENOMEM;
199 	lpfc_sli_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
200 	/* Save off the mailbox pointer for completion */
201 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
202 
203 	/* Update the host index before invoking device */
204 	q->host_index = ((q->host_index + 1) % q->entry_count);
205 
206 	/* Ring Doorbell */
207 	doorbell.word0 = 0;
208 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
209 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
210 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
211 	return 0;
212 }
213 
214 /**
215  * lpfc_sli4_mq_release - Updates internal hba index for MQ
216  * @q: The Mailbox Queue to operate on.
217  *
218  * This routine will update the HBA index of a queue to reflect consumption of
219  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
220  * an entry the host calls this function to update the queue's internal
221  * pointers. This routine returns the number of entries that were consumed by
222  * the HBA.
223  **/
224 static uint32_t
225 lpfc_sli4_mq_release(struct lpfc_queue *q)
226 {
227 	/* sanity check on queue memory */
228 	if (unlikely(!q))
229 		return 0;
230 
231 	/* Clear the mailbox pointer for completion */
232 	q->phba->mbox = NULL;
233 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
234 	return 1;
235 }
236 
237 /**
238  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
239  * @q: The Event Queue to get the first valid EQE from
240  *
241  * This routine will get the first valid Event Queue Entry from @q, update
242  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
243  * the Queue (no more work to do), or the Queue is full of EQEs that have been
244  * processed, but not popped back to the HBA then this routine will return NULL.
245  **/
246 static struct lpfc_eqe *
247 lpfc_sli4_eq_get(struct lpfc_queue *q)
248 {
249 	struct lpfc_eqe *eqe;
250 	uint32_t idx;
251 
252 	/* sanity check on queue memory */
253 	if (unlikely(!q))
254 		return NULL;
255 	eqe = q->qe[q->hba_index].eqe;
256 
257 	/* If the next EQE is not valid then we are done */
258 	if (!bf_get_le32(lpfc_eqe_valid, eqe))
259 		return NULL;
260 	/* If the host has not yet processed the next entry then we are done */
261 	idx = ((q->hba_index + 1) % q->entry_count);
262 	if (idx == q->host_index)
263 		return NULL;
264 
265 	q->hba_index = idx;
266 
267 	/*
268 	 * insert barrier for instruction interlock : data from the hardware
269 	 * must have the valid bit checked before it can be copied and acted
270 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
271 	 * instructions allowing action on content before valid bit checked,
272 	 * add barrier here as well. May not be needed as "content" is a
273 	 * single 32-bit entity here (vs multi word structure for cq's).
274 	 */
275 	mb();
276 	return eqe;
277 }
278 
279 /**
280  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
281  * @q: The Event Queue to disable interrupts
282  *
283  **/
284 static inline void
285 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
286 {
287 	struct lpfc_register doorbell;
288 
289 	doorbell.word0 = 0;
290 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
291 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
292 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
293 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
294 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
295 	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
296 }
297 
298 /**
299  * lpfc_sli4_eq_release - Indicates the host has finished processing an EQ
300  * @q: The Event Queue that the host has completed processing for.
301  * @arm: Indicates whether the host wants to arms this CQ.
302  *
303  * This routine will mark all Event Queue Entries on @q, from the last
304  * known completed entry to the last entry that was processed, as completed
305  * by clearing the valid bit for each completion queue entry. Then it will
306  * notify the HBA, by ringing the doorbell, that the EQEs have been processed.
307  * The internal host index in the @q will be updated by this routine to indicate
308  * that the host has finished processing the entries. The @arm parameter
309  * indicates that the queue should be rearmed when ringing the doorbell.
310  *
311  * This function will return the number of EQEs that were popped.
312  **/
313 uint32_t
314 lpfc_sli4_eq_release(struct lpfc_queue *q, bool arm)
315 {
316 	uint32_t released = 0;
317 	struct lpfc_eqe *temp_eqe;
318 	struct lpfc_register doorbell;
319 
320 	/* sanity check on queue memory */
321 	if (unlikely(!q))
322 		return 0;
323 
324 	/* while there are valid entries */
325 	while (q->hba_index != q->host_index) {
326 		temp_eqe = q->qe[q->host_index].eqe;
327 		bf_set_le32(lpfc_eqe_valid, temp_eqe, 0);
328 		released++;
329 		q->host_index = ((q->host_index + 1) % q->entry_count);
330 	}
331 	if (unlikely(released == 0 && !arm))
332 		return 0;
333 
334 	/* ring doorbell for number popped */
335 	doorbell.word0 = 0;
336 	if (arm) {
337 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
338 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
339 	}
340 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, released);
341 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
342 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
343 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
344 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
345 	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
346 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
347 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
348 		readl(q->phba->sli4_hba.EQCQDBregaddr);
349 	return released;
350 }
351 
352 /**
353  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
354  * @q: The Completion Queue to get the first valid CQE from
355  *
356  * This routine will get the first valid Completion Queue Entry from @q, update
357  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
358  * the Queue (no more work to do), or the Queue is full of CQEs that have been
359  * processed, but not popped back to the HBA then this routine will return NULL.
360  **/
361 static struct lpfc_cqe *
362 lpfc_sli4_cq_get(struct lpfc_queue *q)
363 {
364 	struct lpfc_cqe *cqe;
365 	uint32_t idx;
366 
367 	/* sanity check on queue memory */
368 	if (unlikely(!q))
369 		return NULL;
370 
371 	/* If the next CQE is not valid then we are done */
372 	if (!bf_get_le32(lpfc_cqe_valid, q->qe[q->hba_index].cqe))
373 		return NULL;
374 	/* If the host has not yet processed the next entry then we are done */
375 	idx = ((q->hba_index + 1) % q->entry_count);
376 	if (idx == q->host_index)
377 		return NULL;
378 
379 	cqe = q->qe[q->hba_index].cqe;
380 	q->hba_index = idx;
381 
382 	/*
383 	 * insert barrier for instruction interlock : data from the hardware
384 	 * must have the valid bit checked before it can be copied and acted
385 	 * upon. Speculative instructions were allowing a bcopy at the start
386 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
387 	 * after our return, to copy data before the valid bit check above
388 	 * was done. As such, some of the copied data was stale. The barrier
389 	 * ensures the check is before any data is copied.
390 	 */
391 	mb();
392 	return cqe;
393 }
394 
395 /**
396  * lpfc_sli4_cq_release - Indicates the host has finished processing a CQ
397  * @q: The Completion Queue that the host has completed processing for.
398  * @arm: Indicates whether the host wants to arms this CQ.
399  *
400  * This routine will mark all Completion queue entries on @q, from the last
401  * known completed entry to the last entry that was processed, as completed
402  * by clearing the valid bit for each completion queue entry. Then it will
403  * notify the HBA, by ringing the doorbell, that the CQEs have been processed.
404  * The internal host index in the @q will be updated by this routine to indicate
405  * that the host has finished processing the entries. The @arm parameter
406  * indicates that the queue should be rearmed when ringing the doorbell.
407  *
408  * This function will return the number of CQEs that were released.
409  **/
410 uint32_t
411 lpfc_sli4_cq_release(struct lpfc_queue *q, bool arm)
412 {
413 	uint32_t released = 0;
414 	struct lpfc_cqe *temp_qe;
415 	struct lpfc_register doorbell;
416 
417 	/* sanity check on queue memory */
418 	if (unlikely(!q))
419 		return 0;
420 	/* while there are valid entries */
421 	while (q->hba_index != q->host_index) {
422 		temp_qe = q->qe[q->host_index].cqe;
423 		bf_set_le32(lpfc_cqe_valid, temp_qe, 0);
424 		released++;
425 		q->host_index = ((q->host_index + 1) % q->entry_count);
426 	}
427 	if (unlikely(released == 0 && !arm))
428 		return 0;
429 
430 	/* ring doorbell for number popped */
431 	doorbell.word0 = 0;
432 	if (arm)
433 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
434 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, released);
435 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
436 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
437 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
438 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
439 	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
440 	return released;
441 }
442 
443 /**
444  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
445  * @q: The Header Receive Queue to operate on.
446  * @wqe: The Receive Queue Entry to put on the Receive queue.
447  *
448  * This routine will copy the contents of @wqe to the next available entry on
449  * the @q. This function will then ring the Receive Queue Doorbell to signal the
450  * HBA to start processing the Receive Queue Entry. This function returns the
451  * index that the rqe was copied to if successful. If no entries are available
452  * on @q then this function will return -ENOMEM.
453  * The caller is expected to hold the hbalock when calling this routine.
454  **/
455 static int
456 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
457 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
458 {
459 	struct lpfc_rqe *temp_hrqe;
460 	struct lpfc_rqe *temp_drqe;
461 	struct lpfc_register doorbell;
462 	int put_index;
463 
464 	/* sanity check on queue memory */
465 	if (unlikely(!hq) || unlikely(!dq))
466 		return -ENOMEM;
467 	put_index = hq->host_index;
468 	temp_hrqe = hq->qe[hq->host_index].rqe;
469 	temp_drqe = dq->qe[dq->host_index].rqe;
470 
471 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
472 		return -EINVAL;
473 	if (hq->host_index != dq->host_index)
474 		return -EINVAL;
475 	/* If the host has not yet processed the next entry then we are done */
476 	if (((hq->host_index + 1) % hq->entry_count) == hq->hba_index)
477 		return -EBUSY;
478 	lpfc_sli_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
479 	lpfc_sli_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
480 
481 	/* Update the host index to point to the next slot */
482 	hq->host_index = ((hq->host_index + 1) % hq->entry_count);
483 	dq->host_index = ((dq->host_index + 1) % dq->entry_count);
484 
485 	/* Ring The Header Receive Queue Doorbell */
486 	if (!(hq->host_index % hq->entry_repost)) {
487 		doorbell.word0 = 0;
488 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
489 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
490 			       hq->entry_repost);
491 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
492 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
493 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
494 			       hq->entry_repost);
495 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
496 			       hq->host_index);
497 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
498 		} else {
499 			return -EINVAL;
500 		}
501 		writel(doorbell.word0, hq->db_regaddr);
502 	}
503 	return put_index;
504 }
505 
506 /**
507  * lpfc_sli4_rq_release - Updates internal hba index for RQ
508  * @q: The Header Receive Queue to operate on.
509  *
510  * This routine will update the HBA index of a queue to reflect consumption of
511  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
512  * consumed an entry the host calls this function to update the queue's
513  * internal pointers. This routine returns the number of entries that were
514  * consumed by the HBA.
515  **/
516 static uint32_t
517 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
518 {
519 	/* sanity check on queue memory */
520 	if (unlikely(!hq) || unlikely(!dq))
521 		return 0;
522 
523 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
524 		return 0;
525 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
526 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
527 	return 1;
528 }
529 
530 /**
531  * lpfc_cmd_iocb - Get next command iocb entry in the ring
532  * @phba: Pointer to HBA context object.
533  * @pring: Pointer to driver SLI ring object.
534  *
535  * This function returns pointer to next command iocb entry
536  * in the command ring. The caller must hold hbalock to prevent
537  * other threads consume the next command iocb.
538  * SLI-2/SLI-3 provide different sized iocbs.
539  **/
540 static inline IOCB_t *
541 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
542 {
543 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
544 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
545 }
546 
547 /**
548  * lpfc_resp_iocb - Get next response iocb entry in the ring
549  * @phba: Pointer to HBA context object.
550  * @pring: Pointer to driver SLI ring object.
551  *
552  * This function returns pointer to next response iocb entry
553  * in the response ring. The caller must hold hbalock to make sure
554  * that no other thread consume the next response iocb.
555  * SLI-2/SLI-3 provide different sized iocbs.
556  **/
557 static inline IOCB_t *
558 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
559 {
560 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
561 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
562 }
563 
564 /**
565  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
566  * @phba: Pointer to HBA context object.
567  *
568  * This function is called with hbalock held. This function
569  * allocates a new driver iocb object from the iocb pool. If the
570  * allocation is successful, it returns pointer to the newly
571  * allocated iocb object else it returns NULL.
572  **/
573 struct lpfc_iocbq *
574 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
575 {
576 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
577 	struct lpfc_iocbq * iocbq = NULL;
578 
579 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
580 	if (iocbq)
581 		phba->iocb_cnt++;
582 	if (phba->iocb_cnt > phba->iocb_max)
583 		phba->iocb_max = phba->iocb_cnt;
584 	return iocbq;
585 }
586 
587 /**
588  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
589  * @phba: Pointer to HBA context object.
590  * @xritag: XRI value.
591  *
592  * This function clears the sglq pointer from the array of acive
593  * sglq's. The xritag that is passed in is used to index into the
594  * array. Before the xritag can be used it needs to be adjusted
595  * by subtracting the xribase.
596  *
597  * Returns sglq ponter = success, NULL = Failure.
598  **/
599 static struct lpfc_sglq *
600 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
601 {
602 	struct lpfc_sglq *sglq;
603 
604 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
605 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
606 	return sglq;
607 }
608 
609 /**
610  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
611  * @phba: Pointer to HBA context object.
612  * @xritag: XRI value.
613  *
614  * This function returns the sglq pointer from the array of acive
615  * sglq's. The xritag that is passed in is used to index into the
616  * array. Before the xritag can be used it needs to be adjusted
617  * by subtracting the xribase.
618  *
619  * Returns sglq ponter = success, NULL = Failure.
620  **/
621 struct lpfc_sglq *
622 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
623 {
624 	struct lpfc_sglq *sglq;
625 
626 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
627 	return sglq;
628 }
629 
630 /**
631  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
632  * @phba: Pointer to HBA context object.
633  * @xritag: xri used in this exchange.
634  * @rrq: The RRQ to be cleared.
635  *
636  **/
637 void
638 lpfc_clr_rrq_active(struct lpfc_hba *phba,
639 		    uint16_t xritag,
640 		    struct lpfc_node_rrq *rrq)
641 {
642 	struct lpfc_nodelist *ndlp = NULL;
643 
644 	if ((rrq->vport) && NLP_CHK_NODE_ACT(rrq->ndlp))
645 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
646 
647 	/* The target DID could have been swapped (cable swap)
648 	 * we should use the ndlp from the findnode if it is
649 	 * available.
650 	 */
651 	if ((!ndlp) && rrq->ndlp)
652 		ndlp = rrq->ndlp;
653 
654 	if (!ndlp)
655 		goto out;
656 
657 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
658 		rrq->send_rrq = 0;
659 		rrq->xritag = 0;
660 		rrq->rrq_stop_time = 0;
661 	}
662 out:
663 	mempool_free(rrq, phba->rrq_pool);
664 }
665 
666 /**
667  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
668  * @phba: Pointer to HBA context object.
669  *
670  * This function is called with hbalock held. This function
671  * Checks if stop_time (ratov from setting rrq active) has
672  * been reached, if it has and the send_rrq flag is set then
673  * it will call lpfc_send_rrq. If the send_rrq flag is not set
674  * then it will just call the routine to clear the rrq and
675  * free the rrq resource.
676  * The timer is set to the next rrq that is going to expire before
677  * leaving the routine.
678  *
679  **/
680 void
681 lpfc_handle_rrq_active(struct lpfc_hba *phba)
682 {
683 	struct lpfc_node_rrq *rrq;
684 	struct lpfc_node_rrq *nextrrq;
685 	unsigned long next_time;
686 	unsigned long iflags;
687 	LIST_HEAD(send_rrq);
688 
689 	spin_lock_irqsave(&phba->hbalock, iflags);
690 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
691 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
692 	list_for_each_entry_safe(rrq, nextrrq,
693 				 &phba->active_rrq_list, list) {
694 		if (time_after(jiffies, rrq->rrq_stop_time))
695 			list_move(&rrq->list, &send_rrq);
696 		else if (time_before(rrq->rrq_stop_time, next_time))
697 			next_time = rrq->rrq_stop_time;
698 	}
699 	spin_unlock_irqrestore(&phba->hbalock, iflags);
700 	if ((!list_empty(&phba->active_rrq_list)) &&
701 	    (!(phba->pport->load_flag & FC_UNLOADING)))
702 		mod_timer(&phba->rrq_tmr, next_time);
703 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
704 		list_del(&rrq->list);
705 		if (!rrq->send_rrq)
706 			/* this call will free the rrq */
707 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
708 		else if (lpfc_send_rrq(phba, rrq)) {
709 			/* if we send the rrq then the completion handler
710 			*  will clear the bit in the xribitmap.
711 			*/
712 			lpfc_clr_rrq_active(phba, rrq->xritag,
713 					    rrq);
714 		}
715 	}
716 }
717 
718 /**
719  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
720  * @vport: Pointer to vport context object.
721  * @xri: The xri used in the exchange.
722  * @did: The targets DID for this exchange.
723  *
724  * returns NULL = rrq not found in the phba->active_rrq_list.
725  *         rrq = rrq for this xri and target.
726  **/
727 struct lpfc_node_rrq *
728 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
729 {
730 	struct lpfc_hba *phba = vport->phba;
731 	struct lpfc_node_rrq *rrq;
732 	struct lpfc_node_rrq *nextrrq;
733 	unsigned long iflags;
734 
735 	if (phba->sli_rev != LPFC_SLI_REV4)
736 		return NULL;
737 	spin_lock_irqsave(&phba->hbalock, iflags);
738 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
739 		if (rrq->vport == vport && rrq->xritag == xri &&
740 				rrq->nlp_DID == did){
741 			list_del(&rrq->list);
742 			spin_unlock_irqrestore(&phba->hbalock, iflags);
743 			return rrq;
744 		}
745 	}
746 	spin_unlock_irqrestore(&phba->hbalock, iflags);
747 	return NULL;
748 }
749 
750 /**
751  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
752  * @vport: Pointer to vport context object.
753  * @ndlp: Pointer to the lpfc_node_list structure.
754  * If ndlp is NULL Remove all active RRQs for this vport from the
755  * phba->active_rrq_list and clear the rrq.
756  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
757  **/
758 void
759 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
760 
761 {
762 	struct lpfc_hba *phba = vport->phba;
763 	struct lpfc_node_rrq *rrq;
764 	struct lpfc_node_rrq *nextrrq;
765 	unsigned long iflags;
766 	LIST_HEAD(rrq_list);
767 
768 	if (phba->sli_rev != LPFC_SLI_REV4)
769 		return;
770 	if (!ndlp) {
771 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
772 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
773 	}
774 	spin_lock_irqsave(&phba->hbalock, iflags);
775 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list)
776 		if ((rrq->vport == vport) && (!ndlp  || rrq->ndlp == ndlp))
777 			list_move(&rrq->list, &rrq_list);
778 	spin_unlock_irqrestore(&phba->hbalock, iflags);
779 
780 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
781 		list_del(&rrq->list);
782 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
783 	}
784 }
785 
786 /**
787  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
788  * @phba: Pointer to HBA context object.
789  * @ndlp: Targets nodelist pointer for this exchange.
790  * @xritag the xri in the bitmap to test.
791  *
792  * This function is called with hbalock held. This function
793  * returns 0 = rrq not active for this xri
794  *         1 = rrq is valid for this xri.
795  **/
796 int
797 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
798 			uint16_t  xritag)
799 {
800 	if (!ndlp)
801 		return 0;
802 	if (!ndlp->active_rrqs_xri_bitmap)
803 		return 0;
804 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
805 			return 1;
806 	else
807 		return 0;
808 }
809 
810 /**
811  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
812  * @phba: Pointer to HBA context object.
813  * @ndlp: nodelist pointer for this target.
814  * @xritag: xri used in this exchange.
815  * @rxid: Remote Exchange ID.
816  * @send_rrq: Flag used to determine if we should send rrq els cmd.
817  *
818  * This function takes the hbalock.
819  * The active bit is always set in the active rrq xri_bitmap even
820  * if there is no slot avaiable for the other rrq information.
821  *
822  * returns 0 rrq actived for this xri
823  *         < 0 No memory or invalid ndlp.
824  **/
825 int
826 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
827 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
828 {
829 	unsigned long iflags;
830 	struct lpfc_node_rrq *rrq;
831 	int empty;
832 
833 	if (!ndlp)
834 		return -EINVAL;
835 
836 	if (!phba->cfg_enable_rrq)
837 		return -EINVAL;
838 
839 	spin_lock_irqsave(&phba->hbalock, iflags);
840 	if (phba->pport->load_flag & FC_UNLOADING) {
841 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
842 		goto out;
843 	}
844 
845 	/*
846 	 * set the active bit even if there is no mem available.
847 	 */
848 	if (NLP_CHK_FREE_REQ(ndlp))
849 		goto out;
850 
851 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
852 		goto out;
853 
854 	if (!ndlp->active_rrqs_xri_bitmap)
855 		goto out;
856 
857 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
858 		goto out;
859 
860 	spin_unlock_irqrestore(&phba->hbalock, iflags);
861 	rrq = mempool_alloc(phba->rrq_pool, GFP_KERNEL);
862 	if (!rrq) {
863 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
864 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
865 				" DID:0x%x Send:%d\n",
866 				xritag, rxid, ndlp->nlp_DID, send_rrq);
867 		return -EINVAL;
868 	}
869 	if (phba->cfg_enable_rrq == 1)
870 		rrq->send_rrq = send_rrq;
871 	else
872 		rrq->send_rrq = 0;
873 	rrq->xritag = xritag;
874 	rrq->rrq_stop_time = jiffies +
875 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
876 	rrq->ndlp = ndlp;
877 	rrq->nlp_DID = ndlp->nlp_DID;
878 	rrq->vport = ndlp->vport;
879 	rrq->rxid = rxid;
880 	spin_lock_irqsave(&phba->hbalock, iflags);
881 	empty = list_empty(&phba->active_rrq_list);
882 	list_add_tail(&rrq->list, &phba->active_rrq_list);
883 	phba->hba_flag |= HBA_RRQ_ACTIVE;
884 	if (empty)
885 		lpfc_worker_wake_up(phba);
886 	spin_unlock_irqrestore(&phba->hbalock, iflags);
887 	return 0;
888 out:
889 	spin_unlock_irqrestore(&phba->hbalock, iflags);
890 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
891 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
892 			" DID:0x%x Send:%d\n",
893 			xritag, rxid, ndlp->nlp_DID, send_rrq);
894 	return -EINVAL;
895 }
896 
897 /**
898  * __lpfc_sli_get_sglq - Allocates an iocb object from sgl pool
899  * @phba: Pointer to HBA context object.
900  * @piocb: Pointer to the iocbq.
901  *
902  * This function is called with the ring lock held. This function
903  * gets a new driver sglq object from the sglq list. If the
904  * list is not empty then it is successful, it returns pointer to the newly
905  * allocated sglq object else it returns NULL.
906  **/
907 static struct lpfc_sglq *
908 __lpfc_sli_get_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
909 {
910 	struct list_head *lpfc_sgl_list = &phba->sli4_hba.lpfc_sgl_list;
911 	struct lpfc_sglq *sglq = NULL;
912 	struct lpfc_sglq *start_sglq = NULL;
913 	struct lpfc_scsi_buf *lpfc_cmd;
914 	struct lpfc_nodelist *ndlp;
915 	int found = 0;
916 
917 	if (piocbq->iocb_flag &  LPFC_IO_FCP) {
918 		lpfc_cmd = (struct lpfc_scsi_buf *) piocbq->context1;
919 		ndlp = lpfc_cmd->rdata->pnode;
920 	} else  if ((piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) &&
921 			!(piocbq->iocb_flag & LPFC_IO_LIBDFC)) {
922 		ndlp = piocbq->context_un.ndlp;
923 	} else  if (piocbq->iocb_flag & LPFC_IO_LIBDFC) {
924 		if (piocbq->iocb_flag & LPFC_IO_LOOPBACK)
925 			ndlp = NULL;
926 		else
927 			ndlp = piocbq->context_un.ndlp;
928 	} else {
929 		ndlp = piocbq->context1;
930 	}
931 
932 	list_remove_head(lpfc_sgl_list, sglq, struct lpfc_sglq, list);
933 	start_sglq = sglq;
934 	while (!found) {
935 		if (!sglq)
936 			return NULL;
937 		if (lpfc_test_rrq_active(phba, ndlp, sglq->sli4_lxritag)) {
938 			/* This xri has an rrq outstanding for this DID.
939 			 * put it back in the list and get another xri.
940 			 */
941 			list_add_tail(&sglq->list, lpfc_sgl_list);
942 			sglq = NULL;
943 			list_remove_head(lpfc_sgl_list, sglq,
944 						struct lpfc_sglq, list);
945 			if (sglq == start_sglq) {
946 				sglq = NULL;
947 				break;
948 			} else
949 				continue;
950 		}
951 		sglq->ndlp = ndlp;
952 		found = 1;
953 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
954 		sglq->state = SGL_ALLOCATED;
955 	}
956 	return sglq;
957 }
958 
959 /**
960  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
961  * @phba: Pointer to HBA context object.
962  *
963  * This function is called with no lock held. This function
964  * allocates a new driver iocb object from the iocb pool. If the
965  * allocation is successful, it returns pointer to the newly
966  * allocated iocb object else it returns NULL.
967  **/
968 struct lpfc_iocbq *
969 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
970 {
971 	struct lpfc_iocbq * iocbq = NULL;
972 	unsigned long iflags;
973 
974 	spin_lock_irqsave(&phba->hbalock, iflags);
975 	iocbq = __lpfc_sli_get_iocbq(phba);
976 	spin_unlock_irqrestore(&phba->hbalock, iflags);
977 	return iocbq;
978 }
979 
980 /**
981  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
982  * @phba: Pointer to HBA context object.
983  * @iocbq: Pointer to driver iocb object.
984  *
985  * This function is called with hbalock held to release driver
986  * iocb object to the iocb pool. The iotag in the iocb object
987  * does not change for each use of the iocb object. This function
988  * clears all other fields of the iocb object when it is freed.
989  * The sqlq structure that holds the xritag and phys and virtual
990  * mappings for the scatter gather list is retrieved from the
991  * active array of sglq. The get of the sglq pointer also clears
992  * the entry in the array. If the status of the IO indiactes that
993  * this IO was aborted then the sglq entry it put on the
994  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
995  * IO has good status or fails for any other reason then the sglq
996  * entry is added to the free list (lpfc_sgl_list).
997  **/
998 static void
999 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1000 {
1001 	struct lpfc_sglq *sglq;
1002 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1003 	unsigned long iflag = 0;
1004 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
1005 
1006 	if (iocbq->sli4_xritag == NO_XRI)
1007 		sglq = NULL;
1008 	else
1009 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1010 
1011 
1012 	if (sglq)  {
1013 		if ((iocbq->iocb_flag & LPFC_EXCHANGE_BUSY) &&
1014 			(sglq->state != SGL_XRI_ABORTED)) {
1015 			spin_lock_irqsave(&phba->sli4_hba.abts_sgl_list_lock,
1016 					iflag);
1017 			list_add(&sglq->list,
1018 				&phba->sli4_hba.lpfc_abts_els_sgl_list);
1019 			spin_unlock_irqrestore(
1020 				&phba->sli4_hba.abts_sgl_list_lock, iflag);
1021 		} else {
1022 			spin_lock_irqsave(&pring->ring_lock, iflag);
1023 			sglq->state = SGL_FREED;
1024 			sglq->ndlp = NULL;
1025 			list_add_tail(&sglq->list,
1026 				&phba->sli4_hba.lpfc_sgl_list);
1027 			spin_unlock_irqrestore(&pring->ring_lock, iflag);
1028 
1029 			/* Check if TXQ queue needs to be serviced */
1030 			if (!list_empty(&pring->txq))
1031 				lpfc_worker_wake_up(phba);
1032 		}
1033 	}
1034 
1035 
1036 	/*
1037 	 * Clean all volatile data fields, preserve iotag and node struct.
1038 	 */
1039 	memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1040 	iocbq->sli4_lxritag = NO_XRI;
1041 	iocbq->sli4_xritag = NO_XRI;
1042 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1043 }
1044 
1045 
1046 /**
1047  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1048  * @phba: Pointer to HBA context object.
1049  * @iocbq: Pointer to driver iocb object.
1050  *
1051  * This function is called with hbalock held to release driver
1052  * iocb object to the iocb pool. The iotag in the iocb object
1053  * does not change for each use of the iocb object. This function
1054  * clears all other fields of the iocb object when it is freed.
1055  **/
1056 static void
1057 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1058 {
1059 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1060 
1061 
1062 	/*
1063 	 * Clean all volatile data fields, preserve iotag and node struct.
1064 	 */
1065 	memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1066 	iocbq->sli4_xritag = NO_XRI;
1067 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1068 }
1069 
1070 /**
1071  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1072  * @phba: Pointer to HBA context object.
1073  * @iocbq: Pointer to driver iocb object.
1074  *
1075  * This function is called with hbalock held to release driver
1076  * iocb object to the iocb pool. The iotag in the iocb object
1077  * does not change for each use of the iocb object. This function
1078  * clears all other fields of the iocb object when it is freed.
1079  **/
1080 static void
1081 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1082 {
1083 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1084 	phba->iocb_cnt--;
1085 }
1086 
1087 /**
1088  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1089  * @phba: Pointer to HBA context object.
1090  * @iocbq: Pointer to driver iocb object.
1091  *
1092  * This function is called with no lock held to release the iocb to
1093  * iocb pool.
1094  **/
1095 void
1096 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1097 {
1098 	unsigned long iflags;
1099 
1100 	/*
1101 	 * Clean all volatile data fields, preserve iotag and node struct.
1102 	 */
1103 	spin_lock_irqsave(&phba->hbalock, iflags);
1104 	__lpfc_sli_release_iocbq(phba, iocbq);
1105 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1106 }
1107 
1108 /**
1109  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1110  * @phba: Pointer to HBA context object.
1111  * @iocblist: List of IOCBs.
1112  * @ulpstatus: ULP status in IOCB command field.
1113  * @ulpWord4: ULP word-4 in IOCB command field.
1114  *
1115  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1116  * on the list by invoking the complete callback function associated with the
1117  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1118  * fields.
1119  **/
1120 void
1121 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1122 		      uint32_t ulpstatus, uint32_t ulpWord4)
1123 {
1124 	struct lpfc_iocbq *piocb;
1125 
1126 	while (!list_empty(iocblist)) {
1127 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1128 		if (!piocb->iocb_cmpl)
1129 			lpfc_sli_release_iocbq(phba, piocb);
1130 		else {
1131 			piocb->iocb.ulpStatus = ulpstatus;
1132 			piocb->iocb.un.ulpWord[4] = ulpWord4;
1133 			(piocb->iocb_cmpl) (phba, piocb, piocb);
1134 		}
1135 	}
1136 	return;
1137 }
1138 
1139 /**
1140  * lpfc_sli_iocb_cmd_type - Get the iocb type
1141  * @iocb_cmnd: iocb command code.
1142  *
1143  * This function is called by ring event handler function to get the iocb type.
1144  * This function translates the iocb command to an iocb command type used to
1145  * decide the final disposition of each completed IOCB.
1146  * The function returns
1147  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1148  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1149  * LPFC_ABORT_IOCB   if it is an abort iocb
1150  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1151  *
1152  * The caller is not required to hold any lock.
1153  **/
1154 static lpfc_iocb_type
1155 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1156 {
1157 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1158 
1159 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1160 		return 0;
1161 
1162 	switch (iocb_cmnd) {
1163 	case CMD_XMIT_SEQUENCE_CR:
1164 	case CMD_XMIT_SEQUENCE_CX:
1165 	case CMD_XMIT_BCAST_CN:
1166 	case CMD_XMIT_BCAST_CX:
1167 	case CMD_ELS_REQUEST_CR:
1168 	case CMD_ELS_REQUEST_CX:
1169 	case CMD_CREATE_XRI_CR:
1170 	case CMD_CREATE_XRI_CX:
1171 	case CMD_GET_RPI_CN:
1172 	case CMD_XMIT_ELS_RSP_CX:
1173 	case CMD_GET_RPI_CR:
1174 	case CMD_FCP_IWRITE_CR:
1175 	case CMD_FCP_IWRITE_CX:
1176 	case CMD_FCP_IREAD_CR:
1177 	case CMD_FCP_IREAD_CX:
1178 	case CMD_FCP_ICMND_CR:
1179 	case CMD_FCP_ICMND_CX:
1180 	case CMD_FCP_TSEND_CX:
1181 	case CMD_FCP_TRSP_CX:
1182 	case CMD_FCP_TRECEIVE_CX:
1183 	case CMD_FCP_AUTO_TRSP_CX:
1184 	case CMD_ADAPTER_MSG:
1185 	case CMD_ADAPTER_DUMP:
1186 	case CMD_XMIT_SEQUENCE64_CR:
1187 	case CMD_XMIT_SEQUENCE64_CX:
1188 	case CMD_XMIT_BCAST64_CN:
1189 	case CMD_XMIT_BCAST64_CX:
1190 	case CMD_ELS_REQUEST64_CR:
1191 	case CMD_ELS_REQUEST64_CX:
1192 	case CMD_FCP_IWRITE64_CR:
1193 	case CMD_FCP_IWRITE64_CX:
1194 	case CMD_FCP_IREAD64_CR:
1195 	case CMD_FCP_IREAD64_CX:
1196 	case CMD_FCP_ICMND64_CR:
1197 	case CMD_FCP_ICMND64_CX:
1198 	case CMD_FCP_TSEND64_CX:
1199 	case CMD_FCP_TRSP64_CX:
1200 	case CMD_FCP_TRECEIVE64_CX:
1201 	case CMD_GEN_REQUEST64_CR:
1202 	case CMD_GEN_REQUEST64_CX:
1203 	case CMD_XMIT_ELS_RSP64_CX:
1204 	case DSSCMD_IWRITE64_CR:
1205 	case DSSCMD_IWRITE64_CX:
1206 	case DSSCMD_IREAD64_CR:
1207 	case DSSCMD_IREAD64_CX:
1208 		type = LPFC_SOL_IOCB;
1209 		break;
1210 	case CMD_ABORT_XRI_CN:
1211 	case CMD_ABORT_XRI_CX:
1212 	case CMD_CLOSE_XRI_CN:
1213 	case CMD_CLOSE_XRI_CX:
1214 	case CMD_XRI_ABORTED_CX:
1215 	case CMD_ABORT_MXRI64_CN:
1216 	case CMD_XMIT_BLS_RSP64_CX:
1217 		type = LPFC_ABORT_IOCB;
1218 		break;
1219 	case CMD_RCV_SEQUENCE_CX:
1220 	case CMD_RCV_ELS_REQ_CX:
1221 	case CMD_RCV_SEQUENCE64_CX:
1222 	case CMD_RCV_ELS_REQ64_CX:
1223 	case CMD_ASYNC_STATUS:
1224 	case CMD_IOCB_RCV_SEQ64_CX:
1225 	case CMD_IOCB_RCV_ELS64_CX:
1226 	case CMD_IOCB_RCV_CONT64_CX:
1227 	case CMD_IOCB_RET_XRI64_CX:
1228 		type = LPFC_UNSOL_IOCB;
1229 		break;
1230 	case CMD_IOCB_XMIT_MSEQ64_CR:
1231 	case CMD_IOCB_XMIT_MSEQ64_CX:
1232 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1233 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1234 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1235 	case CMD_IOCB_ABORT_EXTENDED_CN:
1236 	case CMD_IOCB_RET_HBQE64_CN:
1237 	case CMD_IOCB_FCP_IBIDIR64_CR:
1238 	case CMD_IOCB_FCP_IBIDIR64_CX:
1239 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1240 	case CMD_IOCB_LOGENTRY_CN:
1241 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1242 		printk("%s - Unhandled SLI-3 Command x%x\n",
1243 				__func__, iocb_cmnd);
1244 		type = LPFC_UNKNOWN_IOCB;
1245 		break;
1246 	default:
1247 		type = LPFC_UNKNOWN_IOCB;
1248 		break;
1249 	}
1250 
1251 	return type;
1252 }
1253 
1254 /**
1255  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1256  * @phba: Pointer to HBA context object.
1257  *
1258  * This function is called from SLI initialization code
1259  * to configure every ring of the HBA's SLI interface. The
1260  * caller is not required to hold any lock. This function issues
1261  * a config_ring mailbox command for each ring.
1262  * This function returns zero if successful else returns a negative
1263  * error code.
1264  **/
1265 static int
1266 lpfc_sli_ring_map(struct lpfc_hba *phba)
1267 {
1268 	struct lpfc_sli *psli = &phba->sli;
1269 	LPFC_MBOXQ_t *pmb;
1270 	MAILBOX_t *pmbox;
1271 	int i, rc, ret = 0;
1272 
1273 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1274 	if (!pmb)
1275 		return -ENOMEM;
1276 	pmbox = &pmb->u.mb;
1277 	phba->link_state = LPFC_INIT_MBX_CMDS;
1278 	for (i = 0; i < psli->num_rings; i++) {
1279 		lpfc_config_ring(phba, i, pmb);
1280 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1281 		if (rc != MBX_SUCCESS) {
1282 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1283 					"0446 Adapter failed to init (%d), "
1284 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1285 					"ring %d\n",
1286 					rc, pmbox->mbxCommand,
1287 					pmbox->mbxStatus, i);
1288 			phba->link_state = LPFC_HBA_ERROR;
1289 			ret = -ENXIO;
1290 			break;
1291 		}
1292 	}
1293 	mempool_free(pmb, phba->mbox_mem_pool);
1294 	return ret;
1295 }
1296 
1297 /**
1298  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1299  * @phba: Pointer to HBA context object.
1300  * @pring: Pointer to driver SLI ring object.
1301  * @piocb: Pointer to the driver iocb object.
1302  *
1303  * This function is called with hbalock held. The function adds the
1304  * new iocb to txcmplq of the given ring. This function always returns
1305  * 0. If this function is called for ELS ring, this function checks if
1306  * there is a vport associated with the ELS command. This function also
1307  * starts els_tmofunc timer if this is an ELS command.
1308  **/
1309 static int
1310 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1311 			struct lpfc_iocbq *piocb)
1312 {
1313 	list_add_tail(&piocb->list, &pring->txcmplq);
1314 	piocb->iocb_flag |= LPFC_IO_ON_TXCMPLQ;
1315 
1316 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1317 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
1318 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN) &&
1319 	 (!(piocb->vport->load_flag & FC_UNLOADING))) {
1320 		if (!piocb->vport)
1321 			BUG();
1322 		else
1323 			mod_timer(&piocb->vport->els_tmofunc,
1324 				jiffies +
1325 				msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1326 	}
1327 
1328 
1329 	return 0;
1330 }
1331 
1332 /**
1333  * lpfc_sli_ringtx_get - Get first element of the txq
1334  * @phba: Pointer to HBA context object.
1335  * @pring: Pointer to driver SLI ring object.
1336  *
1337  * This function is called with hbalock held to get next
1338  * iocb in txq of the given ring. If there is any iocb in
1339  * the txq, the function returns first iocb in the list after
1340  * removing the iocb from the list, else it returns NULL.
1341  **/
1342 struct lpfc_iocbq *
1343 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1344 {
1345 	struct lpfc_iocbq *cmd_iocb;
1346 
1347 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1348 	return cmd_iocb;
1349 }
1350 
1351 /**
1352  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
1353  * @phba: Pointer to HBA context object.
1354  * @pring: Pointer to driver SLI ring object.
1355  *
1356  * This function is called with hbalock held and the caller must post the
1357  * iocb without releasing the lock. If the caller releases the lock,
1358  * iocb slot returned by the function is not guaranteed to be available.
1359  * The function returns pointer to the next available iocb slot if there
1360  * is available slot in the ring, else it returns NULL.
1361  * If the get index of the ring is ahead of the put index, the function
1362  * will post an error attention event to the worker thread to take the
1363  * HBA to offline state.
1364  **/
1365 static IOCB_t *
1366 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1367 {
1368 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
1369 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
1370 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
1371 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
1372 		pring->sli.sli3.next_cmdidx = 0;
1373 
1374 	if (unlikely(pring->sli.sli3.local_getidx ==
1375 		pring->sli.sli3.next_cmdidx)) {
1376 
1377 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
1378 
1379 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
1380 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1381 					"0315 Ring %d issue: portCmdGet %d "
1382 					"is bigger than cmd ring %d\n",
1383 					pring->ringno,
1384 					pring->sli.sli3.local_getidx,
1385 					max_cmd_idx);
1386 
1387 			phba->link_state = LPFC_HBA_ERROR;
1388 			/*
1389 			 * All error attention handlers are posted to
1390 			 * worker thread
1391 			 */
1392 			phba->work_ha |= HA_ERATT;
1393 			phba->work_hs = HS_FFER3;
1394 
1395 			lpfc_worker_wake_up(phba);
1396 
1397 			return NULL;
1398 		}
1399 
1400 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
1401 			return NULL;
1402 	}
1403 
1404 	return lpfc_cmd_iocb(phba, pring);
1405 }
1406 
1407 /**
1408  * lpfc_sli_next_iotag - Get an iotag for the iocb
1409  * @phba: Pointer to HBA context object.
1410  * @iocbq: Pointer to driver iocb object.
1411  *
1412  * This function gets an iotag for the iocb. If there is no unused iotag and
1413  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
1414  * array and assigns a new iotag.
1415  * The function returns the allocated iotag if successful, else returns zero.
1416  * Zero is not a valid iotag.
1417  * The caller is not required to hold any lock.
1418  **/
1419 uint16_t
1420 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1421 {
1422 	struct lpfc_iocbq **new_arr;
1423 	struct lpfc_iocbq **old_arr;
1424 	size_t new_len;
1425 	struct lpfc_sli *psli = &phba->sli;
1426 	uint16_t iotag;
1427 
1428 	spin_lock_irq(&phba->hbalock);
1429 	iotag = psli->last_iotag;
1430 	if(++iotag < psli->iocbq_lookup_len) {
1431 		psli->last_iotag = iotag;
1432 		psli->iocbq_lookup[iotag] = iocbq;
1433 		spin_unlock_irq(&phba->hbalock);
1434 		iocbq->iotag = iotag;
1435 		return iotag;
1436 	} else if (psli->iocbq_lookup_len < (0xffff
1437 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
1438 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
1439 		spin_unlock_irq(&phba->hbalock);
1440 		new_arr = kzalloc(new_len * sizeof (struct lpfc_iocbq *),
1441 				  GFP_KERNEL);
1442 		if (new_arr) {
1443 			spin_lock_irq(&phba->hbalock);
1444 			old_arr = psli->iocbq_lookup;
1445 			if (new_len <= psli->iocbq_lookup_len) {
1446 				/* highly unprobable case */
1447 				kfree(new_arr);
1448 				iotag = psli->last_iotag;
1449 				if(++iotag < psli->iocbq_lookup_len) {
1450 					psli->last_iotag = iotag;
1451 					psli->iocbq_lookup[iotag] = iocbq;
1452 					spin_unlock_irq(&phba->hbalock);
1453 					iocbq->iotag = iotag;
1454 					return iotag;
1455 				}
1456 				spin_unlock_irq(&phba->hbalock);
1457 				return 0;
1458 			}
1459 			if (psli->iocbq_lookup)
1460 				memcpy(new_arr, old_arr,
1461 				       ((psli->last_iotag  + 1) *
1462 					sizeof (struct lpfc_iocbq *)));
1463 			psli->iocbq_lookup = new_arr;
1464 			psli->iocbq_lookup_len = new_len;
1465 			psli->last_iotag = iotag;
1466 			psli->iocbq_lookup[iotag] = iocbq;
1467 			spin_unlock_irq(&phba->hbalock);
1468 			iocbq->iotag = iotag;
1469 			kfree(old_arr);
1470 			return iotag;
1471 		}
1472 	} else
1473 		spin_unlock_irq(&phba->hbalock);
1474 
1475 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
1476 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
1477 			psli->last_iotag);
1478 
1479 	return 0;
1480 }
1481 
1482 /**
1483  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
1484  * @phba: Pointer to HBA context object.
1485  * @pring: Pointer to driver SLI ring object.
1486  * @iocb: Pointer to iocb slot in the ring.
1487  * @nextiocb: Pointer to driver iocb object which need to be
1488  *            posted to firmware.
1489  *
1490  * This function is called with hbalock held to post a new iocb to
1491  * the firmware. This function copies the new iocb to ring iocb slot and
1492  * updates the ring pointers. It adds the new iocb to txcmplq if there is
1493  * a completion call back for this iocb else the function will free the
1494  * iocb object.
1495  **/
1496 static void
1497 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1498 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
1499 {
1500 	/*
1501 	 * Set up an iotag
1502 	 */
1503 	nextiocb->iocb.ulpIoTag = (nextiocb->iocb_cmpl) ? nextiocb->iotag : 0;
1504 
1505 
1506 	if (pring->ringno == LPFC_ELS_RING) {
1507 		lpfc_debugfs_slow_ring_trc(phba,
1508 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
1509 			*(((uint32_t *) &nextiocb->iocb) + 4),
1510 			*(((uint32_t *) &nextiocb->iocb) + 6),
1511 			*(((uint32_t *) &nextiocb->iocb) + 7));
1512 	}
1513 
1514 	/*
1515 	 * Issue iocb command to adapter
1516 	 */
1517 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
1518 	wmb();
1519 	pring->stats.iocb_cmd++;
1520 
1521 	/*
1522 	 * If there is no completion routine to call, we can release the
1523 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
1524 	 * that have no rsp ring completion, iocb_cmpl MUST be NULL.
1525 	 */
1526 	if (nextiocb->iocb_cmpl)
1527 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
1528 	else
1529 		__lpfc_sli_release_iocbq(phba, nextiocb);
1530 
1531 	/*
1532 	 * Let the HBA know what IOCB slot will be the next one the
1533 	 * driver will put a command into.
1534 	 */
1535 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
1536 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
1537 }
1538 
1539 /**
1540  * lpfc_sli_update_full_ring - Update the chip attention register
1541  * @phba: Pointer to HBA context object.
1542  * @pring: Pointer to driver SLI ring object.
1543  *
1544  * The caller is not required to hold any lock for calling this function.
1545  * This function updates the chip attention bits for the ring to inform firmware
1546  * that there are pending work to be done for this ring and requests an
1547  * interrupt when there is space available in the ring. This function is
1548  * called when the driver is unable to post more iocbs to the ring due
1549  * to unavailability of space in the ring.
1550  **/
1551 static void
1552 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1553 {
1554 	int ringno = pring->ringno;
1555 
1556 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
1557 
1558 	wmb();
1559 
1560 	/*
1561 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
1562 	 * The HBA will tell us when an IOCB entry is available.
1563 	 */
1564 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
1565 	readl(phba->CAregaddr); /* flush */
1566 
1567 	pring->stats.iocb_cmd_full++;
1568 }
1569 
1570 /**
1571  * lpfc_sli_update_ring - Update chip attention register
1572  * @phba: Pointer to HBA context object.
1573  * @pring: Pointer to driver SLI ring object.
1574  *
1575  * This function updates the chip attention register bit for the
1576  * given ring to inform HBA that there is more work to be done
1577  * in this ring. The caller is not required to hold any lock.
1578  **/
1579 static void
1580 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1581 {
1582 	int ringno = pring->ringno;
1583 
1584 	/*
1585 	 * Tell the HBA that there is work to do in this ring.
1586 	 */
1587 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
1588 		wmb();
1589 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
1590 		readl(phba->CAregaddr); /* flush */
1591 	}
1592 }
1593 
1594 /**
1595  * lpfc_sli_resume_iocb - Process iocbs in the txq
1596  * @phba: Pointer to HBA context object.
1597  * @pring: Pointer to driver SLI ring object.
1598  *
1599  * This function is called with hbalock held to post pending iocbs
1600  * in the txq to the firmware. This function is called when driver
1601  * detects space available in the ring.
1602  **/
1603 static void
1604 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1605 {
1606 	IOCB_t *iocb;
1607 	struct lpfc_iocbq *nextiocb;
1608 
1609 	/*
1610 	 * Check to see if:
1611 	 *  (a) there is anything on the txq to send
1612 	 *  (b) link is up
1613 	 *  (c) link attention events can be processed (fcp ring only)
1614 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
1615 	 */
1616 
1617 	if (lpfc_is_link_up(phba) &&
1618 	    (!list_empty(&pring->txq)) &&
1619 	    (pring->ringno != phba->sli.fcp_ring ||
1620 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
1621 
1622 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
1623 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
1624 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
1625 
1626 		if (iocb)
1627 			lpfc_sli_update_ring(phba, pring);
1628 		else
1629 			lpfc_sli_update_full_ring(phba, pring);
1630 	}
1631 
1632 	return;
1633 }
1634 
1635 /**
1636  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
1637  * @phba: Pointer to HBA context object.
1638  * @hbqno: HBQ number.
1639  *
1640  * This function is called with hbalock held to get the next
1641  * available slot for the given HBQ. If there is free slot
1642  * available for the HBQ it will return pointer to the next available
1643  * HBQ entry else it will return NULL.
1644  **/
1645 static struct lpfc_hbq_entry *
1646 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
1647 {
1648 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
1649 
1650 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
1651 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
1652 		hbqp->next_hbqPutIdx = 0;
1653 
1654 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
1655 		uint32_t raw_index = phba->hbq_get[hbqno];
1656 		uint32_t getidx = le32_to_cpu(raw_index);
1657 
1658 		hbqp->local_hbqGetIdx = getidx;
1659 
1660 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
1661 			lpfc_printf_log(phba, KERN_ERR,
1662 					LOG_SLI | LOG_VPORT,
1663 					"1802 HBQ %d: local_hbqGetIdx "
1664 					"%u is > than hbqp->entry_count %u\n",
1665 					hbqno, hbqp->local_hbqGetIdx,
1666 					hbqp->entry_count);
1667 
1668 			phba->link_state = LPFC_HBA_ERROR;
1669 			return NULL;
1670 		}
1671 
1672 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
1673 			return NULL;
1674 	}
1675 
1676 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
1677 			hbqp->hbqPutIdx;
1678 }
1679 
1680 /**
1681  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
1682  * @phba: Pointer to HBA context object.
1683  *
1684  * This function is called with no lock held to free all the
1685  * hbq buffers while uninitializing the SLI interface. It also
1686  * frees the HBQ buffers returned by the firmware but not yet
1687  * processed by the upper layers.
1688  **/
1689 void
1690 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
1691 {
1692 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
1693 	struct hbq_dmabuf *hbq_buf;
1694 	unsigned long flags;
1695 	int i, hbq_count;
1696 	uint32_t hbqno;
1697 
1698 	hbq_count = lpfc_sli_hbq_count();
1699 	/* Return all memory used by all HBQs */
1700 	spin_lock_irqsave(&phba->hbalock, flags);
1701 	for (i = 0; i < hbq_count; ++i) {
1702 		list_for_each_entry_safe(dmabuf, next_dmabuf,
1703 				&phba->hbqs[i].hbq_buffer_list, list) {
1704 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
1705 			list_del(&hbq_buf->dbuf.list);
1706 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
1707 		}
1708 		phba->hbqs[i].buffer_count = 0;
1709 	}
1710 	/* Return all HBQ buffer that are in-fly */
1711 	list_for_each_entry_safe(dmabuf, next_dmabuf, &phba->rb_pend_list,
1712 				 list) {
1713 		hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
1714 		list_del(&hbq_buf->dbuf.list);
1715 		if (hbq_buf->tag == -1) {
1716 			(phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer)
1717 				(phba, hbq_buf);
1718 		} else {
1719 			hbqno = hbq_buf->tag >> 16;
1720 			if (hbqno >= LPFC_MAX_HBQS)
1721 				(phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer)
1722 					(phba, hbq_buf);
1723 			else
1724 				(phba->hbqs[hbqno].hbq_free_buffer)(phba,
1725 					hbq_buf);
1726 		}
1727 	}
1728 
1729 	/* Mark the HBQs not in use */
1730 	phba->hbq_in_use = 0;
1731 	spin_unlock_irqrestore(&phba->hbalock, flags);
1732 }
1733 
1734 /**
1735  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
1736  * @phba: Pointer to HBA context object.
1737  * @hbqno: HBQ number.
1738  * @hbq_buf: Pointer to HBQ buffer.
1739  *
1740  * This function is called with the hbalock held to post a
1741  * hbq buffer to the firmware. If the function finds an empty
1742  * slot in the HBQ, it will post the buffer. The function will return
1743  * pointer to the hbq entry if it successfully post the buffer
1744  * else it will return NULL.
1745  **/
1746 static int
1747 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
1748 			 struct hbq_dmabuf *hbq_buf)
1749 {
1750 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
1751 }
1752 
1753 /**
1754  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
1755  * @phba: Pointer to HBA context object.
1756  * @hbqno: HBQ number.
1757  * @hbq_buf: Pointer to HBQ buffer.
1758  *
1759  * This function is called with the hbalock held to post a hbq buffer to the
1760  * firmware. If the function finds an empty slot in the HBQ, it will post the
1761  * buffer and place it on the hbq_buffer_list. The function will return zero if
1762  * it successfully post the buffer else it will return an error.
1763  **/
1764 static int
1765 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
1766 			    struct hbq_dmabuf *hbq_buf)
1767 {
1768 	struct lpfc_hbq_entry *hbqe;
1769 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
1770 
1771 	/* Get next HBQ entry slot to use */
1772 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
1773 	if (hbqe) {
1774 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
1775 
1776 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
1777 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
1778 		hbqe->bde.tus.f.bdeSize = hbq_buf->size;
1779 		hbqe->bde.tus.f.bdeFlags = 0;
1780 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
1781 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
1782 				/* Sync SLIM */
1783 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
1784 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
1785 				/* flush */
1786 		readl(phba->hbq_put + hbqno);
1787 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
1788 		return 0;
1789 	} else
1790 		return -ENOMEM;
1791 }
1792 
1793 /**
1794  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
1795  * @phba: Pointer to HBA context object.
1796  * @hbqno: HBQ number.
1797  * @hbq_buf: Pointer to HBQ buffer.
1798  *
1799  * This function is called with the hbalock held to post an RQE to the SLI4
1800  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
1801  * the hbq_buffer_list and return zero, otherwise it will return an error.
1802  **/
1803 static int
1804 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
1805 			    struct hbq_dmabuf *hbq_buf)
1806 {
1807 	int rc;
1808 	struct lpfc_rqe hrqe;
1809 	struct lpfc_rqe drqe;
1810 
1811 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
1812 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
1813 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
1814 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
1815 	rc = lpfc_sli4_rq_put(phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
1816 			      &hrqe, &drqe);
1817 	if (rc < 0)
1818 		return rc;
1819 	hbq_buf->tag = rc;
1820 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
1821 	return 0;
1822 }
1823 
1824 /* HBQ for ELS and CT traffic. */
1825 static struct lpfc_hbq_init lpfc_els_hbq = {
1826 	.rn = 1,
1827 	.entry_count = 256,
1828 	.mask_count = 0,
1829 	.profile = 0,
1830 	.ring_mask = (1 << LPFC_ELS_RING),
1831 	.buffer_count = 0,
1832 	.init_count = 40,
1833 	.add_count = 40,
1834 };
1835 
1836 /* HBQ for the extra ring if needed */
1837 static struct lpfc_hbq_init lpfc_extra_hbq = {
1838 	.rn = 1,
1839 	.entry_count = 200,
1840 	.mask_count = 0,
1841 	.profile = 0,
1842 	.ring_mask = (1 << LPFC_EXTRA_RING),
1843 	.buffer_count = 0,
1844 	.init_count = 0,
1845 	.add_count = 5,
1846 };
1847 
1848 /* Array of HBQs */
1849 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
1850 	&lpfc_els_hbq,
1851 	&lpfc_extra_hbq,
1852 };
1853 
1854 /**
1855  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
1856  * @phba: Pointer to HBA context object.
1857  * @hbqno: HBQ number.
1858  * @count: Number of HBQ buffers to be posted.
1859  *
1860  * This function is called with no lock held to post more hbq buffers to the
1861  * given HBQ. The function returns the number of HBQ buffers successfully
1862  * posted.
1863  **/
1864 static int
1865 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
1866 {
1867 	uint32_t i, posted = 0;
1868 	unsigned long flags;
1869 	struct hbq_dmabuf *hbq_buffer;
1870 	LIST_HEAD(hbq_buf_list);
1871 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
1872 		return 0;
1873 
1874 	if ((phba->hbqs[hbqno].buffer_count + count) >
1875 	    lpfc_hbq_defs[hbqno]->entry_count)
1876 		count = lpfc_hbq_defs[hbqno]->entry_count -
1877 					phba->hbqs[hbqno].buffer_count;
1878 	if (!count)
1879 		return 0;
1880 	/* Allocate HBQ entries */
1881 	for (i = 0; i < count; i++) {
1882 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
1883 		if (!hbq_buffer)
1884 			break;
1885 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
1886 	}
1887 	/* Check whether HBQ is still in use */
1888 	spin_lock_irqsave(&phba->hbalock, flags);
1889 	if (!phba->hbq_in_use)
1890 		goto err;
1891 	while (!list_empty(&hbq_buf_list)) {
1892 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
1893 				 dbuf.list);
1894 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
1895 				      (hbqno << 16));
1896 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
1897 			phba->hbqs[hbqno].buffer_count++;
1898 			posted++;
1899 		} else
1900 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
1901 	}
1902 	spin_unlock_irqrestore(&phba->hbalock, flags);
1903 	return posted;
1904 err:
1905 	spin_unlock_irqrestore(&phba->hbalock, flags);
1906 	while (!list_empty(&hbq_buf_list)) {
1907 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
1908 				 dbuf.list);
1909 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
1910 	}
1911 	return 0;
1912 }
1913 
1914 /**
1915  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
1916  * @phba: Pointer to HBA context object.
1917  * @qno: HBQ number.
1918  *
1919  * This function posts more buffers to the HBQ. This function
1920  * is called with no lock held. The function returns the number of HBQ entries
1921  * successfully allocated.
1922  **/
1923 int
1924 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
1925 {
1926 	if (phba->sli_rev == LPFC_SLI_REV4)
1927 		return 0;
1928 	else
1929 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
1930 					 lpfc_hbq_defs[qno]->add_count);
1931 }
1932 
1933 /**
1934  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
1935  * @phba: Pointer to HBA context object.
1936  * @qno:  HBQ queue number.
1937  *
1938  * This function is called from SLI initialization code path with
1939  * no lock held to post initial HBQ buffers to firmware. The
1940  * function returns the number of HBQ entries successfully allocated.
1941  **/
1942 static int
1943 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
1944 {
1945 	if (phba->sli_rev == LPFC_SLI_REV4)
1946 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
1947 					lpfc_hbq_defs[qno]->entry_count);
1948 	else
1949 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
1950 					 lpfc_hbq_defs[qno]->init_count);
1951 }
1952 
1953 /**
1954  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
1955  * @phba: Pointer to HBA context object.
1956  * @hbqno: HBQ number.
1957  *
1958  * This function removes the first hbq buffer on an hbq list and returns a
1959  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
1960  **/
1961 static struct hbq_dmabuf *
1962 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
1963 {
1964 	struct lpfc_dmabuf *d_buf;
1965 
1966 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
1967 	if (!d_buf)
1968 		return NULL;
1969 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
1970 }
1971 
1972 /**
1973  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
1974  * @phba: Pointer to HBA context object.
1975  * @tag: Tag of the hbq buffer.
1976  *
1977  * This function is called with hbalock held. This function searches
1978  * for the hbq buffer associated with the given tag in the hbq buffer
1979  * list. If it finds the hbq buffer, it returns the hbq_buffer other wise
1980  * it returns NULL.
1981  **/
1982 static struct hbq_dmabuf *
1983 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
1984 {
1985 	struct lpfc_dmabuf *d_buf;
1986 	struct hbq_dmabuf *hbq_buf;
1987 	uint32_t hbqno;
1988 
1989 	hbqno = tag >> 16;
1990 	if (hbqno >= LPFC_MAX_HBQS)
1991 		return NULL;
1992 
1993 	spin_lock_irq(&phba->hbalock);
1994 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
1995 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
1996 		if (hbq_buf->tag == tag) {
1997 			spin_unlock_irq(&phba->hbalock);
1998 			return hbq_buf;
1999 		}
2000 	}
2001 	spin_unlock_irq(&phba->hbalock);
2002 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_VPORT,
2003 			"1803 Bad hbq tag. Data: x%x x%x\n",
2004 			tag, phba->hbqs[tag >> 16].buffer_count);
2005 	return NULL;
2006 }
2007 
2008 /**
2009  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2010  * @phba: Pointer to HBA context object.
2011  * @hbq_buffer: Pointer to HBQ buffer.
2012  *
2013  * This function is called with hbalock. This function gives back
2014  * the hbq buffer to firmware. If the HBQ does not have space to
2015  * post the buffer, it will free the buffer.
2016  **/
2017 void
2018 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2019 {
2020 	uint32_t hbqno;
2021 
2022 	if (hbq_buffer) {
2023 		hbqno = hbq_buffer->tag >> 16;
2024 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2025 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2026 	}
2027 }
2028 
2029 /**
2030  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2031  * @mbxCommand: mailbox command code.
2032  *
2033  * This function is called by the mailbox event handler function to verify
2034  * that the completed mailbox command is a legitimate mailbox command. If the
2035  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2036  * and the mailbox event handler will take the HBA offline.
2037  **/
2038 static int
2039 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2040 {
2041 	uint8_t ret;
2042 
2043 	switch (mbxCommand) {
2044 	case MBX_LOAD_SM:
2045 	case MBX_READ_NV:
2046 	case MBX_WRITE_NV:
2047 	case MBX_WRITE_VPARMS:
2048 	case MBX_RUN_BIU_DIAG:
2049 	case MBX_INIT_LINK:
2050 	case MBX_DOWN_LINK:
2051 	case MBX_CONFIG_LINK:
2052 	case MBX_CONFIG_RING:
2053 	case MBX_RESET_RING:
2054 	case MBX_READ_CONFIG:
2055 	case MBX_READ_RCONFIG:
2056 	case MBX_READ_SPARM:
2057 	case MBX_READ_STATUS:
2058 	case MBX_READ_RPI:
2059 	case MBX_READ_XRI:
2060 	case MBX_READ_REV:
2061 	case MBX_READ_LNK_STAT:
2062 	case MBX_REG_LOGIN:
2063 	case MBX_UNREG_LOGIN:
2064 	case MBX_CLEAR_LA:
2065 	case MBX_DUMP_MEMORY:
2066 	case MBX_DUMP_CONTEXT:
2067 	case MBX_RUN_DIAGS:
2068 	case MBX_RESTART:
2069 	case MBX_UPDATE_CFG:
2070 	case MBX_DOWN_LOAD:
2071 	case MBX_DEL_LD_ENTRY:
2072 	case MBX_RUN_PROGRAM:
2073 	case MBX_SET_MASK:
2074 	case MBX_SET_VARIABLE:
2075 	case MBX_UNREG_D_ID:
2076 	case MBX_KILL_BOARD:
2077 	case MBX_CONFIG_FARP:
2078 	case MBX_BEACON:
2079 	case MBX_LOAD_AREA:
2080 	case MBX_RUN_BIU_DIAG64:
2081 	case MBX_CONFIG_PORT:
2082 	case MBX_READ_SPARM64:
2083 	case MBX_READ_RPI64:
2084 	case MBX_REG_LOGIN64:
2085 	case MBX_READ_TOPOLOGY:
2086 	case MBX_WRITE_WWN:
2087 	case MBX_SET_DEBUG:
2088 	case MBX_LOAD_EXP_ROM:
2089 	case MBX_ASYNCEVT_ENABLE:
2090 	case MBX_REG_VPI:
2091 	case MBX_UNREG_VPI:
2092 	case MBX_HEARTBEAT:
2093 	case MBX_PORT_CAPABILITIES:
2094 	case MBX_PORT_IOV_CONTROL:
2095 	case MBX_SLI4_CONFIG:
2096 	case MBX_SLI4_REQ_FTRS:
2097 	case MBX_REG_FCFI:
2098 	case MBX_UNREG_FCFI:
2099 	case MBX_REG_VFI:
2100 	case MBX_UNREG_VFI:
2101 	case MBX_INIT_VPI:
2102 	case MBX_INIT_VFI:
2103 	case MBX_RESUME_RPI:
2104 	case MBX_READ_EVENT_LOG_STATUS:
2105 	case MBX_READ_EVENT_LOG:
2106 	case MBX_SECURITY_MGMT:
2107 	case MBX_AUTH_PORT:
2108 	case MBX_ACCESS_VDATA:
2109 		ret = mbxCommand;
2110 		break;
2111 	default:
2112 		ret = MBX_SHUTDOWN;
2113 		break;
2114 	}
2115 	return ret;
2116 }
2117 
2118 /**
2119  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2120  * @phba: Pointer to HBA context object.
2121  * @pmboxq: Pointer to mailbox command.
2122  *
2123  * This is completion handler function for mailbox commands issued from
2124  * lpfc_sli_issue_mbox_wait function. This function is called by the
2125  * mailbox event handler function with no lock held. This function
2126  * will wake up thread waiting on the wait queue pointed by context1
2127  * of the mailbox.
2128  **/
2129 void
2130 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2131 {
2132 	wait_queue_head_t *pdone_q;
2133 	unsigned long drvr_flag;
2134 
2135 	/*
2136 	 * If pdone_q is empty, the driver thread gave up waiting and
2137 	 * continued running.
2138 	 */
2139 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2140 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2141 	pdone_q = (wait_queue_head_t *) pmboxq->context1;
2142 	if (pdone_q)
2143 		wake_up_interruptible(pdone_q);
2144 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2145 	return;
2146 }
2147 
2148 
2149 /**
2150  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2151  * @phba: Pointer to HBA context object.
2152  * @pmb: Pointer to mailbox object.
2153  *
2154  * This function is the default mailbox completion handler. It
2155  * frees the memory resources associated with the completed mailbox
2156  * command. If the completed command is a REG_LOGIN mailbox command,
2157  * this function will issue a UREG_LOGIN to re-claim the RPI.
2158  **/
2159 void
2160 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2161 {
2162 	struct lpfc_vport  *vport = pmb->vport;
2163 	struct lpfc_dmabuf *mp;
2164 	struct lpfc_nodelist *ndlp;
2165 	struct Scsi_Host *shost;
2166 	uint16_t rpi, vpi;
2167 	int rc;
2168 
2169 	mp = (struct lpfc_dmabuf *) (pmb->context1);
2170 
2171 	if (mp) {
2172 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
2173 		kfree(mp);
2174 	}
2175 
2176 	/*
2177 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2178 	 * is in re-discovery driver need to cleanup the RPI.
2179 	 */
2180 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2181 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2182 	    !pmb->u.mb.mbxStatus) {
2183 		rpi = pmb->u.mb.un.varWords[0];
2184 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2185 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2186 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2187 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2188 		if (rc != MBX_NOT_FINISHED)
2189 			return;
2190 	}
2191 
2192 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2193 		!(phba->pport->load_flag & FC_UNLOADING) &&
2194 		!pmb->u.mb.mbxStatus) {
2195 		shost = lpfc_shost_from_vport(vport);
2196 		spin_lock_irq(shost->host_lock);
2197 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2198 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2199 		spin_unlock_irq(shost->host_lock);
2200 	}
2201 
2202 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2203 		ndlp = (struct lpfc_nodelist *)pmb->context2;
2204 		lpfc_nlp_put(ndlp);
2205 		pmb->context2 = NULL;
2206 	}
2207 
2208 	/* Check security permission status on INIT_LINK mailbox command */
2209 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2210 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2211 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2212 				"2860 SLI authentication is required "
2213 				"for INIT_LINK but has not done yet\n");
2214 
2215 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2216 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2217 	else
2218 		mempool_free(pmb, phba->mbox_mem_pool);
2219 }
2220  /**
2221  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2222  * @phba: Pointer to HBA context object.
2223  * @pmb: Pointer to mailbox object.
2224  *
2225  * This function is the unreg rpi mailbox completion handler. It
2226  * frees the memory resources associated with the completed mailbox
2227  * command. An additional refrenece is put on the ndlp to prevent
2228  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2229  * the unreg mailbox command completes, this routine puts the
2230  * reference back.
2231  *
2232  **/
2233 void
2234 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2235 {
2236 	struct lpfc_vport  *vport = pmb->vport;
2237 	struct lpfc_nodelist *ndlp;
2238 
2239 	ndlp = pmb->context1;
2240 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2241 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2242 		    (bf_get(lpfc_sli_intf_if_type,
2243 		     &phba->sli4_hba.sli_intf) ==
2244 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2245 			if (ndlp) {
2246 				lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
2247 						 "0010 UNREG_LOGIN vpi:%x "
2248 						 "rpi:%x DID:%x map:%x %p\n",
2249 						 vport->vpi, ndlp->nlp_rpi,
2250 						 ndlp->nlp_DID,
2251 						 ndlp->nlp_usg_map, ndlp);
2252 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2253 				lpfc_nlp_put(ndlp);
2254 			}
2255 		}
2256 	}
2257 
2258 	mempool_free(pmb, phba->mbox_mem_pool);
2259 }
2260 
2261 /**
2262  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
2263  * @phba: Pointer to HBA context object.
2264  *
2265  * This function is called with no lock held. This function processes all
2266  * the completed mailbox commands and gives it to upper layers. The interrupt
2267  * service routine processes mailbox completion interrupt and adds completed
2268  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
2269  * Worker thread call lpfc_sli_handle_mb_event, which will return the
2270  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
2271  * function returns the mailbox commands to the upper layer by calling the
2272  * completion handler function of each mailbox.
2273  **/
2274 int
2275 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
2276 {
2277 	MAILBOX_t *pmbox;
2278 	LPFC_MBOXQ_t *pmb;
2279 	int rc;
2280 	LIST_HEAD(cmplq);
2281 
2282 	phba->sli.slistat.mbox_event++;
2283 
2284 	/* Get all completed mailboxe buffers into the cmplq */
2285 	spin_lock_irq(&phba->hbalock);
2286 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
2287 	spin_unlock_irq(&phba->hbalock);
2288 
2289 	/* Get a Mailbox buffer to setup mailbox commands for callback */
2290 	do {
2291 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
2292 		if (pmb == NULL)
2293 			break;
2294 
2295 		pmbox = &pmb->u.mb;
2296 
2297 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
2298 			if (pmb->vport) {
2299 				lpfc_debugfs_disc_trc(pmb->vport,
2300 					LPFC_DISC_TRC_MBOX_VPORT,
2301 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
2302 					(uint32_t)pmbox->mbxCommand,
2303 					pmbox->un.varWords[0],
2304 					pmbox->un.varWords[1]);
2305 			}
2306 			else {
2307 				lpfc_debugfs_disc_trc(phba->pport,
2308 					LPFC_DISC_TRC_MBOX,
2309 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
2310 					(uint32_t)pmbox->mbxCommand,
2311 					pmbox->un.varWords[0],
2312 					pmbox->un.varWords[1]);
2313 			}
2314 		}
2315 
2316 		/*
2317 		 * It is a fatal error if unknown mbox command completion.
2318 		 */
2319 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
2320 		    MBX_SHUTDOWN) {
2321 			/* Unknown mailbox command compl */
2322 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2323 					"(%d):0323 Unknown Mailbox command "
2324 					"x%x (x%x/x%x) Cmpl\n",
2325 					pmb->vport ? pmb->vport->vpi : 0,
2326 					pmbox->mbxCommand,
2327 					lpfc_sli_config_mbox_subsys_get(phba,
2328 									pmb),
2329 					lpfc_sli_config_mbox_opcode_get(phba,
2330 									pmb));
2331 			phba->link_state = LPFC_HBA_ERROR;
2332 			phba->work_hs = HS_FFER3;
2333 			lpfc_handle_eratt(phba);
2334 			continue;
2335 		}
2336 
2337 		if (pmbox->mbxStatus) {
2338 			phba->sli.slistat.mbox_stat_err++;
2339 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
2340 				/* Mbox cmd cmpl error - RETRYing */
2341 				lpfc_printf_log(phba, KERN_INFO,
2342 					LOG_MBOX | LOG_SLI,
2343 					"(%d):0305 Mbox cmd cmpl "
2344 					"error - RETRYing Data: x%x "
2345 					"(x%x/x%x) x%x x%x x%x\n",
2346 					pmb->vport ? pmb->vport->vpi : 0,
2347 					pmbox->mbxCommand,
2348 					lpfc_sli_config_mbox_subsys_get(phba,
2349 									pmb),
2350 					lpfc_sli_config_mbox_opcode_get(phba,
2351 									pmb),
2352 					pmbox->mbxStatus,
2353 					pmbox->un.varWords[0],
2354 					pmb->vport->port_state);
2355 				pmbox->mbxStatus = 0;
2356 				pmbox->mbxOwner = OWN_HOST;
2357 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2358 				if (rc != MBX_NOT_FINISHED)
2359 					continue;
2360 			}
2361 		}
2362 
2363 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
2364 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
2365 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl x%p "
2366 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
2367 				"x%x x%x x%x\n",
2368 				pmb->vport ? pmb->vport->vpi : 0,
2369 				pmbox->mbxCommand,
2370 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
2371 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
2372 				pmb->mbox_cmpl,
2373 				*((uint32_t *) pmbox),
2374 				pmbox->un.varWords[0],
2375 				pmbox->un.varWords[1],
2376 				pmbox->un.varWords[2],
2377 				pmbox->un.varWords[3],
2378 				pmbox->un.varWords[4],
2379 				pmbox->un.varWords[5],
2380 				pmbox->un.varWords[6],
2381 				pmbox->un.varWords[7],
2382 				pmbox->un.varWords[8],
2383 				pmbox->un.varWords[9],
2384 				pmbox->un.varWords[10]);
2385 
2386 		if (pmb->mbox_cmpl)
2387 			pmb->mbox_cmpl(phba,pmb);
2388 	} while (1);
2389 	return 0;
2390 }
2391 
2392 /**
2393  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
2394  * @phba: Pointer to HBA context object.
2395  * @pring: Pointer to driver SLI ring object.
2396  * @tag: buffer tag.
2397  *
2398  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
2399  * is set in the tag the buffer is posted for a particular exchange,
2400  * the function will return the buffer without replacing the buffer.
2401  * If the buffer is for unsolicited ELS or CT traffic, this function
2402  * returns the buffer and also posts another buffer to the firmware.
2403  **/
2404 static struct lpfc_dmabuf *
2405 lpfc_sli_get_buff(struct lpfc_hba *phba,
2406 		  struct lpfc_sli_ring *pring,
2407 		  uint32_t tag)
2408 {
2409 	struct hbq_dmabuf *hbq_entry;
2410 
2411 	if (tag & QUE_BUFTAG_BIT)
2412 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
2413 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
2414 	if (!hbq_entry)
2415 		return NULL;
2416 	return &hbq_entry->dbuf;
2417 }
2418 
2419 /**
2420  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
2421  * @phba: Pointer to HBA context object.
2422  * @pring: Pointer to driver SLI ring object.
2423  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
2424  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
2425  * @fch_type: the type for the first frame of the sequence.
2426  *
2427  * This function is called with no lock held. This function uses the r_ctl and
2428  * type of the received sequence to find the correct callback function to call
2429  * to process the sequence.
2430  **/
2431 static int
2432 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2433 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
2434 			 uint32_t fch_type)
2435 {
2436 	int i;
2437 
2438 	/* unSolicited Responses */
2439 	if (pring->prt[0].profile) {
2440 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
2441 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
2442 									saveq);
2443 		return 1;
2444 	}
2445 	/* We must search, based on rctl / type
2446 	   for the right routine */
2447 	for (i = 0; i < pring->num_mask; i++) {
2448 		if ((pring->prt[i].rctl == fch_r_ctl) &&
2449 		    (pring->prt[i].type == fch_type)) {
2450 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
2451 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
2452 						(phba, pring, saveq);
2453 			return 1;
2454 		}
2455 	}
2456 	return 0;
2457 }
2458 
2459 /**
2460  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
2461  * @phba: Pointer to HBA context object.
2462  * @pring: Pointer to driver SLI ring object.
2463  * @saveq: Pointer to the unsolicited iocb.
2464  *
2465  * This function is called with no lock held by the ring event handler
2466  * when there is an unsolicited iocb posted to the response ring by the
2467  * firmware. This function gets the buffer associated with the iocbs
2468  * and calls the event handler for the ring. This function handles both
2469  * qring buffers and hbq buffers.
2470  * When the function returns 1 the caller can free the iocb object otherwise
2471  * upper layer functions will free the iocb objects.
2472  **/
2473 static int
2474 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2475 			    struct lpfc_iocbq *saveq)
2476 {
2477 	IOCB_t           * irsp;
2478 	WORD5            * w5p;
2479 	uint32_t           Rctl, Type;
2480 	struct lpfc_iocbq *iocbq;
2481 	struct lpfc_dmabuf *dmzbuf;
2482 
2483 	irsp = &(saveq->iocb);
2484 
2485 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
2486 		if (pring->lpfc_sli_rcv_async_status)
2487 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
2488 		else
2489 			lpfc_printf_log(phba,
2490 					KERN_WARNING,
2491 					LOG_SLI,
2492 					"0316 Ring %d handler: unexpected "
2493 					"ASYNC_STATUS iocb received evt_code "
2494 					"0x%x\n",
2495 					pring->ringno,
2496 					irsp->un.asyncstat.evt_code);
2497 		return 1;
2498 	}
2499 
2500 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
2501 		(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
2502 		if (irsp->ulpBdeCount > 0) {
2503 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2504 					irsp->un.ulpWord[3]);
2505 			lpfc_in_buf_free(phba, dmzbuf);
2506 		}
2507 
2508 		if (irsp->ulpBdeCount > 1) {
2509 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2510 					irsp->unsli3.sli3Words[3]);
2511 			lpfc_in_buf_free(phba, dmzbuf);
2512 		}
2513 
2514 		if (irsp->ulpBdeCount > 2) {
2515 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2516 				irsp->unsli3.sli3Words[7]);
2517 			lpfc_in_buf_free(phba, dmzbuf);
2518 		}
2519 
2520 		return 1;
2521 	}
2522 
2523 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
2524 		if (irsp->ulpBdeCount != 0) {
2525 			saveq->context2 = lpfc_sli_get_buff(phba, pring,
2526 						irsp->un.ulpWord[3]);
2527 			if (!saveq->context2)
2528 				lpfc_printf_log(phba,
2529 					KERN_ERR,
2530 					LOG_SLI,
2531 					"0341 Ring %d Cannot find buffer for "
2532 					"an unsolicited iocb. tag 0x%x\n",
2533 					pring->ringno,
2534 					irsp->un.ulpWord[3]);
2535 		}
2536 		if (irsp->ulpBdeCount == 2) {
2537 			saveq->context3 = lpfc_sli_get_buff(phba, pring,
2538 						irsp->unsli3.sli3Words[7]);
2539 			if (!saveq->context3)
2540 				lpfc_printf_log(phba,
2541 					KERN_ERR,
2542 					LOG_SLI,
2543 					"0342 Ring %d Cannot find buffer for an"
2544 					" unsolicited iocb. tag 0x%x\n",
2545 					pring->ringno,
2546 					irsp->unsli3.sli3Words[7]);
2547 		}
2548 		list_for_each_entry(iocbq, &saveq->list, list) {
2549 			irsp = &(iocbq->iocb);
2550 			if (irsp->ulpBdeCount != 0) {
2551 				iocbq->context2 = lpfc_sli_get_buff(phba, pring,
2552 							irsp->un.ulpWord[3]);
2553 				if (!iocbq->context2)
2554 					lpfc_printf_log(phba,
2555 						KERN_ERR,
2556 						LOG_SLI,
2557 						"0343 Ring %d Cannot find "
2558 						"buffer for an unsolicited iocb"
2559 						". tag 0x%x\n", pring->ringno,
2560 						irsp->un.ulpWord[3]);
2561 			}
2562 			if (irsp->ulpBdeCount == 2) {
2563 				iocbq->context3 = lpfc_sli_get_buff(phba, pring,
2564 						irsp->unsli3.sli3Words[7]);
2565 				if (!iocbq->context3)
2566 					lpfc_printf_log(phba,
2567 						KERN_ERR,
2568 						LOG_SLI,
2569 						"0344 Ring %d Cannot find "
2570 						"buffer for an unsolicited "
2571 						"iocb. tag 0x%x\n",
2572 						pring->ringno,
2573 						irsp->unsli3.sli3Words[7]);
2574 			}
2575 		}
2576 	}
2577 	if (irsp->ulpBdeCount != 0 &&
2578 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
2579 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
2580 		int found = 0;
2581 
2582 		/* search continue save q for same XRI */
2583 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
2584 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
2585 				saveq->iocb.unsli3.rcvsli3.ox_id) {
2586 				list_add_tail(&saveq->list, &iocbq->list);
2587 				found = 1;
2588 				break;
2589 			}
2590 		}
2591 		if (!found)
2592 			list_add_tail(&saveq->clist,
2593 				      &pring->iocb_continue_saveq);
2594 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
2595 			list_del_init(&iocbq->clist);
2596 			saveq = iocbq;
2597 			irsp = &(saveq->iocb);
2598 		} else
2599 			return 0;
2600 	}
2601 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
2602 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
2603 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
2604 		Rctl = FC_RCTL_ELS_REQ;
2605 		Type = FC_TYPE_ELS;
2606 	} else {
2607 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
2608 		Rctl = w5p->hcsw.Rctl;
2609 		Type = w5p->hcsw.Type;
2610 
2611 		/* Firmware Workaround */
2612 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
2613 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
2614 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
2615 			Rctl = FC_RCTL_ELS_REQ;
2616 			Type = FC_TYPE_ELS;
2617 			w5p->hcsw.Rctl = Rctl;
2618 			w5p->hcsw.Type = Type;
2619 		}
2620 	}
2621 
2622 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
2623 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2624 				"0313 Ring %d handler: unexpected Rctl x%x "
2625 				"Type x%x received\n",
2626 				pring->ringno, Rctl, Type);
2627 
2628 	return 1;
2629 }
2630 
2631 /**
2632  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
2633  * @phba: Pointer to HBA context object.
2634  * @pring: Pointer to driver SLI ring object.
2635  * @prspiocb: Pointer to response iocb object.
2636  *
2637  * This function looks up the iocb_lookup table to get the command iocb
2638  * corresponding to the given response iocb using the iotag of the
2639  * response iocb. This function is called with the hbalock held.
2640  * This function returns the command iocb object if it finds the command
2641  * iocb else returns NULL.
2642  **/
2643 static struct lpfc_iocbq *
2644 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
2645 		      struct lpfc_sli_ring *pring,
2646 		      struct lpfc_iocbq *prspiocb)
2647 {
2648 	struct lpfc_iocbq *cmd_iocb = NULL;
2649 	uint16_t iotag;
2650 
2651 	iotag = prspiocb->iocb.ulpIoTag;
2652 
2653 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
2654 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
2655 		list_del_init(&cmd_iocb->list);
2656 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
2657 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
2658 		}
2659 		return cmd_iocb;
2660 	}
2661 
2662 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2663 			"0317 iotag x%x is out off "
2664 			"range: max iotag x%x wd0 x%x\n",
2665 			iotag, phba->sli.last_iotag,
2666 			*(((uint32_t *) &prspiocb->iocb) + 7));
2667 	return NULL;
2668 }
2669 
2670 /**
2671  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
2672  * @phba: Pointer to HBA context object.
2673  * @pring: Pointer to driver SLI ring object.
2674  * @iotag: IOCB tag.
2675  *
2676  * This function looks up the iocb_lookup table to get the command iocb
2677  * corresponding to the given iotag. This function is called with the
2678  * hbalock held.
2679  * This function returns the command iocb object if it finds the command
2680  * iocb else returns NULL.
2681  **/
2682 static struct lpfc_iocbq *
2683 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
2684 			     struct lpfc_sli_ring *pring, uint16_t iotag)
2685 {
2686 	struct lpfc_iocbq *cmd_iocb;
2687 
2688 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
2689 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
2690 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
2691 			/* remove from txcmpl queue list */
2692 			list_del_init(&cmd_iocb->list);
2693 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
2694 			return cmd_iocb;
2695 		}
2696 	}
2697 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2698 			"0372 iotag x%x is out off range: max iotag (x%x)\n",
2699 			iotag, phba->sli.last_iotag);
2700 	return NULL;
2701 }
2702 
2703 /**
2704  * lpfc_sli_process_sol_iocb - process solicited iocb completion
2705  * @phba: Pointer to HBA context object.
2706  * @pring: Pointer to driver SLI ring object.
2707  * @saveq: Pointer to the response iocb to be processed.
2708  *
2709  * This function is called by the ring event handler for non-fcp
2710  * rings when there is a new response iocb in the response ring.
2711  * The caller is not required to hold any locks. This function
2712  * gets the command iocb associated with the response iocb and
2713  * calls the completion handler for the command iocb. If there
2714  * is no completion handler, the function will free the resources
2715  * associated with command iocb. If the response iocb is for
2716  * an already aborted command iocb, the status of the completion
2717  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
2718  * This function always returns 1.
2719  **/
2720 static int
2721 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2722 			  struct lpfc_iocbq *saveq)
2723 {
2724 	struct lpfc_iocbq *cmdiocbp;
2725 	int rc = 1;
2726 	unsigned long iflag;
2727 
2728 	/* Based on the iotag field, get the cmd IOCB from the txcmplq */
2729 	spin_lock_irqsave(&phba->hbalock, iflag);
2730 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
2731 	spin_unlock_irqrestore(&phba->hbalock, iflag);
2732 
2733 	if (cmdiocbp) {
2734 		if (cmdiocbp->iocb_cmpl) {
2735 			/*
2736 			 * If an ELS command failed send an event to mgmt
2737 			 * application.
2738 			 */
2739 			if (saveq->iocb.ulpStatus &&
2740 			     (pring->ringno == LPFC_ELS_RING) &&
2741 			     (cmdiocbp->iocb.ulpCommand ==
2742 				CMD_ELS_REQUEST64_CR))
2743 				lpfc_send_els_failure_event(phba,
2744 					cmdiocbp, saveq);
2745 
2746 			/*
2747 			 * Post all ELS completions to the worker thread.
2748 			 * All other are passed to the completion callback.
2749 			 */
2750 			if (pring->ringno == LPFC_ELS_RING) {
2751 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
2752 				    (cmdiocbp->iocb_flag &
2753 							LPFC_DRIVER_ABORTED)) {
2754 					spin_lock_irqsave(&phba->hbalock,
2755 							  iflag);
2756 					cmdiocbp->iocb_flag &=
2757 						~LPFC_DRIVER_ABORTED;
2758 					spin_unlock_irqrestore(&phba->hbalock,
2759 							       iflag);
2760 					saveq->iocb.ulpStatus =
2761 						IOSTAT_LOCAL_REJECT;
2762 					saveq->iocb.un.ulpWord[4] =
2763 						IOERR_SLI_ABORTED;
2764 
2765 					/* Firmware could still be in progress
2766 					 * of DMAing payload, so don't free data
2767 					 * buffer till after a hbeat.
2768 					 */
2769 					spin_lock_irqsave(&phba->hbalock,
2770 							  iflag);
2771 					saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
2772 					spin_unlock_irqrestore(&phba->hbalock,
2773 							       iflag);
2774 				}
2775 				if (phba->sli_rev == LPFC_SLI_REV4) {
2776 					if (saveq->iocb_flag &
2777 					    LPFC_EXCHANGE_BUSY) {
2778 						/* Set cmdiocb flag for the
2779 						 * exchange busy so sgl (xri)
2780 						 * will not be released until
2781 						 * the abort xri is received
2782 						 * from hba.
2783 						 */
2784 						spin_lock_irqsave(
2785 							&phba->hbalock, iflag);
2786 						cmdiocbp->iocb_flag |=
2787 							LPFC_EXCHANGE_BUSY;
2788 						spin_unlock_irqrestore(
2789 							&phba->hbalock, iflag);
2790 					}
2791 					if (cmdiocbp->iocb_flag &
2792 					    LPFC_DRIVER_ABORTED) {
2793 						/*
2794 						 * Clear LPFC_DRIVER_ABORTED
2795 						 * bit in case it was driver
2796 						 * initiated abort.
2797 						 */
2798 						spin_lock_irqsave(
2799 							&phba->hbalock, iflag);
2800 						cmdiocbp->iocb_flag &=
2801 							~LPFC_DRIVER_ABORTED;
2802 						spin_unlock_irqrestore(
2803 							&phba->hbalock, iflag);
2804 						cmdiocbp->iocb.ulpStatus =
2805 							IOSTAT_LOCAL_REJECT;
2806 						cmdiocbp->iocb.un.ulpWord[4] =
2807 							IOERR_ABORT_REQUESTED;
2808 						/*
2809 						 * For SLI4, irsiocb contains
2810 						 * NO_XRI in sli_xritag, it
2811 						 * shall not affect releasing
2812 						 * sgl (xri) process.
2813 						 */
2814 						saveq->iocb.ulpStatus =
2815 							IOSTAT_LOCAL_REJECT;
2816 						saveq->iocb.un.ulpWord[4] =
2817 							IOERR_SLI_ABORTED;
2818 						spin_lock_irqsave(
2819 							&phba->hbalock, iflag);
2820 						saveq->iocb_flag |=
2821 							LPFC_DELAY_MEM_FREE;
2822 						spin_unlock_irqrestore(
2823 							&phba->hbalock, iflag);
2824 					}
2825 				}
2826 			}
2827 			(cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
2828 		} else
2829 			lpfc_sli_release_iocbq(phba, cmdiocbp);
2830 	} else {
2831 		/*
2832 		 * Unknown initiating command based on the response iotag.
2833 		 * This could be the case on the ELS ring because of
2834 		 * lpfc_els_abort().
2835 		 */
2836 		if (pring->ringno != LPFC_ELS_RING) {
2837 			/*
2838 			 * Ring <ringno> handler: unexpected completion IoTag
2839 			 * <IoTag>
2840 			 */
2841 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2842 					 "0322 Ring %d handler: "
2843 					 "unexpected completion IoTag x%x "
2844 					 "Data: x%x x%x x%x x%x\n",
2845 					 pring->ringno,
2846 					 saveq->iocb.ulpIoTag,
2847 					 saveq->iocb.ulpStatus,
2848 					 saveq->iocb.un.ulpWord[4],
2849 					 saveq->iocb.ulpCommand,
2850 					 saveq->iocb.ulpContext);
2851 		}
2852 	}
2853 
2854 	return rc;
2855 }
2856 
2857 /**
2858  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
2859  * @phba: Pointer to HBA context object.
2860  * @pring: Pointer to driver SLI ring object.
2861  *
2862  * This function is called from the iocb ring event handlers when
2863  * put pointer is ahead of the get pointer for a ring. This function signal
2864  * an error attention condition to the worker thread and the worker
2865  * thread will transition the HBA to offline state.
2866  **/
2867 static void
2868 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2869 {
2870 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2871 	/*
2872 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
2873 	 * rsp ring <portRspMax>
2874 	 */
2875 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2876 			"0312 Ring %d handler: portRspPut %d "
2877 			"is bigger than rsp ring %d\n",
2878 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
2879 			pring->sli.sli3.numRiocb);
2880 
2881 	phba->link_state = LPFC_HBA_ERROR;
2882 
2883 	/*
2884 	 * All error attention handlers are posted to
2885 	 * worker thread
2886 	 */
2887 	phba->work_ha |= HA_ERATT;
2888 	phba->work_hs = HS_FFER3;
2889 
2890 	lpfc_worker_wake_up(phba);
2891 
2892 	return;
2893 }
2894 
2895 /**
2896  * lpfc_poll_eratt - Error attention polling timer timeout handler
2897  * @ptr: Pointer to address of HBA context object.
2898  *
2899  * This function is invoked by the Error Attention polling timer when the
2900  * timer times out. It will check the SLI Error Attention register for
2901  * possible attention events. If so, it will post an Error Attention event
2902  * and wake up worker thread to process it. Otherwise, it will set up the
2903  * Error Attention polling timer for the next poll.
2904  **/
2905 void lpfc_poll_eratt(unsigned long ptr)
2906 {
2907 	struct lpfc_hba *phba;
2908 	uint32_t eratt = 0;
2909 	uint64_t sli_intr, cnt;
2910 
2911 	phba = (struct lpfc_hba *)ptr;
2912 
2913 	/* Here we will also keep track of interrupts per sec of the hba */
2914 	sli_intr = phba->sli.slistat.sli_intr;
2915 
2916 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
2917 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
2918 			sli_intr);
2919 	else
2920 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
2921 
2922 	/* 64-bit integer division not supporte on 32-bit x86 - use do_div */
2923 	do_div(cnt, LPFC_ERATT_POLL_INTERVAL);
2924 	phba->sli.slistat.sli_ips = cnt;
2925 
2926 	phba->sli.slistat.sli_prev_intr = sli_intr;
2927 
2928 	/* Check chip HA register for error event */
2929 	eratt = lpfc_sli_check_eratt(phba);
2930 
2931 	if (eratt)
2932 		/* Tell the worker thread there is work to do */
2933 		lpfc_worker_wake_up(phba);
2934 	else
2935 		/* Restart the timer for next eratt poll */
2936 		mod_timer(&phba->eratt_poll,
2937 			  jiffies +
2938 			  msecs_to_jiffies(1000 * LPFC_ERATT_POLL_INTERVAL));
2939 	return;
2940 }
2941 
2942 
2943 /**
2944  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
2945  * @phba: Pointer to HBA context object.
2946  * @pring: Pointer to driver SLI ring object.
2947  * @mask: Host attention register mask for this ring.
2948  *
2949  * This function is called from the interrupt context when there is a ring
2950  * event for the fcp ring. The caller does not hold any lock.
2951  * The function processes each response iocb in the response ring until it
2952  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
2953  * LE bit set. The function will call the completion handler of the command iocb
2954  * if the response iocb indicates a completion for a command iocb or it is
2955  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
2956  * function if this is an unsolicited iocb.
2957  * This routine presumes LPFC_FCP_RING handling and doesn't bother
2958  * to check it explicitly.
2959  */
2960 int
2961 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
2962 				struct lpfc_sli_ring *pring, uint32_t mask)
2963 {
2964 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2965 	IOCB_t *irsp = NULL;
2966 	IOCB_t *entry = NULL;
2967 	struct lpfc_iocbq *cmdiocbq = NULL;
2968 	struct lpfc_iocbq rspiocbq;
2969 	uint32_t status;
2970 	uint32_t portRspPut, portRspMax;
2971 	int rc = 1;
2972 	lpfc_iocb_type type;
2973 	unsigned long iflag;
2974 	uint32_t rsp_cmpl = 0;
2975 
2976 	spin_lock_irqsave(&phba->hbalock, iflag);
2977 	pring->stats.iocb_event++;
2978 
2979 	/*
2980 	 * The next available response entry should never exceed the maximum
2981 	 * entries.  If it does, treat it as an adapter hardware error.
2982 	 */
2983 	portRspMax = pring->sli.sli3.numRiocb;
2984 	portRspPut = le32_to_cpu(pgp->rspPutInx);
2985 	if (unlikely(portRspPut >= portRspMax)) {
2986 		lpfc_sli_rsp_pointers_error(phba, pring);
2987 		spin_unlock_irqrestore(&phba->hbalock, iflag);
2988 		return 1;
2989 	}
2990 	if (phba->fcp_ring_in_use) {
2991 		spin_unlock_irqrestore(&phba->hbalock, iflag);
2992 		return 1;
2993 	} else
2994 		phba->fcp_ring_in_use = 1;
2995 
2996 	rmb();
2997 	while (pring->sli.sli3.rspidx != portRspPut) {
2998 		/*
2999 		 * Fetch an entry off the ring and copy it into a local data
3000 		 * structure.  The copy involves a byte-swap since the
3001 		 * network byte order and pci byte orders are different.
3002 		 */
3003 		entry = lpfc_resp_iocb(phba, pring);
3004 		phba->last_completion_time = jiffies;
3005 
3006 		if (++pring->sli.sli3.rspidx >= portRspMax)
3007 			pring->sli.sli3.rspidx = 0;
3008 
3009 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3010 				      (uint32_t *) &rspiocbq.iocb,
3011 				      phba->iocb_rsp_size);
3012 		INIT_LIST_HEAD(&(rspiocbq.list));
3013 		irsp = &rspiocbq.iocb;
3014 
3015 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3016 		pring->stats.iocb_rsp++;
3017 		rsp_cmpl++;
3018 
3019 		if (unlikely(irsp->ulpStatus)) {
3020 			/*
3021 			 * If resource errors reported from HBA, reduce
3022 			 * queuedepths of the SCSI device.
3023 			 */
3024 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3025 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3026 			     IOERR_NO_RESOURCES)) {
3027 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3028 				phba->lpfc_rampdown_queue_depth(phba);
3029 				spin_lock_irqsave(&phba->hbalock, iflag);
3030 			}
3031 
3032 			/* Rsp ring <ringno> error: IOCB */
3033 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3034 					"0336 Rsp Ring %d error: IOCB Data: "
3035 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
3036 					pring->ringno,
3037 					irsp->un.ulpWord[0],
3038 					irsp->un.ulpWord[1],
3039 					irsp->un.ulpWord[2],
3040 					irsp->un.ulpWord[3],
3041 					irsp->un.ulpWord[4],
3042 					irsp->un.ulpWord[5],
3043 					*(uint32_t *)&irsp->un1,
3044 					*((uint32_t *)&irsp->un1 + 1));
3045 		}
3046 
3047 		switch (type) {
3048 		case LPFC_ABORT_IOCB:
3049 		case LPFC_SOL_IOCB:
3050 			/*
3051 			 * Idle exchange closed via ABTS from port.  No iocb
3052 			 * resources need to be recovered.
3053 			 */
3054 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3055 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3056 						"0333 IOCB cmd 0x%x"
3057 						" processed. Skipping"
3058 						" completion\n",
3059 						irsp->ulpCommand);
3060 				break;
3061 			}
3062 
3063 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3064 							 &rspiocbq);
3065 			if (unlikely(!cmdiocbq))
3066 				break;
3067 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3068 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3069 			if (cmdiocbq->iocb_cmpl) {
3070 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3071 				(cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
3072 						      &rspiocbq);
3073 				spin_lock_irqsave(&phba->hbalock, iflag);
3074 			}
3075 			break;
3076 		case LPFC_UNSOL_IOCB:
3077 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3078 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
3079 			spin_lock_irqsave(&phba->hbalock, iflag);
3080 			break;
3081 		default:
3082 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3083 				char adaptermsg[LPFC_MAX_ADPTMSG];
3084 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3085 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
3086 				       MAX_MSG_DATA);
3087 				dev_warn(&((phba->pcidev)->dev),
3088 					 "lpfc%d: %s\n",
3089 					 phba->brd_no, adaptermsg);
3090 			} else {
3091 				/* Unknown IOCB command */
3092 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3093 						"0334 Unknown IOCB command "
3094 						"Data: x%x, x%x x%x x%x x%x\n",
3095 						type, irsp->ulpCommand,
3096 						irsp->ulpStatus,
3097 						irsp->ulpIoTag,
3098 						irsp->ulpContext);
3099 			}
3100 			break;
3101 		}
3102 
3103 		/*
3104 		 * The response IOCB has been processed.  Update the ring
3105 		 * pointer in SLIM.  If the port response put pointer has not
3106 		 * been updated, sync the pgp->rspPutInx and fetch the new port
3107 		 * response put pointer.
3108 		 */
3109 		writel(pring->sli.sli3.rspidx,
3110 			&phba->host_gp[pring->ringno].rspGetInx);
3111 
3112 		if (pring->sli.sli3.rspidx == portRspPut)
3113 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3114 	}
3115 
3116 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
3117 		pring->stats.iocb_rsp_full++;
3118 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3119 		writel(status, phba->CAregaddr);
3120 		readl(phba->CAregaddr);
3121 	}
3122 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3123 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3124 		pring->stats.iocb_cmd_empty++;
3125 
3126 		/* Force update of the local copy of cmdGetInx */
3127 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3128 		lpfc_sli_resume_iocb(phba, pring);
3129 
3130 		if ((pring->lpfc_sli_cmd_available))
3131 			(pring->lpfc_sli_cmd_available) (phba, pring);
3132 
3133 	}
3134 
3135 	phba->fcp_ring_in_use = 0;
3136 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3137 	return rc;
3138 }
3139 
3140 /**
3141  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
3142  * @phba: Pointer to HBA context object.
3143  * @pring: Pointer to driver SLI ring object.
3144  * @rspiocbp: Pointer to driver response IOCB object.
3145  *
3146  * This function is called from the worker thread when there is a slow-path
3147  * response IOCB to process. This function chains all the response iocbs until
3148  * seeing the iocb with the LE bit set. The function will call
3149  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
3150  * completion of a command iocb. The function will call the
3151  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
3152  * The function frees the resources or calls the completion handler if this
3153  * iocb is an abort completion. The function returns NULL when the response
3154  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
3155  * this function shall chain the iocb on to the iocb_continueq and return the
3156  * response iocb passed in.
3157  **/
3158 static struct lpfc_iocbq *
3159 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3160 			struct lpfc_iocbq *rspiocbp)
3161 {
3162 	struct lpfc_iocbq *saveq;
3163 	struct lpfc_iocbq *cmdiocbp;
3164 	struct lpfc_iocbq *next_iocb;
3165 	IOCB_t *irsp = NULL;
3166 	uint32_t free_saveq;
3167 	uint8_t iocb_cmd_type;
3168 	lpfc_iocb_type type;
3169 	unsigned long iflag;
3170 	int rc;
3171 
3172 	spin_lock_irqsave(&phba->hbalock, iflag);
3173 	/* First add the response iocb to the countinueq list */
3174 	list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
3175 	pring->iocb_continueq_cnt++;
3176 
3177 	/* Now, determine whether the list is completed for processing */
3178 	irsp = &rspiocbp->iocb;
3179 	if (irsp->ulpLe) {
3180 		/*
3181 		 * By default, the driver expects to free all resources
3182 		 * associated with this iocb completion.
3183 		 */
3184 		free_saveq = 1;
3185 		saveq = list_get_first(&pring->iocb_continueq,
3186 				       struct lpfc_iocbq, list);
3187 		irsp = &(saveq->iocb);
3188 		list_del_init(&pring->iocb_continueq);
3189 		pring->iocb_continueq_cnt = 0;
3190 
3191 		pring->stats.iocb_rsp++;
3192 
3193 		/*
3194 		 * If resource errors reported from HBA, reduce
3195 		 * queuedepths of the SCSI device.
3196 		 */
3197 		if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3198 		    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3199 		     IOERR_NO_RESOURCES)) {
3200 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3201 			phba->lpfc_rampdown_queue_depth(phba);
3202 			spin_lock_irqsave(&phba->hbalock, iflag);
3203 		}
3204 
3205 		if (irsp->ulpStatus) {
3206 			/* Rsp ring <ringno> error: IOCB */
3207 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3208 					"0328 Rsp Ring %d error: "
3209 					"IOCB Data: "
3210 					"x%x x%x x%x x%x "
3211 					"x%x x%x x%x x%x "
3212 					"x%x x%x x%x x%x "
3213 					"x%x x%x x%x x%x\n",
3214 					pring->ringno,
3215 					irsp->un.ulpWord[0],
3216 					irsp->un.ulpWord[1],
3217 					irsp->un.ulpWord[2],
3218 					irsp->un.ulpWord[3],
3219 					irsp->un.ulpWord[4],
3220 					irsp->un.ulpWord[5],
3221 					*(((uint32_t *) irsp) + 6),
3222 					*(((uint32_t *) irsp) + 7),
3223 					*(((uint32_t *) irsp) + 8),
3224 					*(((uint32_t *) irsp) + 9),
3225 					*(((uint32_t *) irsp) + 10),
3226 					*(((uint32_t *) irsp) + 11),
3227 					*(((uint32_t *) irsp) + 12),
3228 					*(((uint32_t *) irsp) + 13),
3229 					*(((uint32_t *) irsp) + 14),
3230 					*(((uint32_t *) irsp) + 15));
3231 		}
3232 
3233 		/*
3234 		 * Fetch the IOCB command type and call the correct completion
3235 		 * routine. Solicited and Unsolicited IOCBs on the ELS ring
3236 		 * get freed back to the lpfc_iocb_list by the discovery
3237 		 * kernel thread.
3238 		 */
3239 		iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
3240 		type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
3241 		switch (type) {
3242 		case LPFC_SOL_IOCB:
3243 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3244 			rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
3245 			spin_lock_irqsave(&phba->hbalock, iflag);
3246 			break;
3247 
3248 		case LPFC_UNSOL_IOCB:
3249 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3250 			rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
3251 			spin_lock_irqsave(&phba->hbalock, iflag);
3252 			if (!rc)
3253 				free_saveq = 0;
3254 			break;
3255 
3256 		case LPFC_ABORT_IOCB:
3257 			cmdiocbp = NULL;
3258 			if (irsp->ulpCommand != CMD_XRI_ABORTED_CX)
3259 				cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
3260 								 saveq);
3261 			if (cmdiocbp) {
3262 				/* Call the specified completion routine */
3263 				if (cmdiocbp->iocb_cmpl) {
3264 					spin_unlock_irqrestore(&phba->hbalock,
3265 							       iflag);
3266 					(cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
3267 							      saveq);
3268 					spin_lock_irqsave(&phba->hbalock,
3269 							  iflag);
3270 				} else
3271 					__lpfc_sli_release_iocbq(phba,
3272 								 cmdiocbp);
3273 			}
3274 			break;
3275 
3276 		case LPFC_UNKNOWN_IOCB:
3277 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3278 				char adaptermsg[LPFC_MAX_ADPTMSG];
3279 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3280 				memcpy(&adaptermsg[0], (uint8_t *)irsp,
3281 				       MAX_MSG_DATA);
3282 				dev_warn(&((phba->pcidev)->dev),
3283 					 "lpfc%d: %s\n",
3284 					 phba->brd_no, adaptermsg);
3285 			} else {
3286 				/* Unknown IOCB command */
3287 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3288 						"0335 Unknown IOCB "
3289 						"command Data: x%x "
3290 						"x%x x%x x%x\n",
3291 						irsp->ulpCommand,
3292 						irsp->ulpStatus,
3293 						irsp->ulpIoTag,
3294 						irsp->ulpContext);
3295 			}
3296 			break;
3297 		}
3298 
3299 		if (free_saveq) {
3300 			list_for_each_entry_safe(rspiocbp, next_iocb,
3301 						 &saveq->list, list) {
3302 				list_del_init(&rspiocbp->list);
3303 				__lpfc_sli_release_iocbq(phba, rspiocbp);
3304 			}
3305 			__lpfc_sli_release_iocbq(phba, saveq);
3306 		}
3307 		rspiocbp = NULL;
3308 	}
3309 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3310 	return rspiocbp;
3311 }
3312 
3313 /**
3314  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
3315  * @phba: Pointer to HBA context object.
3316  * @pring: Pointer to driver SLI ring object.
3317  * @mask: Host attention register mask for this ring.
3318  *
3319  * This routine wraps the actual slow_ring event process routine from the
3320  * API jump table function pointer from the lpfc_hba struct.
3321  **/
3322 void
3323 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
3324 				struct lpfc_sli_ring *pring, uint32_t mask)
3325 {
3326 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
3327 }
3328 
3329 /**
3330  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
3331  * @phba: Pointer to HBA context object.
3332  * @pring: Pointer to driver SLI ring object.
3333  * @mask: Host attention register mask for this ring.
3334  *
3335  * This function is called from the worker thread when there is a ring event
3336  * for non-fcp rings. The caller does not hold any lock. The function will
3337  * remove each response iocb in the response ring and calls the handle
3338  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3339  **/
3340 static void
3341 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
3342 				   struct lpfc_sli_ring *pring, uint32_t mask)
3343 {
3344 	struct lpfc_pgp *pgp;
3345 	IOCB_t *entry;
3346 	IOCB_t *irsp = NULL;
3347 	struct lpfc_iocbq *rspiocbp = NULL;
3348 	uint32_t portRspPut, portRspMax;
3349 	unsigned long iflag;
3350 	uint32_t status;
3351 
3352 	pgp = &phba->port_gp[pring->ringno];
3353 	spin_lock_irqsave(&phba->hbalock, iflag);
3354 	pring->stats.iocb_event++;
3355 
3356 	/*
3357 	 * The next available response entry should never exceed the maximum
3358 	 * entries.  If it does, treat it as an adapter hardware error.
3359 	 */
3360 	portRspMax = pring->sli.sli3.numRiocb;
3361 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3362 	if (portRspPut >= portRspMax) {
3363 		/*
3364 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3365 		 * rsp ring <portRspMax>
3366 		 */
3367 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3368 				"0303 Ring %d handler: portRspPut %d "
3369 				"is bigger than rsp ring %d\n",
3370 				pring->ringno, portRspPut, portRspMax);
3371 
3372 		phba->link_state = LPFC_HBA_ERROR;
3373 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3374 
3375 		phba->work_hs = HS_FFER3;
3376 		lpfc_handle_eratt(phba);
3377 
3378 		return;
3379 	}
3380 
3381 	rmb();
3382 	while (pring->sli.sli3.rspidx != portRspPut) {
3383 		/*
3384 		 * Build a completion list and call the appropriate handler.
3385 		 * The process is to get the next available response iocb, get
3386 		 * a free iocb from the list, copy the response data into the
3387 		 * free iocb, insert to the continuation list, and update the
3388 		 * next response index to slim.  This process makes response
3389 		 * iocb's in the ring available to DMA as fast as possible but
3390 		 * pays a penalty for a copy operation.  Since the iocb is
3391 		 * only 32 bytes, this penalty is considered small relative to
3392 		 * the PCI reads for register values and a slim write.  When
3393 		 * the ulpLe field is set, the entire Command has been
3394 		 * received.
3395 		 */
3396 		entry = lpfc_resp_iocb(phba, pring);
3397 
3398 		phba->last_completion_time = jiffies;
3399 		rspiocbp = __lpfc_sli_get_iocbq(phba);
3400 		if (rspiocbp == NULL) {
3401 			printk(KERN_ERR "%s: out of buffers! Failing "
3402 			       "completion.\n", __func__);
3403 			break;
3404 		}
3405 
3406 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
3407 				      phba->iocb_rsp_size);
3408 		irsp = &rspiocbp->iocb;
3409 
3410 		if (++pring->sli.sli3.rspidx >= portRspMax)
3411 			pring->sli.sli3.rspidx = 0;
3412 
3413 		if (pring->ringno == LPFC_ELS_RING) {
3414 			lpfc_debugfs_slow_ring_trc(phba,
3415 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
3416 				*(((uint32_t *) irsp) + 4),
3417 				*(((uint32_t *) irsp) + 6),
3418 				*(((uint32_t *) irsp) + 7));
3419 		}
3420 
3421 		writel(pring->sli.sli3.rspidx,
3422 			&phba->host_gp[pring->ringno].rspGetInx);
3423 
3424 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3425 		/* Handle the response IOCB */
3426 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
3427 		spin_lock_irqsave(&phba->hbalock, iflag);
3428 
3429 		/*
3430 		 * If the port response put pointer has not been updated, sync
3431 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
3432 		 * response put pointer.
3433 		 */
3434 		if (pring->sli.sli3.rspidx == portRspPut) {
3435 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3436 		}
3437 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
3438 
3439 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
3440 		/* At least one response entry has been freed */
3441 		pring->stats.iocb_rsp_full++;
3442 		/* SET RxRE_RSP in Chip Att register */
3443 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3444 		writel(status, phba->CAregaddr);
3445 		readl(phba->CAregaddr); /* flush */
3446 	}
3447 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3448 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3449 		pring->stats.iocb_cmd_empty++;
3450 
3451 		/* Force update of the local copy of cmdGetInx */
3452 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3453 		lpfc_sli_resume_iocb(phba, pring);
3454 
3455 		if ((pring->lpfc_sli_cmd_available))
3456 			(pring->lpfc_sli_cmd_available) (phba, pring);
3457 
3458 	}
3459 
3460 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3461 	return;
3462 }
3463 
3464 /**
3465  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
3466  * @phba: Pointer to HBA context object.
3467  * @pring: Pointer to driver SLI ring object.
3468  * @mask: Host attention register mask for this ring.
3469  *
3470  * This function is called from the worker thread when there is a pending
3471  * ELS response iocb on the driver internal slow-path response iocb worker
3472  * queue. The caller does not hold any lock. The function will remove each
3473  * response iocb from the response worker queue and calls the handle
3474  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3475  **/
3476 static void
3477 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
3478 				   struct lpfc_sli_ring *pring, uint32_t mask)
3479 {
3480 	struct lpfc_iocbq *irspiocbq;
3481 	struct hbq_dmabuf *dmabuf;
3482 	struct lpfc_cq_event *cq_event;
3483 	unsigned long iflag;
3484 
3485 	spin_lock_irqsave(&phba->hbalock, iflag);
3486 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
3487 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3488 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
3489 		/* Get the response iocb from the head of work queue */
3490 		spin_lock_irqsave(&phba->hbalock, iflag);
3491 		list_remove_head(&phba->sli4_hba.sp_queue_event,
3492 				 cq_event, struct lpfc_cq_event, list);
3493 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3494 
3495 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
3496 		case CQE_CODE_COMPL_WQE:
3497 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
3498 						 cq_event);
3499 			/* Translate ELS WCQE to response IOCBQ */
3500 			irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
3501 								   irspiocbq);
3502 			if (irspiocbq)
3503 				lpfc_sli_sp_handle_rspiocb(phba, pring,
3504 							   irspiocbq);
3505 			break;
3506 		case CQE_CODE_RECEIVE:
3507 		case CQE_CODE_RECEIVE_V1:
3508 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
3509 					      cq_event);
3510 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
3511 			break;
3512 		default:
3513 			break;
3514 		}
3515 	}
3516 }
3517 
3518 /**
3519  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
3520  * @phba: Pointer to HBA context object.
3521  * @pring: Pointer to driver SLI ring object.
3522  *
3523  * This function aborts all iocbs in the given ring and frees all the iocb
3524  * objects in txq. This function issues an abort iocb for all the iocb commands
3525  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3526  * the return of this function. The caller is not required to hold any locks.
3527  **/
3528 void
3529 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3530 {
3531 	LIST_HEAD(completions);
3532 	struct lpfc_iocbq *iocb, *next_iocb;
3533 
3534 	if (pring->ringno == LPFC_ELS_RING) {
3535 		lpfc_fabric_abort_hba(phba);
3536 	}
3537 
3538 	/* Error everything on txq and txcmplq
3539 	 * First do the txq.
3540 	 */
3541 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3542 		spin_lock_irq(&pring->ring_lock);
3543 		list_splice_init(&pring->txq, &completions);
3544 		pring->txq_cnt = 0;
3545 		spin_unlock_irq(&pring->ring_lock);
3546 
3547 		spin_lock_irq(&phba->hbalock);
3548 		/* Next issue ABTS for everything on the txcmplq */
3549 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3550 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3551 		spin_unlock_irq(&phba->hbalock);
3552 	} else {
3553 		spin_lock_irq(&phba->hbalock);
3554 		list_splice_init(&pring->txq, &completions);
3555 		pring->txq_cnt = 0;
3556 
3557 		/* Next issue ABTS for everything on the txcmplq */
3558 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3559 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3560 		spin_unlock_irq(&phba->hbalock);
3561 	}
3562 
3563 	/* Cancel all the IOCBs from the completions list */
3564 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
3565 			      IOERR_SLI_ABORTED);
3566 }
3567 
3568 /**
3569  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
3570  * @phba: Pointer to HBA context object.
3571  * @pring: Pointer to driver SLI ring object.
3572  *
3573  * This function aborts all iocbs in FCP rings and frees all the iocb
3574  * objects in txq. This function issues an abort iocb for all the iocb commands
3575  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3576  * the return of this function. The caller is not required to hold any locks.
3577  **/
3578 void
3579 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
3580 {
3581 	struct lpfc_sli *psli = &phba->sli;
3582 	struct lpfc_sli_ring  *pring;
3583 	uint32_t i;
3584 
3585 	/* Look on all the FCP Rings for the iotag */
3586 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3587 		for (i = 0; i < phba->cfg_fcp_io_channel; i++) {
3588 			pring = &psli->ring[i + MAX_SLI3_CONFIGURED_RINGS];
3589 			lpfc_sli_abort_iocb_ring(phba, pring);
3590 		}
3591 	} else {
3592 		pring = &psli->ring[psli->fcp_ring];
3593 		lpfc_sli_abort_iocb_ring(phba, pring);
3594 	}
3595 }
3596 
3597 
3598 /**
3599  * lpfc_sli_flush_fcp_rings - flush all iocbs in the fcp ring
3600  * @phba: Pointer to HBA context object.
3601  *
3602  * This function flushes all iocbs in the fcp ring and frees all the iocb
3603  * objects in txq and txcmplq. This function will not issue abort iocbs
3604  * for all the iocb commands in txcmplq, they will just be returned with
3605  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
3606  * slot has been permanently disabled.
3607  **/
3608 void
3609 lpfc_sli_flush_fcp_rings(struct lpfc_hba *phba)
3610 {
3611 	LIST_HEAD(txq);
3612 	LIST_HEAD(txcmplq);
3613 	struct lpfc_sli *psli = &phba->sli;
3614 	struct lpfc_sli_ring  *pring;
3615 	uint32_t i;
3616 
3617 	spin_lock_irq(&phba->hbalock);
3618 	/* Indicate the I/O queues are flushed */
3619 	phba->hba_flag |= HBA_FCP_IOQ_FLUSH;
3620 	spin_unlock_irq(&phba->hbalock);
3621 
3622 	/* Look on all the FCP Rings for the iotag */
3623 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3624 		for (i = 0; i < phba->cfg_fcp_io_channel; i++) {
3625 			pring = &psli->ring[i + MAX_SLI3_CONFIGURED_RINGS];
3626 
3627 			spin_lock_irq(&pring->ring_lock);
3628 			/* Retrieve everything on txq */
3629 			list_splice_init(&pring->txq, &txq);
3630 			/* Retrieve everything on the txcmplq */
3631 			list_splice_init(&pring->txcmplq, &txcmplq);
3632 			pring->txq_cnt = 0;
3633 			pring->txcmplq_cnt = 0;
3634 			spin_unlock_irq(&pring->ring_lock);
3635 
3636 			/* Flush the txq */
3637 			lpfc_sli_cancel_iocbs(phba, &txq,
3638 					      IOSTAT_LOCAL_REJECT,
3639 					      IOERR_SLI_DOWN);
3640 			/* Flush the txcmpq */
3641 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
3642 					      IOSTAT_LOCAL_REJECT,
3643 					      IOERR_SLI_DOWN);
3644 		}
3645 	} else {
3646 		pring = &psli->ring[psli->fcp_ring];
3647 
3648 		spin_lock_irq(&phba->hbalock);
3649 		/* Retrieve everything on txq */
3650 		list_splice_init(&pring->txq, &txq);
3651 		/* Retrieve everything on the txcmplq */
3652 		list_splice_init(&pring->txcmplq, &txcmplq);
3653 		pring->txq_cnt = 0;
3654 		pring->txcmplq_cnt = 0;
3655 		spin_unlock_irq(&phba->hbalock);
3656 
3657 		/* Flush the txq */
3658 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
3659 				      IOERR_SLI_DOWN);
3660 		/* Flush the txcmpq */
3661 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
3662 				      IOERR_SLI_DOWN);
3663 	}
3664 }
3665 
3666 /**
3667  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
3668  * @phba: Pointer to HBA context object.
3669  * @mask: Bit mask to be checked.
3670  *
3671  * This function reads the host status register and compares
3672  * with the provided bit mask to check if HBA completed
3673  * the restart. This function will wait in a loop for the
3674  * HBA to complete restart. If the HBA does not restart within
3675  * 15 iterations, the function will reset the HBA again. The
3676  * function returns 1 when HBA fail to restart otherwise returns
3677  * zero.
3678  **/
3679 static int
3680 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
3681 {
3682 	uint32_t status;
3683 	int i = 0;
3684 	int retval = 0;
3685 
3686 	/* Read the HBA Host Status Register */
3687 	if (lpfc_readl(phba->HSregaddr, &status))
3688 		return 1;
3689 
3690 	/*
3691 	 * Check status register every 100ms for 5 retries, then every
3692 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
3693 	 * every 2.5 sec for 4.
3694 	 * Break our of the loop if errors occurred during init.
3695 	 */
3696 	while (((status & mask) != mask) &&
3697 	       !(status & HS_FFERM) &&
3698 	       i++ < 20) {
3699 
3700 		if (i <= 5)
3701 			msleep(10);
3702 		else if (i <= 10)
3703 			msleep(500);
3704 		else
3705 			msleep(2500);
3706 
3707 		if (i == 15) {
3708 				/* Do post */
3709 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
3710 			lpfc_sli_brdrestart(phba);
3711 		}
3712 		/* Read the HBA Host Status Register */
3713 		if (lpfc_readl(phba->HSregaddr, &status)) {
3714 			retval = 1;
3715 			break;
3716 		}
3717 	}
3718 
3719 	/* Check to see if any errors occurred during init */
3720 	if ((status & HS_FFERM) || (i >= 20)) {
3721 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3722 				"2751 Adapter failed to restart, "
3723 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
3724 				status,
3725 				readl(phba->MBslimaddr + 0xa8),
3726 				readl(phba->MBslimaddr + 0xac));
3727 		phba->link_state = LPFC_HBA_ERROR;
3728 		retval = 1;
3729 	}
3730 
3731 	return retval;
3732 }
3733 
3734 /**
3735  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
3736  * @phba: Pointer to HBA context object.
3737  * @mask: Bit mask to be checked.
3738  *
3739  * This function checks the host status register to check if HBA is
3740  * ready. This function will wait in a loop for the HBA to be ready
3741  * If the HBA is not ready , the function will will reset the HBA PCI
3742  * function again. The function returns 1 when HBA fail to be ready
3743  * otherwise returns zero.
3744  **/
3745 static int
3746 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
3747 {
3748 	uint32_t status;
3749 	int retval = 0;
3750 
3751 	/* Read the HBA Host Status Register */
3752 	status = lpfc_sli4_post_status_check(phba);
3753 
3754 	if (status) {
3755 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
3756 		lpfc_sli_brdrestart(phba);
3757 		status = lpfc_sli4_post_status_check(phba);
3758 	}
3759 
3760 	/* Check to see if any errors occurred during init */
3761 	if (status) {
3762 		phba->link_state = LPFC_HBA_ERROR;
3763 		retval = 1;
3764 	} else
3765 		phba->sli4_hba.intr_enable = 0;
3766 
3767 	return retval;
3768 }
3769 
3770 /**
3771  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
3772  * @phba: Pointer to HBA context object.
3773  * @mask: Bit mask to be checked.
3774  *
3775  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
3776  * from the API jump table function pointer from the lpfc_hba struct.
3777  **/
3778 int
3779 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
3780 {
3781 	return phba->lpfc_sli_brdready(phba, mask);
3782 }
3783 
3784 #define BARRIER_TEST_PATTERN (0xdeadbeef)
3785 
3786 /**
3787  * lpfc_reset_barrier - Make HBA ready for HBA reset
3788  * @phba: Pointer to HBA context object.
3789  *
3790  * This function is called before resetting an HBA. This function is called
3791  * with hbalock held and requests HBA to quiesce DMAs before a reset.
3792  **/
3793 void lpfc_reset_barrier(struct lpfc_hba *phba)
3794 {
3795 	uint32_t __iomem *resp_buf;
3796 	uint32_t __iomem *mbox_buf;
3797 	volatile uint32_t mbox;
3798 	uint32_t hc_copy, ha_copy, resp_data;
3799 	int  i;
3800 	uint8_t hdrtype;
3801 
3802 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
3803 	if (hdrtype != 0x80 ||
3804 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
3805 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
3806 		return;
3807 
3808 	/*
3809 	 * Tell the other part of the chip to suspend temporarily all
3810 	 * its DMA activity.
3811 	 */
3812 	resp_buf = phba->MBslimaddr;
3813 
3814 	/* Disable the error attention */
3815 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
3816 		return;
3817 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
3818 	readl(phba->HCregaddr); /* flush */
3819 	phba->link_flag |= LS_IGNORE_ERATT;
3820 
3821 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
3822 		return;
3823 	if (ha_copy & HA_ERATT) {
3824 		/* Clear Chip error bit */
3825 		writel(HA_ERATT, phba->HAregaddr);
3826 		phba->pport->stopped = 1;
3827 	}
3828 
3829 	mbox = 0;
3830 	((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
3831 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
3832 
3833 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
3834 	mbox_buf = phba->MBslimaddr;
3835 	writel(mbox, mbox_buf);
3836 
3837 	for (i = 0; i < 50; i++) {
3838 		if (lpfc_readl((resp_buf + 1), &resp_data))
3839 			return;
3840 		if (resp_data != ~(BARRIER_TEST_PATTERN))
3841 			mdelay(1);
3842 		else
3843 			break;
3844 	}
3845 	resp_data = 0;
3846 	if (lpfc_readl((resp_buf + 1), &resp_data))
3847 		return;
3848 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
3849 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
3850 		    phba->pport->stopped)
3851 			goto restore_hc;
3852 		else
3853 			goto clear_errat;
3854 	}
3855 
3856 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
3857 	resp_data = 0;
3858 	for (i = 0; i < 500; i++) {
3859 		if (lpfc_readl(resp_buf, &resp_data))
3860 			return;
3861 		if (resp_data != mbox)
3862 			mdelay(1);
3863 		else
3864 			break;
3865 	}
3866 
3867 clear_errat:
3868 
3869 	while (++i < 500) {
3870 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
3871 			return;
3872 		if (!(ha_copy & HA_ERATT))
3873 			mdelay(1);
3874 		else
3875 			break;
3876 	}
3877 
3878 	if (readl(phba->HAregaddr) & HA_ERATT) {
3879 		writel(HA_ERATT, phba->HAregaddr);
3880 		phba->pport->stopped = 1;
3881 	}
3882 
3883 restore_hc:
3884 	phba->link_flag &= ~LS_IGNORE_ERATT;
3885 	writel(hc_copy, phba->HCregaddr);
3886 	readl(phba->HCregaddr); /* flush */
3887 }
3888 
3889 /**
3890  * lpfc_sli_brdkill - Issue a kill_board mailbox command
3891  * @phba: Pointer to HBA context object.
3892  *
3893  * This function issues a kill_board mailbox command and waits for
3894  * the error attention interrupt. This function is called for stopping
3895  * the firmware processing. The caller is not required to hold any
3896  * locks. This function calls lpfc_hba_down_post function to free
3897  * any pending commands after the kill. The function will return 1 when it
3898  * fails to kill the board else will return 0.
3899  **/
3900 int
3901 lpfc_sli_brdkill(struct lpfc_hba *phba)
3902 {
3903 	struct lpfc_sli *psli;
3904 	LPFC_MBOXQ_t *pmb;
3905 	uint32_t status;
3906 	uint32_t ha_copy;
3907 	int retval;
3908 	int i = 0;
3909 
3910 	psli = &phba->sli;
3911 
3912 	/* Kill HBA */
3913 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3914 			"0329 Kill HBA Data: x%x x%x\n",
3915 			phba->pport->port_state, psli->sli_flag);
3916 
3917 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
3918 	if (!pmb)
3919 		return 1;
3920 
3921 	/* Disable the error attention */
3922 	spin_lock_irq(&phba->hbalock);
3923 	if (lpfc_readl(phba->HCregaddr, &status)) {
3924 		spin_unlock_irq(&phba->hbalock);
3925 		mempool_free(pmb, phba->mbox_mem_pool);
3926 		return 1;
3927 	}
3928 	status &= ~HC_ERINT_ENA;
3929 	writel(status, phba->HCregaddr);
3930 	readl(phba->HCregaddr); /* flush */
3931 	phba->link_flag |= LS_IGNORE_ERATT;
3932 	spin_unlock_irq(&phba->hbalock);
3933 
3934 	lpfc_kill_board(phba, pmb);
3935 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
3936 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3937 
3938 	if (retval != MBX_SUCCESS) {
3939 		if (retval != MBX_BUSY)
3940 			mempool_free(pmb, phba->mbox_mem_pool);
3941 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3942 				"2752 KILL_BOARD command failed retval %d\n",
3943 				retval);
3944 		spin_lock_irq(&phba->hbalock);
3945 		phba->link_flag &= ~LS_IGNORE_ERATT;
3946 		spin_unlock_irq(&phba->hbalock);
3947 		return 1;
3948 	}
3949 
3950 	spin_lock_irq(&phba->hbalock);
3951 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
3952 	spin_unlock_irq(&phba->hbalock);
3953 
3954 	mempool_free(pmb, phba->mbox_mem_pool);
3955 
3956 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
3957 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
3958 	 * 3 seconds we still set HBA_ERROR state because the status of the
3959 	 * board is now undefined.
3960 	 */
3961 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
3962 		return 1;
3963 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
3964 		mdelay(100);
3965 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
3966 			return 1;
3967 	}
3968 
3969 	del_timer_sync(&psli->mbox_tmo);
3970 	if (ha_copy & HA_ERATT) {
3971 		writel(HA_ERATT, phba->HAregaddr);
3972 		phba->pport->stopped = 1;
3973 	}
3974 	spin_lock_irq(&phba->hbalock);
3975 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
3976 	psli->mbox_active = NULL;
3977 	phba->link_flag &= ~LS_IGNORE_ERATT;
3978 	spin_unlock_irq(&phba->hbalock);
3979 
3980 	lpfc_hba_down_post(phba);
3981 	phba->link_state = LPFC_HBA_ERROR;
3982 
3983 	return ha_copy & HA_ERATT ? 0 : 1;
3984 }
3985 
3986 /**
3987  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
3988  * @phba: Pointer to HBA context object.
3989  *
3990  * This function resets the HBA by writing HC_INITFF to the control
3991  * register. After the HBA resets, this function resets all the iocb ring
3992  * indices. This function disables PCI layer parity checking during
3993  * the reset.
3994  * This function returns 0 always.
3995  * The caller is not required to hold any locks.
3996  **/
3997 int
3998 lpfc_sli_brdreset(struct lpfc_hba *phba)
3999 {
4000 	struct lpfc_sli *psli;
4001 	struct lpfc_sli_ring *pring;
4002 	uint16_t cfg_value;
4003 	int i;
4004 
4005 	psli = &phba->sli;
4006 
4007 	/* Reset HBA */
4008 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4009 			"0325 Reset HBA Data: x%x x%x\n",
4010 			phba->pport->port_state, psli->sli_flag);
4011 
4012 	/* perform board reset */
4013 	phba->fc_eventTag = 0;
4014 	phba->link_events = 0;
4015 	phba->pport->fc_myDID = 0;
4016 	phba->pport->fc_prevDID = 0;
4017 
4018 	/* Turn off parity checking and serr during the physical reset */
4019 	pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value);
4020 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
4021 			      (cfg_value &
4022 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4023 
4024 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4025 
4026 	/* Now toggle INITFF bit in the Host Control Register */
4027 	writel(HC_INITFF, phba->HCregaddr);
4028 	mdelay(1);
4029 	readl(phba->HCregaddr); /* flush */
4030 	writel(0, phba->HCregaddr);
4031 	readl(phba->HCregaddr); /* flush */
4032 
4033 	/* Restore PCI cmd register */
4034 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4035 
4036 	/* Initialize relevant SLI info */
4037 	for (i = 0; i < psli->num_rings; i++) {
4038 		pring = &psli->ring[i];
4039 		pring->flag = 0;
4040 		pring->sli.sli3.rspidx = 0;
4041 		pring->sli.sli3.next_cmdidx  = 0;
4042 		pring->sli.sli3.local_getidx = 0;
4043 		pring->sli.sli3.cmdidx = 0;
4044 		pring->missbufcnt = 0;
4045 	}
4046 
4047 	phba->link_state = LPFC_WARM_START;
4048 	return 0;
4049 }
4050 
4051 /**
4052  * lpfc_sli4_brdreset - Reset a sli-4 HBA
4053  * @phba: Pointer to HBA context object.
4054  *
4055  * This function resets a SLI4 HBA. This function disables PCI layer parity
4056  * checking during resets the device. The caller is not required to hold
4057  * any locks.
4058  *
4059  * This function returns 0 always.
4060  **/
4061 int
4062 lpfc_sli4_brdreset(struct lpfc_hba *phba)
4063 {
4064 	struct lpfc_sli *psli = &phba->sli;
4065 	uint16_t cfg_value;
4066 	int rc = 0;
4067 
4068 	/* Reset HBA */
4069 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4070 			"0295 Reset HBA Data: x%x x%x x%x\n",
4071 			phba->pport->port_state, psli->sli_flag,
4072 			phba->hba_flag);
4073 
4074 	/* perform board reset */
4075 	phba->fc_eventTag = 0;
4076 	phba->link_events = 0;
4077 	phba->pport->fc_myDID = 0;
4078 	phba->pport->fc_prevDID = 0;
4079 
4080 	spin_lock_irq(&phba->hbalock);
4081 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
4082 	phba->fcf.fcf_flag = 0;
4083 	spin_unlock_irq(&phba->hbalock);
4084 
4085 	/* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
4086 	if (phba->hba_flag & HBA_FW_DUMP_OP) {
4087 		phba->hba_flag &= ~HBA_FW_DUMP_OP;
4088 		return rc;
4089 	}
4090 
4091 	/* Now physically reset the device */
4092 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4093 			"0389 Performing PCI function reset!\n");
4094 
4095 	/* Turn off parity checking and serr during the physical reset */
4096 	pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value);
4097 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
4098 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4099 
4100 	/* Perform FCoE PCI function reset before freeing queue memory */
4101 	rc = lpfc_pci_function_reset(phba);
4102 	lpfc_sli4_queue_destroy(phba);
4103 
4104 	/* Restore PCI cmd register */
4105 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4106 
4107 	return rc;
4108 }
4109 
4110 /**
4111  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
4112  * @phba: Pointer to HBA context object.
4113  *
4114  * This function is called in the SLI initialization code path to
4115  * restart the HBA. The caller is not required to hold any lock.
4116  * This function writes MBX_RESTART mailbox command to the SLIM and
4117  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
4118  * function to free any pending commands. The function enables
4119  * POST only during the first initialization. The function returns zero.
4120  * The function does not guarantee completion of MBX_RESTART mailbox
4121  * command before the return of this function.
4122  **/
4123 static int
4124 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
4125 {
4126 	MAILBOX_t *mb;
4127 	struct lpfc_sli *psli;
4128 	volatile uint32_t word0;
4129 	void __iomem *to_slim;
4130 	uint32_t hba_aer_enabled;
4131 
4132 	spin_lock_irq(&phba->hbalock);
4133 
4134 	/* Take PCIe device Advanced Error Reporting (AER) state */
4135 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4136 
4137 	psli = &phba->sli;
4138 
4139 	/* Restart HBA */
4140 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4141 			"0337 Restart HBA Data: x%x x%x\n",
4142 			phba->pport->port_state, psli->sli_flag);
4143 
4144 	word0 = 0;
4145 	mb = (MAILBOX_t *) &word0;
4146 	mb->mbxCommand = MBX_RESTART;
4147 	mb->mbxHc = 1;
4148 
4149 	lpfc_reset_barrier(phba);
4150 
4151 	to_slim = phba->MBslimaddr;
4152 	writel(*(uint32_t *) mb, to_slim);
4153 	readl(to_slim); /* flush */
4154 
4155 	/* Only skip post after fc_ffinit is completed */
4156 	if (phba->pport->port_state)
4157 		word0 = 1;	/* This is really setting up word1 */
4158 	else
4159 		word0 = 0;	/* This is really setting up word1 */
4160 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
4161 	writel(*(uint32_t *) mb, to_slim);
4162 	readl(to_slim); /* flush */
4163 
4164 	lpfc_sli_brdreset(phba);
4165 	phba->pport->stopped = 0;
4166 	phba->link_state = LPFC_INIT_START;
4167 	phba->hba_flag = 0;
4168 	spin_unlock_irq(&phba->hbalock);
4169 
4170 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4171 	psli->stats_start = get_seconds();
4172 
4173 	/* Give the INITFF and Post time to settle. */
4174 	mdelay(100);
4175 
4176 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4177 	if (hba_aer_enabled)
4178 		pci_disable_pcie_error_reporting(phba->pcidev);
4179 
4180 	lpfc_hba_down_post(phba);
4181 
4182 	return 0;
4183 }
4184 
4185 /**
4186  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
4187  * @phba: Pointer to HBA context object.
4188  *
4189  * This function is called in the SLI initialization code path to restart
4190  * a SLI4 HBA. The caller is not required to hold any lock.
4191  * At the end of the function, it calls lpfc_hba_down_post function to
4192  * free any pending commands.
4193  **/
4194 static int
4195 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
4196 {
4197 	struct lpfc_sli *psli = &phba->sli;
4198 	uint32_t hba_aer_enabled;
4199 	int rc;
4200 
4201 	/* Restart HBA */
4202 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4203 			"0296 Restart HBA Data: x%x x%x\n",
4204 			phba->pport->port_state, psli->sli_flag);
4205 
4206 	/* Take PCIe device Advanced Error Reporting (AER) state */
4207 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4208 
4209 	rc = lpfc_sli4_brdreset(phba);
4210 
4211 	spin_lock_irq(&phba->hbalock);
4212 	phba->pport->stopped = 0;
4213 	phba->link_state = LPFC_INIT_START;
4214 	phba->hba_flag = 0;
4215 	spin_unlock_irq(&phba->hbalock);
4216 
4217 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4218 	psli->stats_start = get_seconds();
4219 
4220 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4221 	if (hba_aer_enabled)
4222 		pci_disable_pcie_error_reporting(phba->pcidev);
4223 
4224 	lpfc_hba_down_post(phba);
4225 
4226 	return rc;
4227 }
4228 
4229 /**
4230  * lpfc_sli_brdrestart - Wrapper func for restarting hba
4231  * @phba: Pointer to HBA context object.
4232  *
4233  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
4234  * API jump table function pointer from the lpfc_hba struct.
4235 **/
4236 int
4237 lpfc_sli_brdrestart(struct lpfc_hba *phba)
4238 {
4239 	return phba->lpfc_sli_brdrestart(phba);
4240 }
4241 
4242 /**
4243  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
4244  * @phba: Pointer to HBA context object.
4245  *
4246  * This function is called after a HBA restart to wait for successful
4247  * restart of the HBA. Successful restart of the HBA is indicated by
4248  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
4249  * iteration, the function will restart the HBA again. The function returns
4250  * zero if HBA successfully restarted else returns negative error code.
4251  **/
4252 static int
4253 lpfc_sli_chipset_init(struct lpfc_hba *phba)
4254 {
4255 	uint32_t status, i = 0;
4256 
4257 	/* Read the HBA Host Status Register */
4258 	if (lpfc_readl(phba->HSregaddr, &status))
4259 		return -EIO;
4260 
4261 	/* Check status register to see what current state is */
4262 	i = 0;
4263 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
4264 
4265 		/* Check every 10ms for 10 retries, then every 100ms for 90
4266 		 * retries, then every 1 sec for 50 retires for a total of
4267 		 * ~60 seconds before reset the board again and check every
4268 		 * 1 sec for 50 retries. The up to 60 seconds before the
4269 		 * board ready is required by the Falcon FIPS zeroization
4270 		 * complete, and any reset the board in between shall cause
4271 		 * restart of zeroization, further delay the board ready.
4272 		 */
4273 		if (i++ >= 200) {
4274 			/* Adapter failed to init, timeout, status reg
4275 			   <status> */
4276 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4277 					"0436 Adapter failed to init, "
4278 					"timeout, status reg x%x, "
4279 					"FW Data: A8 x%x AC x%x\n", status,
4280 					readl(phba->MBslimaddr + 0xa8),
4281 					readl(phba->MBslimaddr + 0xac));
4282 			phba->link_state = LPFC_HBA_ERROR;
4283 			return -ETIMEDOUT;
4284 		}
4285 
4286 		/* Check to see if any errors occurred during init */
4287 		if (status & HS_FFERM) {
4288 			/* ERROR: During chipset initialization */
4289 			/* Adapter failed to init, chipset, status reg
4290 			   <status> */
4291 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4292 					"0437 Adapter failed to init, "
4293 					"chipset, status reg x%x, "
4294 					"FW Data: A8 x%x AC x%x\n", status,
4295 					readl(phba->MBslimaddr + 0xa8),
4296 					readl(phba->MBslimaddr + 0xac));
4297 			phba->link_state = LPFC_HBA_ERROR;
4298 			return -EIO;
4299 		}
4300 
4301 		if (i <= 10)
4302 			msleep(10);
4303 		else if (i <= 100)
4304 			msleep(100);
4305 		else
4306 			msleep(1000);
4307 
4308 		if (i == 150) {
4309 			/* Do post */
4310 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4311 			lpfc_sli_brdrestart(phba);
4312 		}
4313 		/* Read the HBA Host Status Register */
4314 		if (lpfc_readl(phba->HSregaddr, &status))
4315 			return -EIO;
4316 	}
4317 
4318 	/* Check to see if any errors occurred during init */
4319 	if (status & HS_FFERM) {
4320 		/* ERROR: During chipset initialization */
4321 		/* Adapter failed to init, chipset, status reg <status> */
4322 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4323 				"0438 Adapter failed to init, chipset, "
4324 				"status reg x%x, "
4325 				"FW Data: A8 x%x AC x%x\n", status,
4326 				readl(phba->MBslimaddr + 0xa8),
4327 				readl(phba->MBslimaddr + 0xac));
4328 		phba->link_state = LPFC_HBA_ERROR;
4329 		return -EIO;
4330 	}
4331 
4332 	/* Clear all interrupt enable conditions */
4333 	writel(0, phba->HCregaddr);
4334 	readl(phba->HCregaddr); /* flush */
4335 
4336 	/* setup host attn register */
4337 	writel(0xffffffff, phba->HAregaddr);
4338 	readl(phba->HAregaddr); /* flush */
4339 	return 0;
4340 }
4341 
4342 /**
4343  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
4344  *
4345  * This function calculates and returns the number of HBQs required to be
4346  * configured.
4347  **/
4348 int
4349 lpfc_sli_hbq_count(void)
4350 {
4351 	return ARRAY_SIZE(lpfc_hbq_defs);
4352 }
4353 
4354 /**
4355  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
4356  *
4357  * This function adds the number of hbq entries in every HBQ to get
4358  * the total number of hbq entries required for the HBA and returns
4359  * the total count.
4360  **/
4361 static int
4362 lpfc_sli_hbq_entry_count(void)
4363 {
4364 	int  hbq_count = lpfc_sli_hbq_count();
4365 	int  count = 0;
4366 	int  i;
4367 
4368 	for (i = 0; i < hbq_count; ++i)
4369 		count += lpfc_hbq_defs[i]->entry_count;
4370 	return count;
4371 }
4372 
4373 /**
4374  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
4375  *
4376  * This function calculates amount of memory required for all hbq entries
4377  * to be configured and returns the total memory required.
4378  **/
4379 int
4380 lpfc_sli_hbq_size(void)
4381 {
4382 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
4383 }
4384 
4385 /**
4386  * lpfc_sli_hbq_setup - configure and initialize HBQs
4387  * @phba: Pointer to HBA context object.
4388  *
4389  * This function is called during the SLI initialization to configure
4390  * all the HBQs and post buffers to the HBQ. The caller is not
4391  * required to hold any locks. This function will return zero if successful
4392  * else it will return negative error code.
4393  **/
4394 static int
4395 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
4396 {
4397 	int  hbq_count = lpfc_sli_hbq_count();
4398 	LPFC_MBOXQ_t *pmb;
4399 	MAILBOX_t *pmbox;
4400 	uint32_t hbqno;
4401 	uint32_t hbq_entry_index;
4402 
4403 				/* Get a Mailbox buffer to setup mailbox
4404 				 * commands for HBA initialization
4405 				 */
4406 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4407 
4408 	if (!pmb)
4409 		return -ENOMEM;
4410 
4411 	pmbox = &pmb->u.mb;
4412 
4413 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
4414 	phba->link_state = LPFC_INIT_MBX_CMDS;
4415 	phba->hbq_in_use = 1;
4416 
4417 	hbq_entry_index = 0;
4418 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
4419 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
4420 		phba->hbqs[hbqno].hbqPutIdx      = 0;
4421 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
4422 		phba->hbqs[hbqno].entry_count =
4423 			lpfc_hbq_defs[hbqno]->entry_count;
4424 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
4425 			hbq_entry_index, pmb);
4426 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
4427 
4428 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
4429 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
4430 			   mbxStatus <status>, ring <num> */
4431 
4432 			lpfc_printf_log(phba, KERN_ERR,
4433 					LOG_SLI | LOG_VPORT,
4434 					"1805 Adapter failed to init. "
4435 					"Data: x%x x%x x%x\n",
4436 					pmbox->mbxCommand,
4437 					pmbox->mbxStatus, hbqno);
4438 
4439 			phba->link_state = LPFC_HBA_ERROR;
4440 			mempool_free(pmb, phba->mbox_mem_pool);
4441 			return -ENXIO;
4442 		}
4443 	}
4444 	phba->hbq_count = hbq_count;
4445 
4446 	mempool_free(pmb, phba->mbox_mem_pool);
4447 
4448 	/* Initially populate or replenish the HBQs */
4449 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
4450 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
4451 	return 0;
4452 }
4453 
4454 /**
4455  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
4456  * @phba: Pointer to HBA context object.
4457  *
4458  * This function is called during the SLI initialization to configure
4459  * all the HBQs and post buffers to the HBQ. The caller is not
4460  * required to hold any locks. This function will return zero if successful
4461  * else it will return negative error code.
4462  **/
4463 static int
4464 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
4465 {
4466 	phba->hbq_in_use = 1;
4467 	phba->hbqs[0].entry_count = lpfc_hbq_defs[0]->entry_count;
4468 	phba->hbq_count = 1;
4469 	/* Initially populate or replenish the HBQs */
4470 	lpfc_sli_hbqbuf_init_hbqs(phba, 0);
4471 	return 0;
4472 }
4473 
4474 /**
4475  * lpfc_sli_config_port - Issue config port mailbox command
4476  * @phba: Pointer to HBA context object.
4477  * @sli_mode: sli mode - 2/3
4478  *
4479  * This function is called by the sli intialization code path
4480  * to issue config_port mailbox command. This function restarts the
4481  * HBA firmware and issues a config_port mailbox command to configure
4482  * the SLI interface in the sli mode specified by sli_mode
4483  * variable. The caller is not required to hold any locks.
4484  * The function returns 0 if successful, else returns negative error
4485  * code.
4486  **/
4487 int
4488 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
4489 {
4490 	LPFC_MBOXQ_t *pmb;
4491 	uint32_t resetcount = 0, rc = 0, done = 0;
4492 
4493 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4494 	if (!pmb) {
4495 		phba->link_state = LPFC_HBA_ERROR;
4496 		return -ENOMEM;
4497 	}
4498 
4499 	phba->sli_rev = sli_mode;
4500 	while (resetcount < 2 && !done) {
4501 		spin_lock_irq(&phba->hbalock);
4502 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
4503 		spin_unlock_irq(&phba->hbalock);
4504 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4505 		lpfc_sli_brdrestart(phba);
4506 		rc = lpfc_sli_chipset_init(phba);
4507 		if (rc)
4508 			break;
4509 
4510 		spin_lock_irq(&phba->hbalock);
4511 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4512 		spin_unlock_irq(&phba->hbalock);
4513 		resetcount++;
4514 
4515 		/* Call pre CONFIG_PORT mailbox command initialization.  A
4516 		 * value of 0 means the call was successful.  Any other
4517 		 * nonzero value is a failure, but if ERESTART is returned,
4518 		 * the driver may reset the HBA and try again.
4519 		 */
4520 		rc = lpfc_config_port_prep(phba);
4521 		if (rc == -ERESTART) {
4522 			phba->link_state = LPFC_LINK_UNKNOWN;
4523 			continue;
4524 		} else if (rc)
4525 			break;
4526 
4527 		phba->link_state = LPFC_INIT_MBX_CMDS;
4528 		lpfc_config_port(phba, pmb);
4529 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
4530 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
4531 					LPFC_SLI3_HBQ_ENABLED |
4532 					LPFC_SLI3_CRP_ENABLED |
4533 					LPFC_SLI3_BG_ENABLED |
4534 					LPFC_SLI3_DSS_ENABLED);
4535 		if (rc != MBX_SUCCESS) {
4536 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4537 				"0442 Adapter failed to init, mbxCmd x%x "
4538 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
4539 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
4540 			spin_lock_irq(&phba->hbalock);
4541 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
4542 			spin_unlock_irq(&phba->hbalock);
4543 			rc = -ENXIO;
4544 		} else {
4545 			/* Allow asynchronous mailbox command to go through */
4546 			spin_lock_irq(&phba->hbalock);
4547 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
4548 			spin_unlock_irq(&phba->hbalock);
4549 			done = 1;
4550 
4551 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
4552 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
4553 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
4554 					"3110 Port did not grant ASABT\n");
4555 		}
4556 	}
4557 	if (!done) {
4558 		rc = -EINVAL;
4559 		goto do_prep_failed;
4560 	}
4561 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
4562 		if (!pmb->u.mb.un.varCfgPort.cMA) {
4563 			rc = -ENXIO;
4564 			goto do_prep_failed;
4565 		}
4566 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
4567 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
4568 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
4569 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
4570 				phba->max_vpi : phba->max_vports;
4571 
4572 		} else
4573 			phba->max_vpi = 0;
4574 		phba->fips_level = 0;
4575 		phba->fips_spec_rev = 0;
4576 		if (pmb->u.mb.un.varCfgPort.gdss) {
4577 			phba->sli3_options |= LPFC_SLI3_DSS_ENABLED;
4578 			phba->fips_level = pmb->u.mb.un.varCfgPort.fips_level;
4579 			phba->fips_spec_rev = pmb->u.mb.un.varCfgPort.fips_rev;
4580 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4581 					"2850 Security Crypto Active. FIPS x%d "
4582 					"(Spec Rev: x%d)",
4583 					phba->fips_level, phba->fips_spec_rev);
4584 		}
4585 		if (pmb->u.mb.un.varCfgPort.sec_err) {
4586 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4587 					"2856 Config Port Security Crypto "
4588 					"Error: x%x ",
4589 					pmb->u.mb.un.varCfgPort.sec_err);
4590 		}
4591 		if (pmb->u.mb.un.varCfgPort.gerbm)
4592 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
4593 		if (pmb->u.mb.un.varCfgPort.gcrp)
4594 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
4595 
4596 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
4597 		phba->port_gp = phba->mbox->us.s3_pgp.port;
4598 
4599 		if (phba->cfg_enable_bg) {
4600 			if (pmb->u.mb.un.varCfgPort.gbg)
4601 				phba->sli3_options |= LPFC_SLI3_BG_ENABLED;
4602 			else
4603 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4604 						"0443 Adapter did not grant "
4605 						"BlockGuard\n");
4606 		}
4607 	} else {
4608 		phba->hbq_get = NULL;
4609 		phba->port_gp = phba->mbox->us.s2.port;
4610 		phba->max_vpi = 0;
4611 	}
4612 do_prep_failed:
4613 	mempool_free(pmb, phba->mbox_mem_pool);
4614 	return rc;
4615 }
4616 
4617 
4618 /**
4619  * lpfc_sli_hba_setup - SLI intialization function
4620  * @phba: Pointer to HBA context object.
4621  *
4622  * This function is the main SLI intialization function. This function
4623  * is called by the HBA intialization code, HBA reset code and HBA
4624  * error attention handler code. Caller is not required to hold any
4625  * locks. This function issues config_port mailbox command to configure
4626  * the SLI, setup iocb rings and HBQ rings. In the end the function
4627  * calls the config_port_post function to issue init_link mailbox
4628  * command and to start the discovery. The function will return zero
4629  * if successful, else it will return negative error code.
4630  **/
4631 int
4632 lpfc_sli_hba_setup(struct lpfc_hba *phba)
4633 {
4634 	uint32_t rc;
4635 	int  mode = 3, i;
4636 	int longs;
4637 
4638 	switch (lpfc_sli_mode) {
4639 	case 2:
4640 		if (phba->cfg_enable_npiv) {
4641 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4642 				"1824 NPIV enabled: Override lpfc_sli_mode "
4643 				"parameter (%d) to auto (0).\n",
4644 				lpfc_sli_mode);
4645 			break;
4646 		}
4647 		mode = 2;
4648 		break;
4649 	case 0:
4650 	case 3:
4651 		break;
4652 	default:
4653 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4654 				"1819 Unrecognized lpfc_sli_mode "
4655 				"parameter: %d.\n", lpfc_sli_mode);
4656 
4657 		break;
4658 	}
4659 
4660 	rc = lpfc_sli_config_port(phba, mode);
4661 
4662 	if (rc && lpfc_sli_mode == 3)
4663 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4664 				"1820 Unable to select SLI-3.  "
4665 				"Not supported by adapter.\n");
4666 	if (rc && mode != 2)
4667 		rc = lpfc_sli_config_port(phba, 2);
4668 	if (rc)
4669 		goto lpfc_sli_hba_setup_error;
4670 
4671 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
4672 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
4673 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
4674 		if (!rc) {
4675 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4676 					"2709 This device supports "
4677 					"Advanced Error Reporting (AER)\n");
4678 			spin_lock_irq(&phba->hbalock);
4679 			phba->hba_flag |= HBA_AER_ENABLED;
4680 			spin_unlock_irq(&phba->hbalock);
4681 		} else {
4682 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4683 					"2708 This device does not support "
4684 					"Advanced Error Reporting (AER): %d\n",
4685 					rc);
4686 			phba->cfg_aer_support = 0;
4687 		}
4688 	}
4689 
4690 	if (phba->sli_rev == 3) {
4691 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
4692 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
4693 	} else {
4694 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
4695 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
4696 		phba->sli3_options = 0;
4697 	}
4698 
4699 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4700 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
4701 			phba->sli_rev, phba->max_vpi);
4702 	rc = lpfc_sli_ring_map(phba);
4703 
4704 	if (rc)
4705 		goto lpfc_sli_hba_setup_error;
4706 
4707 	/* Initialize VPIs. */
4708 	if (phba->sli_rev == LPFC_SLI_REV3) {
4709 		/*
4710 		 * The VPI bitmask and physical ID array are allocated
4711 		 * and initialized once only - at driver load.  A port
4712 		 * reset doesn't need to reinitialize this memory.
4713 		 */
4714 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
4715 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
4716 			phba->vpi_bmask = kzalloc(longs * sizeof(unsigned long),
4717 						  GFP_KERNEL);
4718 			if (!phba->vpi_bmask) {
4719 				rc = -ENOMEM;
4720 				goto lpfc_sli_hba_setup_error;
4721 			}
4722 
4723 			phba->vpi_ids = kzalloc(
4724 					(phba->max_vpi+1) * sizeof(uint16_t),
4725 					GFP_KERNEL);
4726 			if (!phba->vpi_ids) {
4727 				kfree(phba->vpi_bmask);
4728 				rc = -ENOMEM;
4729 				goto lpfc_sli_hba_setup_error;
4730 			}
4731 			for (i = 0; i < phba->max_vpi; i++)
4732 				phba->vpi_ids[i] = i;
4733 		}
4734 	}
4735 
4736 	/* Init HBQs */
4737 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
4738 		rc = lpfc_sli_hbq_setup(phba);
4739 		if (rc)
4740 			goto lpfc_sli_hba_setup_error;
4741 	}
4742 	spin_lock_irq(&phba->hbalock);
4743 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
4744 	spin_unlock_irq(&phba->hbalock);
4745 
4746 	rc = lpfc_config_port_post(phba);
4747 	if (rc)
4748 		goto lpfc_sli_hba_setup_error;
4749 
4750 	return rc;
4751 
4752 lpfc_sli_hba_setup_error:
4753 	phba->link_state = LPFC_HBA_ERROR;
4754 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4755 			"0445 Firmware initialization failed\n");
4756 	return rc;
4757 }
4758 
4759 /**
4760  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
4761  * @phba: Pointer to HBA context object.
4762  * @mboxq: mailbox pointer.
4763  * This function issue a dump mailbox command to read config region
4764  * 23 and parse the records in the region and populate driver
4765  * data structure.
4766  **/
4767 static int
4768 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
4769 {
4770 	LPFC_MBOXQ_t *mboxq;
4771 	struct lpfc_dmabuf *mp;
4772 	struct lpfc_mqe *mqe;
4773 	uint32_t data_length;
4774 	int rc;
4775 
4776 	/* Program the default value of vlan_id and fc_map */
4777 	phba->valid_vlan = 0;
4778 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
4779 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
4780 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
4781 
4782 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4783 	if (!mboxq)
4784 		return -ENOMEM;
4785 
4786 	mqe = &mboxq->u.mqe;
4787 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
4788 		rc = -ENOMEM;
4789 		goto out_free_mboxq;
4790 	}
4791 
4792 	mp = (struct lpfc_dmabuf *) mboxq->context1;
4793 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4794 
4795 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
4796 			"(%d):2571 Mailbox cmd x%x Status x%x "
4797 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
4798 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
4799 			"CQ: x%x x%x x%x x%x\n",
4800 			mboxq->vport ? mboxq->vport->vpi : 0,
4801 			bf_get(lpfc_mqe_command, mqe),
4802 			bf_get(lpfc_mqe_status, mqe),
4803 			mqe->un.mb_words[0], mqe->un.mb_words[1],
4804 			mqe->un.mb_words[2], mqe->un.mb_words[3],
4805 			mqe->un.mb_words[4], mqe->un.mb_words[5],
4806 			mqe->un.mb_words[6], mqe->un.mb_words[7],
4807 			mqe->un.mb_words[8], mqe->un.mb_words[9],
4808 			mqe->un.mb_words[10], mqe->un.mb_words[11],
4809 			mqe->un.mb_words[12], mqe->un.mb_words[13],
4810 			mqe->un.mb_words[14], mqe->un.mb_words[15],
4811 			mqe->un.mb_words[16], mqe->un.mb_words[50],
4812 			mboxq->mcqe.word0,
4813 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
4814 			mboxq->mcqe.trailer);
4815 
4816 	if (rc) {
4817 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
4818 		kfree(mp);
4819 		rc = -EIO;
4820 		goto out_free_mboxq;
4821 	}
4822 	data_length = mqe->un.mb_words[5];
4823 	if (data_length > DMP_RGN23_SIZE) {
4824 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
4825 		kfree(mp);
4826 		rc = -EIO;
4827 		goto out_free_mboxq;
4828 	}
4829 
4830 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
4831 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
4832 	kfree(mp);
4833 	rc = 0;
4834 
4835 out_free_mboxq:
4836 	mempool_free(mboxq, phba->mbox_mem_pool);
4837 	return rc;
4838 }
4839 
4840 /**
4841  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
4842  * @phba: pointer to lpfc hba data structure.
4843  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
4844  * @vpd: pointer to the memory to hold resulting port vpd data.
4845  * @vpd_size: On input, the number of bytes allocated to @vpd.
4846  *	      On output, the number of data bytes in @vpd.
4847  *
4848  * This routine executes a READ_REV SLI4 mailbox command.  In
4849  * addition, this routine gets the port vpd data.
4850  *
4851  * Return codes
4852  * 	0 - successful
4853  * 	-ENOMEM - could not allocated memory.
4854  **/
4855 static int
4856 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
4857 		    uint8_t *vpd, uint32_t *vpd_size)
4858 {
4859 	int rc = 0;
4860 	uint32_t dma_size;
4861 	struct lpfc_dmabuf *dmabuf;
4862 	struct lpfc_mqe *mqe;
4863 
4864 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
4865 	if (!dmabuf)
4866 		return -ENOMEM;
4867 
4868 	/*
4869 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
4870 	 * mailbox command.
4871 	 */
4872 	dma_size = *vpd_size;
4873 	dmabuf->virt = dma_zalloc_coherent(&phba->pcidev->dev, dma_size,
4874 					   &dmabuf->phys, GFP_KERNEL);
4875 	if (!dmabuf->virt) {
4876 		kfree(dmabuf);
4877 		return -ENOMEM;
4878 	}
4879 
4880 	/*
4881 	 * The SLI4 implementation of READ_REV conflicts at word1,
4882 	 * bits 31:16 and SLI4 adds vpd functionality not present
4883 	 * in SLI3.  This code corrects the conflicts.
4884 	 */
4885 	lpfc_read_rev(phba, mboxq);
4886 	mqe = &mboxq->u.mqe;
4887 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
4888 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
4889 	mqe->un.read_rev.word1 &= 0x0000FFFF;
4890 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
4891 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
4892 
4893 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4894 	if (rc) {
4895 		dma_free_coherent(&phba->pcidev->dev, dma_size,
4896 				  dmabuf->virt, dmabuf->phys);
4897 		kfree(dmabuf);
4898 		return -EIO;
4899 	}
4900 
4901 	/*
4902 	 * The available vpd length cannot be bigger than the
4903 	 * DMA buffer passed to the port.  Catch the less than
4904 	 * case and update the caller's size.
4905 	 */
4906 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
4907 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
4908 
4909 	memcpy(vpd, dmabuf->virt, *vpd_size);
4910 
4911 	dma_free_coherent(&phba->pcidev->dev, dma_size,
4912 			  dmabuf->virt, dmabuf->phys);
4913 	kfree(dmabuf);
4914 	return 0;
4915 }
4916 
4917 /**
4918  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
4919  * @phba: pointer to lpfc hba data structure.
4920  *
4921  * This routine retrieves SLI4 device physical port name this PCI function
4922  * is attached to.
4923  *
4924  * Return codes
4925  *      0 - successful
4926  *      otherwise - failed to retrieve physical port name
4927  **/
4928 static int
4929 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
4930 {
4931 	LPFC_MBOXQ_t *mboxq;
4932 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
4933 	struct lpfc_controller_attribute *cntl_attr;
4934 	struct lpfc_mbx_get_port_name *get_port_name;
4935 	void *virtaddr = NULL;
4936 	uint32_t alloclen, reqlen;
4937 	uint32_t shdr_status, shdr_add_status;
4938 	union lpfc_sli4_cfg_shdr *shdr;
4939 	char cport_name = 0;
4940 	int rc;
4941 
4942 	/* We assume nothing at this point */
4943 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
4944 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
4945 
4946 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4947 	if (!mboxq)
4948 		return -ENOMEM;
4949 	/* obtain link type and link number via READ_CONFIG */
4950 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
4951 	lpfc_sli4_read_config(phba);
4952 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
4953 		goto retrieve_ppname;
4954 
4955 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
4956 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
4957 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
4958 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
4959 			LPFC_SLI4_MBX_NEMBED);
4960 	if (alloclen < reqlen) {
4961 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4962 				"3084 Allocated DMA memory size (%d) is "
4963 				"less than the requested DMA memory size "
4964 				"(%d)\n", alloclen, reqlen);
4965 		rc = -ENOMEM;
4966 		goto out_free_mboxq;
4967 	}
4968 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4969 	virtaddr = mboxq->sge_array->addr[0];
4970 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
4971 	shdr = &mbx_cntl_attr->cfg_shdr;
4972 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
4973 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
4974 	if (shdr_status || shdr_add_status || rc) {
4975 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4976 				"3085 Mailbox x%x (x%x/x%x) failed, "
4977 				"rc:x%x, status:x%x, add_status:x%x\n",
4978 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
4979 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
4980 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
4981 				rc, shdr_status, shdr_add_status);
4982 		rc = -ENXIO;
4983 		goto out_free_mboxq;
4984 	}
4985 	cntl_attr = &mbx_cntl_attr->cntl_attr;
4986 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
4987 	phba->sli4_hba.lnk_info.lnk_tp =
4988 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
4989 	phba->sli4_hba.lnk_info.lnk_no =
4990 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
4991 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4992 			"3086 lnk_type:%d, lnk_numb:%d\n",
4993 			phba->sli4_hba.lnk_info.lnk_tp,
4994 			phba->sli4_hba.lnk_info.lnk_no);
4995 
4996 retrieve_ppname:
4997 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
4998 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
4999 		sizeof(struct lpfc_mbx_get_port_name) -
5000 		sizeof(struct lpfc_sli4_cfg_mhdr),
5001 		LPFC_SLI4_MBX_EMBED);
5002 	get_port_name = &mboxq->u.mqe.un.get_port_name;
5003 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5004 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
5005 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
5006 		phba->sli4_hba.lnk_info.lnk_tp);
5007 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5008 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5009 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5010 	if (shdr_status || shdr_add_status || rc) {
5011 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5012 				"3087 Mailbox x%x (x%x/x%x) failed: "
5013 				"rc:x%x, status:x%x, add_status:x%x\n",
5014 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5015 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5016 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5017 				rc, shdr_status, shdr_add_status);
5018 		rc = -ENXIO;
5019 		goto out_free_mboxq;
5020 	}
5021 	switch (phba->sli4_hba.lnk_info.lnk_no) {
5022 	case LPFC_LINK_NUMBER_0:
5023 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
5024 				&get_port_name->u.response);
5025 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5026 		break;
5027 	case LPFC_LINK_NUMBER_1:
5028 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
5029 				&get_port_name->u.response);
5030 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5031 		break;
5032 	case LPFC_LINK_NUMBER_2:
5033 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
5034 				&get_port_name->u.response);
5035 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5036 		break;
5037 	case LPFC_LINK_NUMBER_3:
5038 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
5039 				&get_port_name->u.response);
5040 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5041 		break;
5042 	default:
5043 		break;
5044 	}
5045 
5046 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
5047 		phba->Port[0] = cport_name;
5048 		phba->Port[1] = '\0';
5049 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5050 				"3091 SLI get port name: %s\n", phba->Port);
5051 	}
5052 
5053 out_free_mboxq:
5054 	if (rc != MBX_TIMEOUT) {
5055 		if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5056 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
5057 		else
5058 			mempool_free(mboxq, phba->mbox_mem_pool);
5059 	}
5060 	return rc;
5061 }
5062 
5063 /**
5064  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
5065  * @phba: pointer to lpfc hba data structure.
5066  *
5067  * This routine is called to explicitly arm the SLI4 device's completion and
5068  * event queues
5069  **/
5070 static void
5071 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
5072 {
5073 	int fcp_eqidx;
5074 
5075 	lpfc_sli4_cq_release(phba->sli4_hba.mbx_cq, LPFC_QUEUE_REARM);
5076 	lpfc_sli4_cq_release(phba->sli4_hba.els_cq, LPFC_QUEUE_REARM);
5077 	fcp_eqidx = 0;
5078 	if (phba->sli4_hba.fcp_cq) {
5079 		do {
5080 			lpfc_sli4_cq_release(phba->sli4_hba.fcp_cq[fcp_eqidx],
5081 					     LPFC_QUEUE_REARM);
5082 		} while (++fcp_eqidx < phba->cfg_fcp_io_channel);
5083 	}
5084 
5085 	if (phba->cfg_fof)
5086 		lpfc_sli4_cq_release(phba->sli4_hba.oas_cq, LPFC_QUEUE_REARM);
5087 
5088 	if (phba->sli4_hba.hba_eq) {
5089 		for (fcp_eqidx = 0; fcp_eqidx < phba->cfg_fcp_io_channel;
5090 		     fcp_eqidx++)
5091 			lpfc_sli4_eq_release(phba->sli4_hba.hba_eq[fcp_eqidx],
5092 					     LPFC_QUEUE_REARM);
5093 	}
5094 
5095 	if (phba->cfg_fof)
5096 		lpfc_sli4_eq_release(phba->sli4_hba.fof_eq, LPFC_QUEUE_REARM);
5097 }
5098 
5099 /**
5100  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
5101  * @phba: Pointer to HBA context object.
5102  * @type: The resource extent type.
5103  * @extnt_count: buffer to hold port available extent count.
5104  * @extnt_size: buffer to hold element count per extent.
5105  *
5106  * This function calls the port and retrievs the number of available
5107  * extents and their size for a particular extent type.
5108  *
5109  * Returns: 0 if successful.  Nonzero otherwise.
5110  **/
5111 int
5112 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
5113 			       uint16_t *extnt_count, uint16_t *extnt_size)
5114 {
5115 	int rc = 0;
5116 	uint32_t length;
5117 	uint32_t mbox_tmo;
5118 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
5119 	LPFC_MBOXQ_t *mbox;
5120 
5121 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5122 	if (!mbox)
5123 		return -ENOMEM;
5124 
5125 	/* Find out how many extents are available for this resource type */
5126 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
5127 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5128 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5129 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
5130 			 length, LPFC_SLI4_MBX_EMBED);
5131 
5132 	/* Send an extents count of 0 - the GET doesn't use it. */
5133 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5134 					LPFC_SLI4_MBX_EMBED);
5135 	if (unlikely(rc)) {
5136 		rc = -EIO;
5137 		goto err_exit;
5138 	}
5139 
5140 	if (!phba->sli4_hba.intr_enable)
5141 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5142 	else {
5143 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5144 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5145 	}
5146 	if (unlikely(rc)) {
5147 		rc = -EIO;
5148 		goto err_exit;
5149 	}
5150 
5151 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
5152 	if (bf_get(lpfc_mbox_hdr_status,
5153 		   &rsrc_info->header.cfg_shdr.response)) {
5154 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5155 				"2930 Failed to get resource extents "
5156 				"Status 0x%x Add'l Status 0x%x\n",
5157 				bf_get(lpfc_mbox_hdr_status,
5158 				       &rsrc_info->header.cfg_shdr.response),
5159 				bf_get(lpfc_mbox_hdr_add_status,
5160 				       &rsrc_info->header.cfg_shdr.response));
5161 		rc = -EIO;
5162 		goto err_exit;
5163 	}
5164 
5165 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
5166 			      &rsrc_info->u.rsp);
5167 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
5168 			     &rsrc_info->u.rsp);
5169 
5170 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5171 			"3162 Retrieved extents type-%d from port: count:%d, "
5172 			"size:%d\n", type, *extnt_count, *extnt_size);
5173 
5174 err_exit:
5175 	mempool_free(mbox, phba->mbox_mem_pool);
5176 	return rc;
5177 }
5178 
5179 /**
5180  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
5181  * @phba: Pointer to HBA context object.
5182  * @type: The extent type to check.
5183  *
5184  * This function reads the current available extents from the port and checks
5185  * if the extent count or extent size has changed since the last access.
5186  * Callers use this routine post port reset to understand if there is a
5187  * extent reprovisioning requirement.
5188  *
5189  * Returns:
5190  *   -Error: error indicates problem.
5191  *   1: Extent count or size has changed.
5192  *   0: No changes.
5193  **/
5194 static int
5195 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
5196 {
5197 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
5198 	uint16_t size_diff, rsrc_ext_size;
5199 	int rc = 0;
5200 	struct lpfc_rsrc_blks *rsrc_entry;
5201 	struct list_head *rsrc_blk_list = NULL;
5202 
5203 	size_diff = 0;
5204 	curr_ext_cnt = 0;
5205 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5206 					    &rsrc_ext_cnt,
5207 					    &rsrc_ext_size);
5208 	if (unlikely(rc))
5209 		return -EIO;
5210 
5211 	switch (type) {
5212 	case LPFC_RSC_TYPE_FCOE_RPI:
5213 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5214 		break;
5215 	case LPFC_RSC_TYPE_FCOE_VPI:
5216 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
5217 		break;
5218 	case LPFC_RSC_TYPE_FCOE_XRI:
5219 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5220 		break;
5221 	case LPFC_RSC_TYPE_FCOE_VFI:
5222 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5223 		break;
5224 	default:
5225 		break;
5226 	}
5227 
5228 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
5229 		curr_ext_cnt++;
5230 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
5231 			size_diff++;
5232 	}
5233 
5234 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
5235 		rc = 1;
5236 
5237 	return rc;
5238 }
5239 
5240 /**
5241  * lpfc_sli4_cfg_post_extnts -
5242  * @phba: Pointer to HBA context object.
5243  * @extnt_cnt - number of available extents.
5244  * @type - the extent type (rpi, xri, vfi, vpi).
5245  * @emb - buffer to hold either MBX_EMBED or MBX_NEMBED operation.
5246  * @mbox - pointer to the caller's allocated mailbox structure.
5247  *
5248  * This function executes the extents allocation request.  It also
5249  * takes care of the amount of memory needed to allocate or get the
5250  * allocated extents. It is the caller's responsibility to evaluate
5251  * the response.
5252  *
5253  * Returns:
5254  *   -Error:  Error value describes the condition found.
5255  *   0: if successful
5256  **/
5257 static int
5258 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
5259 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
5260 {
5261 	int rc = 0;
5262 	uint32_t req_len;
5263 	uint32_t emb_len;
5264 	uint32_t alloc_len, mbox_tmo;
5265 
5266 	/* Calculate the total requested length of the dma memory */
5267 	req_len = extnt_cnt * sizeof(uint16_t);
5268 
5269 	/*
5270 	 * Calculate the size of an embedded mailbox.  The uint32_t
5271 	 * accounts for extents-specific word.
5272 	 */
5273 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
5274 		sizeof(uint32_t);
5275 
5276 	/*
5277 	 * Presume the allocation and response will fit into an embedded
5278 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
5279 	 */
5280 	*emb = LPFC_SLI4_MBX_EMBED;
5281 	if (req_len > emb_len) {
5282 		req_len = extnt_cnt * sizeof(uint16_t) +
5283 			sizeof(union lpfc_sli4_cfg_shdr) +
5284 			sizeof(uint32_t);
5285 		*emb = LPFC_SLI4_MBX_NEMBED;
5286 	}
5287 
5288 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5289 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
5290 				     req_len, *emb);
5291 	if (alloc_len < req_len) {
5292 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5293 			"2982 Allocated DMA memory size (x%x) is "
5294 			"less than the requested DMA memory "
5295 			"size (x%x)\n", alloc_len, req_len);
5296 		return -ENOMEM;
5297 	}
5298 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
5299 	if (unlikely(rc))
5300 		return -EIO;
5301 
5302 	if (!phba->sli4_hba.intr_enable)
5303 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5304 	else {
5305 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5306 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5307 	}
5308 
5309 	if (unlikely(rc))
5310 		rc = -EIO;
5311 	return rc;
5312 }
5313 
5314 /**
5315  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
5316  * @phba: Pointer to HBA context object.
5317  * @type:  The resource extent type to allocate.
5318  *
5319  * This function allocates the number of elements for the specified
5320  * resource type.
5321  **/
5322 static int
5323 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
5324 {
5325 	bool emb = false;
5326 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
5327 	uint16_t rsrc_id, rsrc_start, j, k;
5328 	uint16_t *ids;
5329 	int i, rc;
5330 	unsigned long longs;
5331 	unsigned long *bmask;
5332 	struct lpfc_rsrc_blks *rsrc_blks;
5333 	LPFC_MBOXQ_t *mbox;
5334 	uint32_t length;
5335 	struct lpfc_id_range *id_array = NULL;
5336 	void *virtaddr = NULL;
5337 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
5338 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
5339 	struct list_head *ext_blk_list;
5340 
5341 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5342 					    &rsrc_cnt,
5343 					    &rsrc_size);
5344 	if (unlikely(rc))
5345 		return -EIO;
5346 
5347 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
5348 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5349 			"3009 No available Resource Extents "
5350 			"for resource type 0x%x: Count: 0x%x, "
5351 			"Size 0x%x\n", type, rsrc_cnt,
5352 			rsrc_size);
5353 		return -ENOMEM;
5354 	}
5355 
5356 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
5357 			"2903 Post resource extents type-0x%x: "
5358 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
5359 
5360 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5361 	if (!mbox)
5362 		return -ENOMEM;
5363 
5364 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
5365 	if (unlikely(rc)) {
5366 		rc = -EIO;
5367 		goto err_exit;
5368 	}
5369 
5370 	/*
5371 	 * Figure out where the response is located.  Then get local pointers
5372 	 * to the response data.  The port does not guarantee to respond to
5373 	 * all extents counts request so update the local variable with the
5374 	 * allocated count from the port.
5375 	 */
5376 	if (emb == LPFC_SLI4_MBX_EMBED) {
5377 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
5378 		id_array = &rsrc_ext->u.rsp.id[0];
5379 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
5380 	} else {
5381 		virtaddr = mbox->sge_array->addr[0];
5382 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
5383 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
5384 		id_array = &n_rsrc->id;
5385 	}
5386 
5387 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
5388 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
5389 
5390 	/*
5391 	 * Based on the resource size and count, correct the base and max
5392 	 * resource values.
5393 	 */
5394 	length = sizeof(struct lpfc_rsrc_blks);
5395 	switch (type) {
5396 	case LPFC_RSC_TYPE_FCOE_RPI:
5397 		phba->sli4_hba.rpi_bmask = kzalloc(longs *
5398 						   sizeof(unsigned long),
5399 						   GFP_KERNEL);
5400 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
5401 			rc = -ENOMEM;
5402 			goto err_exit;
5403 		}
5404 		phba->sli4_hba.rpi_ids = kzalloc(rsrc_id_cnt *
5405 						 sizeof(uint16_t),
5406 						 GFP_KERNEL);
5407 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
5408 			kfree(phba->sli4_hba.rpi_bmask);
5409 			rc = -ENOMEM;
5410 			goto err_exit;
5411 		}
5412 
5413 		/*
5414 		 * The next_rpi was initialized with the maximum available
5415 		 * count but the port may allocate a smaller number.  Catch
5416 		 * that case and update the next_rpi.
5417 		 */
5418 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
5419 
5420 		/* Initialize local ptrs for common extent processing later. */
5421 		bmask = phba->sli4_hba.rpi_bmask;
5422 		ids = phba->sli4_hba.rpi_ids;
5423 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5424 		break;
5425 	case LPFC_RSC_TYPE_FCOE_VPI:
5426 		phba->vpi_bmask = kzalloc(longs *
5427 					  sizeof(unsigned long),
5428 					  GFP_KERNEL);
5429 		if (unlikely(!phba->vpi_bmask)) {
5430 			rc = -ENOMEM;
5431 			goto err_exit;
5432 		}
5433 		phba->vpi_ids = kzalloc(rsrc_id_cnt *
5434 					 sizeof(uint16_t),
5435 					 GFP_KERNEL);
5436 		if (unlikely(!phba->vpi_ids)) {
5437 			kfree(phba->vpi_bmask);
5438 			rc = -ENOMEM;
5439 			goto err_exit;
5440 		}
5441 
5442 		/* Initialize local ptrs for common extent processing later. */
5443 		bmask = phba->vpi_bmask;
5444 		ids = phba->vpi_ids;
5445 		ext_blk_list = &phba->lpfc_vpi_blk_list;
5446 		break;
5447 	case LPFC_RSC_TYPE_FCOE_XRI:
5448 		phba->sli4_hba.xri_bmask = kzalloc(longs *
5449 						   sizeof(unsigned long),
5450 						   GFP_KERNEL);
5451 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
5452 			rc = -ENOMEM;
5453 			goto err_exit;
5454 		}
5455 		phba->sli4_hba.max_cfg_param.xri_used = 0;
5456 		phba->sli4_hba.xri_ids = kzalloc(rsrc_id_cnt *
5457 						 sizeof(uint16_t),
5458 						 GFP_KERNEL);
5459 		if (unlikely(!phba->sli4_hba.xri_ids)) {
5460 			kfree(phba->sli4_hba.xri_bmask);
5461 			rc = -ENOMEM;
5462 			goto err_exit;
5463 		}
5464 
5465 		/* Initialize local ptrs for common extent processing later. */
5466 		bmask = phba->sli4_hba.xri_bmask;
5467 		ids = phba->sli4_hba.xri_ids;
5468 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5469 		break;
5470 	case LPFC_RSC_TYPE_FCOE_VFI:
5471 		phba->sli4_hba.vfi_bmask = kzalloc(longs *
5472 						   sizeof(unsigned long),
5473 						   GFP_KERNEL);
5474 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
5475 			rc = -ENOMEM;
5476 			goto err_exit;
5477 		}
5478 		phba->sli4_hba.vfi_ids = kzalloc(rsrc_id_cnt *
5479 						 sizeof(uint16_t),
5480 						 GFP_KERNEL);
5481 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
5482 			kfree(phba->sli4_hba.vfi_bmask);
5483 			rc = -ENOMEM;
5484 			goto err_exit;
5485 		}
5486 
5487 		/* Initialize local ptrs for common extent processing later. */
5488 		bmask = phba->sli4_hba.vfi_bmask;
5489 		ids = phba->sli4_hba.vfi_ids;
5490 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5491 		break;
5492 	default:
5493 		/* Unsupported Opcode.  Fail call. */
5494 		id_array = NULL;
5495 		bmask = NULL;
5496 		ids = NULL;
5497 		ext_blk_list = NULL;
5498 		goto err_exit;
5499 	}
5500 
5501 	/*
5502 	 * Complete initializing the extent configuration with the
5503 	 * allocated ids assigned to this function.  The bitmask serves
5504 	 * as an index into the array and manages the available ids.  The
5505 	 * array just stores the ids communicated to the port via the wqes.
5506 	 */
5507 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
5508 		if ((i % 2) == 0)
5509 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
5510 					 &id_array[k]);
5511 		else
5512 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
5513 					 &id_array[k]);
5514 
5515 		rsrc_blks = kzalloc(length, GFP_KERNEL);
5516 		if (unlikely(!rsrc_blks)) {
5517 			rc = -ENOMEM;
5518 			kfree(bmask);
5519 			kfree(ids);
5520 			goto err_exit;
5521 		}
5522 		rsrc_blks->rsrc_start = rsrc_id;
5523 		rsrc_blks->rsrc_size = rsrc_size;
5524 		list_add_tail(&rsrc_blks->list, ext_blk_list);
5525 		rsrc_start = rsrc_id;
5526 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0))
5527 			phba->sli4_hba.scsi_xri_start = rsrc_start +
5528 				lpfc_sli4_get_els_iocb_cnt(phba);
5529 
5530 		while (rsrc_id < (rsrc_start + rsrc_size)) {
5531 			ids[j] = rsrc_id;
5532 			rsrc_id++;
5533 			j++;
5534 		}
5535 		/* Entire word processed.  Get next word.*/
5536 		if ((i % 2) == 1)
5537 			k++;
5538 	}
5539  err_exit:
5540 	lpfc_sli4_mbox_cmd_free(phba, mbox);
5541 	return rc;
5542 }
5543 
5544 /**
5545  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
5546  * @phba: Pointer to HBA context object.
5547  * @type: the extent's type.
5548  *
5549  * This function deallocates all extents of a particular resource type.
5550  * SLI4 does not allow for deallocating a particular extent range.  It
5551  * is the caller's responsibility to release all kernel memory resources.
5552  **/
5553 static int
5554 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
5555 {
5556 	int rc;
5557 	uint32_t length, mbox_tmo = 0;
5558 	LPFC_MBOXQ_t *mbox;
5559 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
5560 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
5561 
5562 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5563 	if (!mbox)
5564 		return -ENOMEM;
5565 
5566 	/*
5567 	 * This function sends an embedded mailbox because it only sends the
5568 	 * the resource type.  All extents of this type are released by the
5569 	 * port.
5570 	 */
5571 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
5572 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5573 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5574 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
5575 			 length, LPFC_SLI4_MBX_EMBED);
5576 
5577 	/* Send an extents count of 0 - the dealloc doesn't use it. */
5578 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5579 					LPFC_SLI4_MBX_EMBED);
5580 	if (unlikely(rc)) {
5581 		rc = -EIO;
5582 		goto out_free_mbox;
5583 	}
5584 	if (!phba->sli4_hba.intr_enable)
5585 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5586 	else {
5587 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5588 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5589 	}
5590 	if (unlikely(rc)) {
5591 		rc = -EIO;
5592 		goto out_free_mbox;
5593 	}
5594 
5595 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
5596 	if (bf_get(lpfc_mbox_hdr_status,
5597 		   &dealloc_rsrc->header.cfg_shdr.response)) {
5598 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5599 				"2919 Failed to release resource extents "
5600 				"for type %d - Status 0x%x Add'l Status 0x%x. "
5601 				"Resource memory not released.\n",
5602 				type,
5603 				bf_get(lpfc_mbox_hdr_status,
5604 				    &dealloc_rsrc->header.cfg_shdr.response),
5605 				bf_get(lpfc_mbox_hdr_add_status,
5606 				    &dealloc_rsrc->header.cfg_shdr.response));
5607 		rc = -EIO;
5608 		goto out_free_mbox;
5609 	}
5610 
5611 	/* Release kernel memory resources for the specific type. */
5612 	switch (type) {
5613 	case LPFC_RSC_TYPE_FCOE_VPI:
5614 		kfree(phba->vpi_bmask);
5615 		kfree(phba->vpi_ids);
5616 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5617 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5618 				    &phba->lpfc_vpi_blk_list, list) {
5619 			list_del_init(&rsrc_blk->list);
5620 			kfree(rsrc_blk);
5621 		}
5622 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
5623 		break;
5624 	case LPFC_RSC_TYPE_FCOE_XRI:
5625 		kfree(phba->sli4_hba.xri_bmask);
5626 		kfree(phba->sli4_hba.xri_ids);
5627 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5628 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
5629 			list_del_init(&rsrc_blk->list);
5630 			kfree(rsrc_blk);
5631 		}
5632 		break;
5633 	case LPFC_RSC_TYPE_FCOE_VFI:
5634 		kfree(phba->sli4_hba.vfi_bmask);
5635 		kfree(phba->sli4_hba.vfi_ids);
5636 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5637 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5638 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
5639 			list_del_init(&rsrc_blk->list);
5640 			kfree(rsrc_blk);
5641 		}
5642 		break;
5643 	case LPFC_RSC_TYPE_FCOE_RPI:
5644 		/* RPI bitmask and physical id array are cleaned up earlier. */
5645 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5646 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
5647 			list_del_init(&rsrc_blk->list);
5648 			kfree(rsrc_blk);
5649 		}
5650 		break;
5651 	default:
5652 		break;
5653 	}
5654 
5655 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5656 
5657  out_free_mbox:
5658 	mempool_free(mbox, phba->mbox_mem_pool);
5659 	return rc;
5660 }
5661 
5662 /**
5663  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
5664  * @phba: Pointer to HBA context object.
5665  *
5666  * This function allocates all SLI4 resource identifiers.
5667  **/
5668 int
5669 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
5670 {
5671 	int i, rc, error = 0;
5672 	uint16_t count, base;
5673 	unsigned long longs;
5674 
5675 	if (!phba->sli4_hba.rpi_hdrs_in_use)
5676 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
5677 	if (phba->sli4_hba.extents_in_use) {
5678 		/*
5679 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
5680 		 * resource extent count must be read and allocated before
5681 		 * provisioning the resource id arrays.
5682 		 */
5683 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
5684 		    LPFC_IDX_RSRC_RDY) {
5685 			/*
5686 			 * Extent-based resources are set - the driver could
5687 			 * be in a port reset. Figure out if any corrective
5688 			 * actions need to be taken.
5689 			 */
5690 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5691 						 LPFC_RSC_TYPE_FCOE_VFI);
5692 			if (rc != 0)
5693 				error++;
5694 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5695 						 LPFC_RSC_TYPE_FCOE_VPI);
5696 			if (rc != 0)
5697 				error++;
5698 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5699 						 LPFC_RSC_TYPE_FCOE_XRI);
5700 			if (rc != 0)
5701 				error++;
5702 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5703 						 LPFC_RSC_TYPE_FCOE_RPI);
5704 			if (rc != 0)
5705 				error++;
5706 
5707 			/*
5708 			 * It's possible that the number of resources
5709 			 * provided to this port instance changed between
5710 			 * resets.  Detect this condition and reallocate
5711 			 * resources.  Otherwise, there is no action.
5712 			 */
5713 			if (error) {
5714 				lpfc_printf_log(phba, KERN_INFO,
5715 						LOG_MBOX | LOG_INIT,
5716 						"2931 Detected extent resource "
5717 						"change.  Reallocating all "
5718 						"extents.\n");
5719 				rc = lpfc_sli4_dealloc_extent(phba,
5720 						 LPFC_RSC_TYPE_FCOE_VFI);
5721 				rc = lpfc_sli4_dealloc_extent(phba,
5722 						 LPFC_RSC_TYPE_FCOE_VPI);
5723 				rc = lpfc_sli4_dealloc_extent(phba,
5724 						 LPFC_RSC_TYPE_FCOE_XRI);
5725 				rc = lpfc_sli4_dealloc_extent(phba,
5726 						 LPFC_RSC_TYPE_FCOE_RPI);
5727 			} else
5728 				return 0;
5729 		}
5730 
5731 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
5732 		if (unlikely(rc))
5733 			goto err_exit;
5734 
5735 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
5736 		if (unlikely(rc))
5737 			goto err_exit;
5738 
5739 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
5740 		if (unlikely(rc))
5741 			goto err_exit;
5742 
5743 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
5744 		if (unlikely(rc))
5745 			goto err_exit;
5746 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
5747 		       LPFC_IDX_RSRC_RDY);
5748 		return rc;
5749 	} else {
5750 		/*
5751 		 * The port does not support resource extents.  The XRI, VPI,
5752 		 * VFI, RPI resource ids were determined from READ_CONFIG.
5753 		 * Just allocate the bitmasks and provision the resource id
5754 		 * arrays.  If a port reset is active, the resources don't
5755 		 * need any action - just exit.
5756 		 */
5757 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
5758 		    LPFC_IDX_RSRC_RDY) {
5759 			lpfc_sli4_dealloc_resource_identifiers(phba);
5760 			lpfc_sli4_remove_rpis(phba);
5761 		}
5762 		/* RPIs. */
5763 		count = phba->sli4_hba.max_cfg_param.max_rpi;
5764 		if (count <= 0) {
5765 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5766 					"3279 Invalid provisioning of "
5767 					"rpi:%d\n", count);
5768 			rc = -EINVAL;
5769 			goto err_exit;
5770 		}
5771 		base = phba->sli4_hba.max_cfg_param.rpi_base;
5772 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5773 		phba->sli4_hba.rpi_bmask = kzalloc(longs *
5774 						   sizeof(unsigned long),
5775 						   GFP_KERNEL);
5776 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
5777 			rc = -ENOMEM;
5778 			goto err_exit;
5779 		}
5780 		phba->sli4_hba.rpi_ids = kzalloc(count *
5781 						 sizeof(uint16_t),
5782 						 GFP_KERNEL);
5783 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
5784 			rc = -ENOMEM;
5785 			goto free_rpi_bmask;
5786 		}
5787 
5788 		for (i = 0; i < count; i++)
5789 			phba->sli4_hba.rpi_ids[i] = base + i;
5790 
5791 		/* VPIs. */
5792 		count = phba->sli4_hba.max_cfg_param.max_vpi;
5793 		if (count <= 0) {
5794 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5795 					"3280 Invalid provisioning of "
5796 					"vpi:%d\n", count);
5797 			rc = -EINVAL;
5798 			goto free_rpi_ids;
5799 		}
5800 		base = phba->sli4_hba.max_cfg_param.vpi_base;
5801 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5802 		phba->vpi_bmask = kzalloc(longs *
5803 					  sizeof(unsigned long),
5804 					  GFP_KERNEL);
5805 		if (unlikely(!phba->vpi_bmask)) {
5806 			rc = -ENOMEM;
5807 			goto free_rpi_ids;
5808 		}
5809 		phba->vpi_ids = kzalloc(count *
5810 					sizeof(uint16_t),
5811 					GFP_KERNEL);
5812 		if (unlikely(!phba->vpi_ids)) {
5813 			rc = -ENOMEM;
5814 			goto free_vpi_bmask;
5815 		}
5816 
5817 		for (i = 0; i < count; i++)
5818 			phba->vpi_ids[i] = base + i;
5819 
5820 		/* XRIs. */
5821 		count = phba->sli4_hba.max_cfg_param.max_xri;
5822 		if (count <= 0) {
5823 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5824 					"3281 Invalid provisioning of "
5825 					"xri:%d\n", count);
5826 			rc = -EINVAL;
5827 			goto free_vpi_ids;
5828 		}
5829 		base = phba->sli4_hba.max_cfg_param.xri_base;
5830 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5831 		phba->sli4_hba.xri_bmask = kzalloc(longs *
5832 						   sizeof(unsigned long),
5833 						   GFP_KERNEL);
5834 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
5835 			rc = -ENOMEM;
5836 			goto free_vpi_ids;
5837 		}
5838 		phba->sli4_hba.max_cfg_param.xri_used = 0;
5839 		phba->sli4_hba.xri_ids = kzalloc(count *
5840 						 sizeof(uint16_t),
5841 						 GFP_KERNEL);
5842 		if (unlikely(!phba->sli4_hba.xri_ids)) {
5843 			rc = -ENOMEM;
5844 			goto free_xri_bmask;
5845 		}
5846 
5847 		for (i = 0; i < count; i++)
5848 			phba->sli4_hba.xri_ids[i] = base + i;
5849 
5850 		/* VFIs. */
5851 		count = phba->sli4_hba.max_cfg_param.max_vfi;
5852 		if (count <= 0) {
5853 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5854 					"3282 Invalid provisioning of "
5855 					"vfi:%d\n", count);
5856 			rc = -EINVAL;
5857 			goto free_xri_ids;
5858 		}
5859 		base = phba->sli4_hba.max_cfg_param.vfi_base;
5860 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5861 		phba->sli4_hba.vfi_bmask = kzalloc(longs *
5862 						   sizeof(unsigned long),
5863 						   GFP_KERNEL);
5864 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
5865 			rc = -ENOMEM;
5866 			goto free_xri_ids;
5867 		}
5868 		phba->sli4_hba.vfi_ids = kzalloc(count *
5869 						 sizeof(uint16_t),
5870 						 GFP_KERNEL);
5871 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
5872 			rc = -ENOMEM;
5873 			goto free_vfi_bmask;
5874 		}
5875 
5876 		for (i = 0; i < count; i++)
5877 			phba->sli4_hba.vfi_ids[i] = base + i;
5878 
5879 		/*
5880 		 * Mark all resources ready.  An HBA reset doesn't need
5881 		 * to reset the initialization.
5882 		 */
5883 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
5884 		       LPFC_IDX_RSRC_RDY);
5885 		return 0;
5886 	}
5887 
5888  free_vfi_bmask:
5889 	kfree(phba->sli4_hba.vfi_bmask);
5890  free_xri_ids:
5891 	kfree(phba->sli4_hba.xri_ids);
5892  free_xri_bmask:
5893 	kfree(phba->sli4_hba.xri_bmask);
5894  free_vpi_ids:
5895 	kfree(phba->vpi_ids);
5896  free_vpi_bmask:
5897 	kfree(phba->vpi_bmask);
5898  free_rpi_ids:
5899 	kfree(phba->sli4_hba.rpi_ids);
5900  free_rpi_bmask:
5901 	kfree(phba->sli4_hba.rpi_bmask);
5902  err_exit:
5903 	return rc;
5904 }
5905 
5906 /**
5907  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
5908  * @phba: Pointer to HBA context object.
5909  *
5910  * This function allocates the number of elements for the specified
5911  * resource type.
5912  **/
5913 int
5914 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
5915 {
5916 	if (phba->sli4_hba.extents_in_use) {
5917 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
5918 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
5919 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
5920 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
5921 	} else {
5922 		kfree(phba->vpi_bmask);
5923 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
5924 		kfree(phba->vpi_ids);
5925 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5926 		kfree(phba->sli4_hba.xri_bmask);
5927 		kfree(phba->sli4_hba.xri_ids);
5928 		kfree(phba->sli4_hba.vfi_bmask);
5929 		kfree(phba->sli4_hba.vfi_ids);
5930 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5931 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5932 	}
5933 
5934 	return 0;
5935 }
5936 
5937 /**
5938  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
5939  * @phba: Pointer to HBA context object.
5940  * @type: The resource extent type.
5941  * @extnt_count: buffer to hold port extent count response
5942  * @extnt_size: buffer to hold port extent size response.
5943  *
5944  * This function calls the port to read the host allocated extents
5945  * for a particular type.
5946  **/
5947 int
5948 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
5949 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
5950 {
5951 	bool emb;
5952 	int rc = 0;
5953 	uint16_t curr_blks = 0;
5954 	uint32_t req_len, emb_len;
5955 	uint32_t alloc_len, mbox_tmo;
5956 	struct list_head *blk_list_head;
5957 	struct lpfc_rsrc_blks *rsrc_blk;
5958 	LPFC_MBOXQ_t *mbox;
5959 	void *virtaddr = NULL;
5960 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
5961 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
5962 	union  lpfc_sli4_cfg_shdr *shdr;
5963 
5964 	switch (type) {
5965 	case LPFC_RSC_TYPE_FCOE_VPI:
5966 		blk_list_head = &phba->lpfc_vpi_blk_list;
5967 		break;
5968 	case LPFC_RSC_TYPE_FCOE_XRI:
5969 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
5970 		break;
5971 	case LPFC_RSC_TYPE_FCOE_VFI:
5972 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
5973 		break;
5974 	case LPFC_RSC_TYPE_FCOE_RPI:
5975 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
5976 		break;
5977 	default:
5978 		return -EIO;
5979 	}
5980 
5981 	/* Count the number of extents currently allocatd for this type. */
5982 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
5983 		if (curr_blks == 0) {
5984 			/*
5985 			 * The GET_ALLOCATED mailbox does not return the size,
5986 			 * just the count.  The size should be just the size
5987 			 * stored in the current allocated block and all sizes
5988 			 * for an extent type are the same so set the return
5989 			 * value now.
5990 			 */
5991 			*extnt_size = rsrc_blk->rsrc_size;
5992 		}
5993 		curr_blks++;
5994 	}
5995 
5996 	/*
5997 	 * Calculate the size of an embedded mailbox.  The uint32_t
5998 	 * accounts for extents-specific word.
5999 	 */
6000 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6001 		sizeof(uint32_t);
6002 
6003 	/*
6004 	 * Presume the allocation and response will fit into an embedded
6005 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6006 	 */
6007 	emb = LPFC_SLI4_MBX_EMBED;
6008 	req_len = emb_len;
6009 	if (req_len > emb_len) {
6010 		req_len = curr_blks * sizeof(uint16_t) +
6011 			sizeof(union lpfc_sli4_cfg_shdr) +
6012 			sizeof(uint32_t);
6013 		emb = LPFC_SLI4_MBX_NEMBED;
6014 	}
6015 
6016 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6017 	if (!mbox)
6018 		return -ENOMEM;
6019 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
6020 
6021 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6022 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
6023 				     req_len, emb);
6024 	if (alloc_len < req_len) {
6025 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6026 			"2983 Allocated DMA memory size (x%x) is "
6027 			"less than the requested DMA memory "
6028 			"size (x%x)\n", alloc_len, req_len);
6029 		rc = -ENOMEM;
6030 		goto err_exit;
6031 	}
6032 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
6033 	if (unlikely(rc)) {
6034 		rc = -EIO;
6035 		goto err_exit;
6036 	}
6037 
6038 	if (!phba->sli4_hba.intr_enable)
6039 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6040 	else {
6041 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6042 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6043 	}
6044 
6045 	if (unlikely(rc)) {
6046 		rc = -EIO;
6047 		goto err_exit;
6048 	}
6049 
6050 	/*
6051 	 * Figure out where the response is located.  Then get local pointers
6052 	 * to the response data.  The port does not guarantee to respond to
6053 	 * all extents counts request so update the local variable with the
6054 	 * allocated count from the port.
6055 	 */
6056 	if (emb == LPFC_SLI4_MBX_EMBED) {
6057 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6058 		shdr = &rsrc_ext->header.cfg_shdr;
6059 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6060 	} else {
6061 		virtaddr = mbox->sge_array->addr[0];
6062 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6063 		shdr = &n_rsrc->cfg_shdr;
6064 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6065 	}
6066 
6067 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
6068 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
6069 			"2984 Failed to read allocated resources "
6070 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
6071 			type,
6072 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
6073 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
6074 		rc = -EIO;
6075 		goto err_exit;
6076 	}
6077  err_exit:
6078 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6079 	return rc;
6080 }
6081 
6082 /**
6083  * lpfc_sli4_repost_els_sgl_list - Repsot the els buffers sgl pages as block
6084  * @phba: pointer to lpfc hba data structure.
6085  *
6086  * This routine walks the list of els buffers that have been allocated and
6087  * repost them to the port by using SGL block post. This is needed after a
6088  * pci_function_reset/warm_start or start. It attempts to construct blocks
6089  * of els buffer sgls which contains contiguous xris and uses the non-embedded
6090  * SGL block post mailbox commands to post them to the port. For single els
6091  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
6092  * mailbox command for posting.
6093  *
6094  * Returns: 0 = success, non-zero failure.
6095  **/
6096 static int
6097 lpfc_sli4_repost_els_sgl_list(struct lpfc_hba *phba)
6098 {
6099 	struct lpfc_sglq *sglq_entry = NULL;
6100 	struct lpfc_sglq *sglq_entry_next = NULL;
6101 	struct lpfc_sglq *sglq_entry_first = NULL;
6102 	int status, total_cnt, post_cnt = 0, num_posted = 0, block_cnt = 0;
6103 	int last_xritag = NO_XRI;
6104 	struct lpfc_sli_ring *pring;
6105 	LIST_HEAD(prep_sgl_list);
6106 	LIST_HEAD(blck_sgl_list);
6107 	LIST_HEAD(allc_sgl_list);
6108 	LIST_HEAD(post_sgl_list);
6109 	LIST_HEAD(free_sgl_list);
6110 
6111 	pring = &phba->sli.ring[LPFC_ELS_RING];
6112 	spin_lock_irq(&phba->hbalock);
6113 	spin_lock(&pring->ring_lock);
6114 	list_splice_init(&phba->sli4_hba.lpfc_sgl_list, &allc_sgl_list);
6115 	spin_unlock(&pring->ring_lock);
6116 	spin_unlock_irq(&phba->hbalock);
6117 
6118 	total_cnt = phba->sli4_hba.els_xri_cnt;
6119 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
6120 				 &allc_sgl_list, list) {
6121 		list_del_init(&sglq_entry->list);
6122 		block_cnt++;
6123 		if ((last_xritag != NO_XRI) &&
6124 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
6125 			/* a hole in xri block, form a sgl posting block */
6126 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
6127 			post_cnt = block_cnt - 1;
6128 			/* prepare list for next posting block */
6129 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6130 			block_cnt = 1;
6131 		} else {
6132 			/* prepare list for next posting block */
6133 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6134 			/* enough sgls for non-embed sgl mbox command */
6135 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
6136 				list_splice_init(&prep_sgl_list,
6137 						 &blck_sgl_list);
6138 				post_cnt = block_cnt;
6139 				block_cnt = 0;
6140 			}
6141 		}
6142 		num_posted++;
6143 
6144 		/* keep track of last sgl's xritag */
6145 		last_xritag = sglq_entry->sli4_xritag;
6146 
6147 		/* end of repost sgl list condition for els buffers */
6148 		if (num_posted == phba->sli4_hba.els_xri_cnt) {
6149 			if (post_cnt == 0) {
6150 				list_splice_init(&prep_sgl_list,
6151 						 &blck_sgl_list);
6152 				post_cnt = block_cnt;
6153 			} else if (block_cnt == 1) {
6154 				status = lpfc_sli4_post_sgl(phba,
6155 						sglq_entry->phys, 0,
6156 						sglq_entry->sli4_xritag);
6157 				if (!status) {
6158 					/* successful, put sgl to posted list */
6159 					list_add_tail(&sglq_entry->list,
6160 						      &post_sgl_list);
6161 				} else {
6162 					/* Failure, put sgl to free list */
6163 					lpfc_printf_log(phba, KERN_WARNING,
6164 						LOG_SLI,
6165 						"3159 Failed to post els "
6166 						"sgl, xritag:x%x\n",
6167 						sglq_entry->sli4_xritag);
6168 					list_add_tail(&sglq_entry->list,
6169 						      &free_sgl_list);
6170 					total_cnt--;
6171 				}
6172 			}
6173 		}
6174 
6175 		/* continue until a nembed page worth of sgls */
6176 		if (post_cnt == 0)
6177 			continue;
6178 
6179 		/* post the els buffer list sgls as a block */
6180 		status = lpfc_sli4_post_els_sgl_list(phba, &blck_sgl_list,
6181 						     post_cnt);
6182 
6183 		if (!status) {
6184 			/* success, put sgl list to posted sgl list */
6185 			list_splice_init(&blck_sgl_list, &post_sgl_list);
6186 		} else {
6187 			/* Failure, put sgl list to free sgl list */
6188 			sglq_entry_first = list_first_entry(&blck_sgl_list,
6189 							    struct lpfc_sglq,
6190 							    list);
6191 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6192 					"3160 Failed to post els sgl-list, "
6193 					"xritag:x%x-x%x\n",
6194 					sglq_entry_first->sli4_xritag,
6195 					(sglq_entry_first->sli4_xritag +
6196 					 post_cnt - 1));
6197 			list_splice_init(&blck_sgl_list, &free_sgl_list);
6198 			total_cnt -= post_cnt;
6199 		}
6200 
6201 		/* don't reset xirtag due to hole in xri block */
6202 		if (block_cnt == 0)
6203 			last_xritag = NO_XRI;
6204 
6205 		/* reset els sgl post count for next round of posting */
6206 		post_cnt = 0;
6207 	}
6208 	/* update the number of XRIs posted for ELS */
6209 	phba->sli4_hba.els_xri_cnt = total_cnt;
6210 
6211 	/* free the els sgls failed to post */
6212 	lpfc_free_sgl_list(phba, &free_sgl_list);
6213 
6214 	/* push els sgls posted to the availble list */
6215 	if (!list_empty(&post_sgl_list)) {
6216 		spin_lock_irq(&phba->hbalock);
6217 		spin_lock(&pring->ring_lock);
6218 		list_splice_init(&post_sgl_list,
6219 				 &phba->sli4_hba.lpfc_sgl_list);
6220 		spin_unlock(&pring->ring_lock);
6221 		spin_unlock_irq(&phba->hbalock);
6222 	} else {
6223 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6224 				"3161 Failure to post els sgl to port.\n");
6225 		return -EIO;
6226 	}
6227 	return 0;
6228 }
6229 
6230 /**
6231  * lpfc_sli4_hba_setup - SLI4 device intialization PCI function
6232  * @phba: Pointer to HBA context object.
6233  *
6234  * This function is the main SLI4 device intialization PCI function. This
6235  * function is called by the HBA intialization code, HBA reset code and
6236  * HBA error attention handler code. Caller is not required to hold any
6237  * locks.
6238  **/
6239 int
6240 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
6241 {
6242 	int rc;
6243 	LPFC_MBOXQ_t *mboxq;
6244 	struct lpfc_mqe *mqe;
6245 	uint8_t *vpd;
6246 	uint32_t vpd_size;
6247 	uint32_t ftr_rsp = 0;
6248 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
6249 	struct lpfc_vport *vport = phba->pport;
6250 	struct lpfc_dmabuf *mp;
6251 
6252 	/* Perform a PCI function reset to start from clean */
6253 	rc = lpfc_pci_function_reset(phba);
6254 	if (unlikely(rc))
6255 		return -ENODEV;
6256 
6257 	/* Check the HBA Host Status Register for readyness */
6258 	rc = lpfc_sli4_post_status_check(phba);
6259 	if (unlikely(rc))
6260 		return -ENODEV;
6261 	else {
6262 		spin_lock_irq(&phba->hbalock);
6263 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
6264 		spin_unlock_irq(&phba->hbalock);
6265 	}
6266 
6267 	/*
6268 	 * Allocate a single mailbox container for initializing the
6269 	 * port.
6270 	 */
6271 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6272 	if (!mboxq)
6273 		return -ENOMEM;
6274 
6275 	/* Issue READ_REV to collect vpd and FW information. */
6276 	vpd_size = SLI4_PAGE_SIZE;
6277 	vpd = kzalloc(vpd_size, GFP_KERNEL);
6278 	if (!vpd) {
6279 		rc = -ENOMEM;
6280 		goto out_free_mbox;
6281 	}
6282 
6283 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
6284 	if (unlikely(rc)) {
6285 		kfree(vpd);
6286 		goto out_free_mbox;
6287 	}
6288 
6289 	mqe = &mboxq->u.mqe;
6290 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
6291 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev))
6292 		phba->hba_flag |= HBA_FCOE_MODE;
6293 	else
6294 		phba->hba_flag &= ~HBA_FCOE_MODE;
6295 
6296 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
6297 		LPFC_DCBX_CEE_MODE)
6298 		phba->hba_flag |= HBA_FIP_SUPPORT;
6299 	else
6300 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
6301 
6302 	phba->hba_flag &= ~HBA_FCP_IOQ_FLUSH;
6303 
6304 	if (phba->sli_rev != LPFC_SLI_REV4) {
6305 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6306 			"0376 READ_REV Error. SLI Level %d "
6307 			"FCoE enabled %d\n",
6308 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
6309 		rc = -EIO;
6310 		kfree(vpd);
6311 		goto out_free_mbox;
6312 	}
6313 
6314 	/*
6315 	 * Continue initialization with default values even if driver failed
6316 	 * to read FCoE param config regions, only read parameters if the
6317 	 * board is FCoE
6318 	 */
6319 	if (phba->hba_flag & HBA_FCOE_MODE &&
6320 	    lpfc_sli4_read_fcoe_params(phba))
6321 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
6322 			"2570 Failed to read FCoE parameters\n");
6323 
6324 	/*
6325 	 * Retrieve sli4 device physical port name, failure of doing it
6326 	 * is considered as non-fatal.
6327 	 */
6328 	rc = lpfc_sli4_retrieve_pport_name(phba);
6329 	if (!rc)
6330 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
6331 				"3080 Successful retrieving SLI4 device "
6332 				"physical port name: %s.\n", phba->Port);
6333 
6334 	/*
6335 	 * Evaluate the read rev and vpd data. Populate the driver
6336 	 * state with the results. If this routine fails, the failure
6337 	 * is not fatal as the driver will use generic values.
6338 	 */
6339 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
6340 	if (unlikely(!rc)) {
6341 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6342 				"0377 Error %d parsing vpd. "
6343 				"Using defaults.\n", rc);
6344 		rc = 0;
6345 	}
6346 	kfree(vpd);
6347 
6348 	/* Save information as VPD data */
6349 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
6350 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
6351 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
6352 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
6353 					 &mqe->un.read_rev);
6354 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
6355 				       &mqe->un.read_rev);
6356 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
6357 					    &mqe->un.read_rev);
6358 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
6359 					   &mqe->un.read_rev);
6360 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
6361 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
6362 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
6363 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
6364 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
6365 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
6366 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
6367 			"(%d):0380 READ_REV Status x%x "
6368 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
6369 			mboxq->vport ? mboxq->vport->vpi : 0,
6370 			bf_get(lpfc_mqe_status, mqe),
6371 			phba->vpd.rev.opFwName,
6372 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
6373 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
6374 
6375 	/* Reset the DFT_LUN_Q_DEPTH to (max xri >> 3)  */
6376 	rc = (phba->sli4_hba.max_cfg_param.max_xri >> 3);
6377 	if (phba->pport->cfg_lun_queue_depth > rc) {
6378 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6379 				"3362 LUN queue depth changed from %d to %d\n",
6380 				phba->pport->cfg_lun_queue_depth, rc);
6381 		phba->pport->cfg_lun_queue_depth = rc;
6382 	}
6383 
6384 
6385 	/*
6386 	 * Discover the port's supported feature set and match it against the
6387 	 * hosts requests.
6388 	 */
6389 	lpfc_request_features(phba, mboxq);
6390 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6391 	if (unlikely(rc)) {
6392 		rc = -EIO;
6393 		goto out_free_mbox;
6394 	}
6395 
6396 	/*
6397 	 * The port must support FCP initiator mode as this is the
6398 	 * only mode running in the host.
6399 	 */
6400 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
6401 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
6402 				"0378 No support for fcpi mode.\n");
6403 		ftr_rsp++;
6404 	}
6405 	if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
6406 		phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
6407 	else
6408 		phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
6409 	/*
6410 	 * If the port cannot support the host's requested features
6411 	 * then turn off the global config parameters to disable the
6412 	 * feature in the driver.  This is not a fatal error.
6413 	 */
6414 	phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
6415 	if (phba->cfg_enable_bg) {
6416 		if (bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))
6417 			phba->sli3_options |= LPFC_SLI3_BG_ENABLED;
6418 		else
6419 			ftr_rsp++;
6420 	}
6421 
6422 	if (phba->max_vpi && phba->cfg_enable_npiv &&
6423 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
6424 		ftr_rsp++;
6425 
6426 	if (ftr_rsp) {
6427 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
6428 				"0379 Feature Mismatch Data: x%08x %08x "
6429 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
6430 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
6431 				phba->cfg_enable_npiv, phba->max_vpi);
6432 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
6433 			phba->cfg_enable_bg = 0;
6434 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
6435 			phba->cfg_enable_npiv = 0;
6436 	}
6437 
6438 	/* These SLI3 features are assumed in SLI4 */
6439 	spin_lock_irq(&phba->hbalock);
6440 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
6441 	spin_unlock_irq(&phba->hbalock);
6442 
6443 	/*
6444 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
6445 	 * calls depends on these resources to complete port setup.
6446 	 */
6447 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
6448 	if (rc) {
6449 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6450 				"2920 Failed to alloc Resource IDs "
6451 				"rc = x%x\n", rc);
6452 		goto out_free_mbox;
6453 	}
6454 
6455 	/* Read the port's service parameters. */
6456 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
6457 	if (rc) {
6458 		phba->link_state = LPFC_HBA_ERROR;
6459 		rc = -ENOMEM;
6460 		goto out_free_mbox;
6461 	}
6462 
6463 	mboxq->vport = vport;
6464 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6465 	mp = (struct lpfc_dmabuf *) mboxq->context1;
6466 	if (rc == MBX_SUCCESS) {
6467 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
6468 		rc = 0;
6469 	}
6470 
6471 	/*
6472 	 * This memory was allocated by the lpfc_read_sparam routine. Release
6473 	 * it to the mbuf pool.
6474 	 */
6475 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
6476 	kfree(mp);
6477 	mboxq->context1 = NULL;
6478 	if (unlikely(rc)) {
6479 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6480 				"0382 READ_SPARAM command failed "
6481 				"status %d, mbxStatus x%x\n",
6482 				rc, bf_get(lpfc_mqe_status, mqe));
6483 		phba->link_state = LPFC_HBA_ERROR;
6484 		rc = -EIO;
6485 		goto out_free_mbox;
6486 	}
6487 
6488 	lpfc_update_vport_wwn(vport);
6489 
6490 	/* Update the fc_host data structures with new wwn. */
6491 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
6492 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
6493 
6494 	/* update host els and scsi xri-sgl sizes and mappings */
6495 	rc = lpfc_sli4_xri_sgl_update(phba);
6496 	if (unlikely(rc)) {
6497 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6498 				"1400 Failed to update xri-sgl size and "
6499 				"mapping: %d\n", rc);
6500 		goto out_free_mbox;
6501 	}
6502 
6503 	/* register the els sgl pool to the port */
6504 	rc = lpfc_sli4_repost_els_sgl_list(phba);
6505 	if (unlikely(rc)) {
6506 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6507 				"0582 Error %d during els sgl post "
6508 				"operation\n", rc);
6509 		rc = -ENODEV;
6510 		goto out_free_mbox;
6511 	}
6512 
6513 	/* register the allocated scsi sgl pool to the port */
6514 	rc = lpfc_sli4_repost_scsi_sgl_list(phba);
6515 	if (unlikely(rc)) {
6516 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6517 				"0383 Error %d during scsi sgl post "
6518 				"operation\n", rc);
6519 		/* Some Scsi buffers were moved to the abort scsi list */
6520 		/* A pci function reset will repost them */
6521 		rc = -ENODEV;
6522 		goto out_free_mbox;
6523 	}
6524 
6525 	/* Post the rpi header region to the device. */
6526 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
6527 	if (unlikely(rc)) {
6528 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6529 				"0393 Error %d during rpi post operation\n",
6530 				rc);
6531 		rc = -ENODEV;
6532 		goto out_free_mbox;
6533 	}
6534 	lpfc_sli4_node_prep(phba);
6535 
6536 	/* Create all the SLI4 queues */
6537 	rc = lpfc_sli4_queue_create(phba);
6538 	if (rc) {
6539 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6540 				"3089 Failed to allocate queues\n");
6541 		rc = -ENODEV;
6542 		goto out_stop_timers;
6543 	}
6544 	/* Set up all the queues to the device */
6545 	rc = lpfc_sli4_queue_setup(phba);
6546 	if (unlikely(rc)) {
6547 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6548 				"0381 Error %d during queue setup.\n ", rc);
6549 		goto out_destroy_queue;
6550 	}
6551 
6552 	/* Arm the CQs and then EQs on device */
6553 	lpfc_sli4_arm_cqeq_intr(phba);
6554 
6555 	/* Indicate device interrupt mode */
6556 	phba->sli4_hba.intr_enable = 1;
6557 
6558 	/* Allow asynchronous mailbox command to go through */
6559 	spin_lock_irq(&phba->hbalock);
6560 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
6561 	spin_unlock_irq(&phba->hbalock);
6562 
6563 	/* Post receive buffers to the device */
6564 	lpfc_sli4_rb_setup(phba);
6565 
6566 	/* Reset HBA FCF states after HBA reset */
6567 	phba->fcf.fcf_flag = 0;
6568 	phba->fcf.current_rec.flag = 0;
6569 
6570 	/* Start the ELS watchdog timer */
6571 	mod_timer(&vport->els_tmofunc,
6572 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
6573 
6574 	/* Start heart beat timer */
6575 	mod_timer(&phba->hb_tmofunc,
6576 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
6577 	phba->hb_outstanding = 0;
6578 	phba->last_completion_time = jiffies;
6579 
6580 	/* Start error attention (ERATT) polling timer */
6581 	mod_timer(&phba->eratt_poll,
6582 		  jiffies + msecs_to_jiffies(1000 * LPFC_ERATT_POLL_INTERVAL));
6583 
6584 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
6585 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
6586 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
6587 		if (!rc) {
6588 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6589 					"2829 This device supports "
6590 					"Advanced Error Reporting (AER)\n");
6591 			spin_lock_irq(&phba->hbalock);
6592 			phba->hba_flag |= HBA_AER_ENABLED;
6593 			spin_unlock_irq(&phba->hbalock);
6594 		} else {
6595 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6596 					"2830 This device does not support "
6597 					"Advanced Error Reporting (AER)\n");
6598 			phba->cfg_aer_support = 0;
6599 		}
6600 		rc = 0;
6601 	}
6602 
6603 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
6604 		/*
6605 		 * The FC Port needs to register FCFI (index 0)
6606 		 */
6607 		lpfc_reg_fcfi(phba, mboxq);
6608 		mboxq->vport = phba->pport;
6609 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6610 		if (rc != MBX_SUCCESS)
6611 			goto out_unset_queue;
6612 		rc = 0;
6613 		phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
6614 					&mboxq->u.mqe.un.reg_fcfi);
6615 
6616 		/* Check if the port is configured to be disabled */
6617 		lpfc_sli_read_link_ste(phba);
6618 	}
6619 
6620 	/*
6621 	 * The port is ready, set the host's link state to LINK_DOWN
6622 	 * in preparation for link interrupts.
6623 	 */
6624 	spin_lock_irq(&phba->hbalock);
6625 	phba->link_state = LPFC_LINK_DOWN;
6626 	spin_unlock_irq(&phba->hbalock);
6627 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
6628 	    (phba->hba_flag & LINK_DISABLED)) {
6629 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
6630 				"3103 Adapter Link is disabled.\n");
6631 		lpfc_down_link(phba, mboxq);
6632 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6633 		if (rc != MBX_SUCCESS) {
6634 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
6635 					"3104 Adapter failed to issue "
6636 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
6637 			goto out_unset_queue;
6638 		}
6639 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
6640 		/* don't perform init_link on SLI4 FC port loopback test */
6641 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
6642 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
6643 			if (rc)
6644 				goto out_unset_queue;
6645 		}
6646 	}
6647 	mempool_free(mboxq, phba->mbox_mem_pool);
6648 	return rc;
6649 out_unset_queue:
6650 	/* Unset all the queues set up in this routine when error out */
6651 	lpfc_sli4_queue_unset(phba);
6652 out_destroy_queue:
6653 	lpfc_sli4_queue_destroy(phba);
6654 out_stop_timers:
6655 	lpfc_stop_hba_timers(phba);
6656 out_free_mbox:
6657 	mempool_free(mboxq, phba->mbox_mem_pool);
6658 	return rc;
6659 }
6660 
6661 /**
6662  * lpfc_mbox_timeout - Timeout call back function for mbox timer
6663  * @ptr: context object - pointer to hba structure.
6664  *
6665  * This is the callback function for mailbox timer. The mailbox
6666  * timer is armed when a new mailbox command is issued and the timer
6667  * is deleted when the mailbox complete. The function is called by
6668  * the kernel timer code when a mailbox does not complete within
6669  * expected time. This function wakes up the worker thread to
6670  * process the mailbox timeout and returns. All the processing is
6671  * done by the worker thread function lpfc_mbox_timeout_handler.
6672  **/
6673 void
6674 lpfc_mbox_timeout(unsigned long ptr)
6675 {
6676 	struct lpfc_hba  *phba = (struct lpfc_hba *) ptr;
6677 	unsigned long iflag;
6678 	uint32_t tmo_posted;
6679 
6680 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
6681 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
6682 	if (!tmo_posted)
6683 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
6684 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
6685 
6686 	if (!tmo_posted)
6687 		lpfc_worker_wake_up(phba);
6688 	return;
6689 }
6690 
6691 /**
6692  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
6693  *                                    are pending
6694  * @phba: Pointer to HBA context object.
6695  *
6696  * This function checks if any mailbox completions are present on the mailbox
6697  * completion queue.
6698  **/
6699 bool
6700 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
6701 {
6702 
6703 	uint32_t idx;
6704 	struct lpfc_queue *mcq;
6705 	struct lpfc_mcqe *mcqe;
6706 	bool pending_completions = false;
6707 
6708 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
6709 		return false;
6710 
6711 	/* Check for completions on mailbox completion queue */
6712 
6713 	mcq = phba->sli4_hba.mbx_cq;
6714 	idx = mcq->hba_index;
6715 	while (bf_get_le32(lpfc_cqe_valid, mcq->qe[idx].cqe)) {
6716 		mcqe = (struct lpfc_mcqe *)mcq->qe[idx].cqe;
6717 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
6718 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
6719 			pending_completions = true;
6720 			break;
6721 		}
6722 		idx = (idx + 1) % mcq->entry_count;
6723 		if (mcq->hba_index == idx)
6724 			break;
6725 	}
6726 	return pending_completions;
6727 
6728 }
6729 
6730 /**
6731  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
6732  *					      that were missed.
6733  * @phba: Pointer to HBA context object.
6734  *
6735  * For sli4, it is possible to miss an interrupt. As such mbox completions
6736  * maybe missed causing erroneous mailbox timeouts to occur. This function
6737  * checks to see if mbox completions are on the mailbox completion queue
6738  * and will process all the completions associated with the eq for the
6739  * mailbox completion queue.
6740  **/
6741 bool
6742 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
6743 {
6744 
6745 	uint32_t eqidx;
6746 	struct lpfc_queue *fpeq = NULL;
6747 	struct lpfc_eqe *eqe;
6748 	bool mbox_pending;
6749 
6750 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
6751 		return false;
6752 
6753 	/* Find the eq associated with the mcq */
6754 
6755 	if (phba->sli4_hba.hba_eq)
6756 		for (eqidx = 0; eqidx < phba->cfg_fcp_io_channel; eqidx++)
6757 			if (phba->sli4_hba.hba_eq[eqidx]->queue_id ==
6758 			    phba->sli4_hba.mbx_cq->assoc_qid) {
6759 				fpeq = phba->sli4_hba.hba_eq[eqidx];
6760 				break;
6761 			}
6762 	if (!fpeq)
6763 		return false;
6764 
6765 	/* Turn off interrupts from this EQ */
6766 
6767 	lpfc_sli4_eq_clr_intr(fpeq);
6768 
6769 	/* Check to see if a mbox completion is pending */
6770 
6771 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
6772 
6773 	/*
6774 	 * If a mbox completion is pending, process all the events on EQ
6775 	 * associated with the mbox completion queue (this could include
6776 	 * mailbox commands, async events, els commands, receive queue data
6777 	 * and fcp commands)
6778 	 */
6779 
6780 	if (mbox_pending)
6781 		while ((eqe = lpfc_sli4_eq_get(fpeq))) {
6782 			lpfc_sli4_hba_handle_eqe(phba, eqe, eqidx);
6783 			fpeq->EQ_processed++;
6784 		}
6785 
6786 	/* Always clear and re-arm the EQ */
6787 
6788 	lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_REARM);
6789 
6790 	return mbox_pending;
6791 
6792 }
6793 
6794 /**
6795  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
6796  * @phba: Pointer to HBA context object.
6797  *
6798  * This function is called from worker thread when a mailbox command times out.
6799  * The caller is not required to hold any locks. This function will reset the
6800  * HBA and recover all the pending commands.
6801  **/
6802 void
6803 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
6804 {
6805 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
6806 	MAILBOX_t *mb = NULL;
6807 
6808 	struct lpfc_sli *psli = &phba->sli;
6809 
6810 	/* If the mailbox completed, process the completion and return */
6811 	if (lpfc_sli4_process_missed_mbox_completions(phba))
6812 		return;
6813 
6814 	if (pmbox != NULL)
6815 		mb = &pmbox->u.mb;
6816 	/* Check the pmbox pointer first.  There is a race condition
6817 	 * between the mbox timeout handler getting executed in the
6818 	 * worklist and the mailbox actually completing. When this
6819 	 * race condition occurs, the mbox_active will be NULL.
6820 	 */
6821 	spin_lock_irq(&phba->hbalock);
6822 	if (pmbox == NULL) {
6823 		lpfc_printf_log(phba, KERN_WARNING,
6824 				LOG_MBOX | LOG_SLI,
6825 				"0353 Active Mailbox cleared - mailbox timeout "
6826 				"exiting\n");
6827 		spin_unlock_irq(&phba->hbalock);
6828 		return;
6829 	}
6830 
6831 	/* Mbox cmd <mbxCommand> timeout */
6832 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6833 			"0310 Mailbox command x%x timeout Data: x%x x%x x%p\n",
6834 			mb->mbxCommand,
6835 			phba->pport->port_state,
6836 			phba->sli.sli_flag,
6837 			phba->sli.mbox_active);
6838 	spin_unlock_irq(&phba->hbalock);
6839 
6840 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
6841 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
6842 	 * it to fail all outstanding SCSI IO.
6843 	 */
6844 	spin_lock_irq(&phba->pport->work_port_lock);
6845 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
6846 	spin_unlock_irq(&phba->pport->work_port_lock);
6847 	spin_lock_irq(&phba->hbalock);
6848 	phba->link_state = LPFC_LINK_UNKNOWN;
6849 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
6850 	spin_unlock_irq(&phba->hbalock);
6851 
6852 	lpfc_sli_abort_fcp_rings(phba);
6853 
6854 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6855 			"0345 Resetting board due to mailbox timeout\n");
6856 
6857 	/* Reset the HBA device */
6858 	lpfc_reset_hba(phba);
6859 }
6860 
6861 /**
6862  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
6863  * @phba: Pointer to HBA context object.
6864  * @pmbox: Pointer to mailbox object.
6865  * @flag: Flag indicating how the mailbox need to be processed.
6866  *
6867  * This function is called by discovery code and HBA management code
6868  * to submit a mailbox command to firmware with SLI-3 interface spec. This
6869  * function gets the hbalock to protect the data structures.
6870  * The mailbox command can be submitted in polling mode, in which case
6871  * this function will wait in a polling loop for the completion of the
6872  * mailbox.
6873  * If the mailbox is submitted in no_wait mode (not polling) the
6874  * function will submit the command and returns immediately without waiting
6875  * for the mailbox completion. The no_wait is supported only when HBA
6876  * is in SLI2/SLI3 mode - interrupts are enabled.
6877  * The SLI interface allows only one mailbox pending at a time. If the
6878  * mailbox is issued in polling mode and there is already a mailbox
6879  * pending, then the function will return an error. If the mailbox is issued
6880  * in NO_WAIT mode and there is a mailbox pending already, the function
6881  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
6882  * The sli layer owns the mailbox object until the completion of mailbox
6883  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
6884  * return codes the caller owns the mailbox command after the return of
6885  * the function.
6886  **/
6887 static int
6888 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
6889 		       uint32_t flag)
6890 {
6891 	MAILBOX_t *mbx;
6892 	struct lpfc_sli *psli = &phba->sli;
6893 	uint32_t status, evtctr;
6894 	uint32_t ha_copy, hc_copy;
6895 	int i;
6896 	unsigned long timeout;
6897 	unsigned long drvr_flag = 0;
6898 	uint32_t word0, ldata;
6899 	void __iomem *to_slim;
6900 	int processing_queue = 0;
6901 
6902 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
6903 	if (!pmbox) {
6904 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
6905 		/* processing mbox queue from intr_handler */
6906 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
6907 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6908 			return MBX_SUCCESS;
6909 		}
6910 		processing_queue = 1;
6911 		pmbox = lpfc_mbox_get(phba);
6912 		if (!pmbox) {
6913 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6914 			return MBX_SUCCESS;
6915 		}
6916 	}
6917 
6918 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
6919 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
6920 		if(!pmbox->vport) {
6921 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6922 			lpfc_printf_log(phba, KERN_ERR,
6923 					LOG_MBOX | LOG_VPORT,
6924 					"1806 Mbox x%x failed. No vport\n",
6925 					pmbox->u.mb.mbxCommand);
6926 			dump_stack();
6927 			goto out_not_finished;
6928 		}
6929 	}
6930 
6931 	/* If the PCI channel is in offline state, do not post mbox. */
6932 	if (unlikely(pci_channel_offline(phba->pcidev))) {
6933 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6934 		goto out_not_finished;
6935 	}
6936 
6937 	/* If HBA has a deferred error attention, fail the iocb. */
6938 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
6939 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6940 		goto out_not_finished;
6941 	}
6942 
6943 	psli = &phba->sli;
6944 
6945 	mbx = &pmbox->u.mb;
6946 	status = MBX_SUCCESS;
6947 
6948 	if (phba->link_state == LPFC_HBA_ERROR) {
6949 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6950 
6951 		/* Mbox command <mbxCommand> cannot issue */
6952 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6953 				"(%d):0311 Mailbox command x%x cannot "
6954 				"issue Data: x%x x%x\n",
6955 				pmbox->vport ? pmbox->vport->vpi : 0,
6956 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
6957 		goto out_not_finished;
6958 	}
6959 
6960 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
6961 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
6962 			!(hc_copy & HC_MBINT_ENA)) {
6963 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6964 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6965 				"(%d):2528 Mailbox command x%x cannot "
6966 				"issue Data: x%x x%x\n",
6967 				pmbox->vport ? pmbox->vport->vpi : 0,
6968 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
6969 			goto out_not_finished;
6970 		}
6971 	}
6972 
6973 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
6974 		/* Polling for a mbox command when another one is already active
6975 		 * is not allowed in SLI. Also, the driver must have established
6976 		 * SLI2 mode to queue and process multiple mbox commands.
6977 		 */
6978 
6979 		if (flag & MBX_POLL) {
6980 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6981 
6982 			/* Mbox command <mbxCommand> cannot issue */
6983 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6984 					"(%d):2529 Mailbox command x%x "
6985 					"cannot issue Data: x%x x%x\n",
6986 					pmbox->vport ? pmbox->vport->vpi : 0,
6987 					pmbox->u.mb.mbxCommand,
6988 					psli->sli_flag, flag);
6989 			goto out_not_finished;
6990 		}
6991 
6992 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
6993 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6994 			/* Mbox command <mbxCommand> cannot issue */
6995 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6996 					"(%d):2530 Mailbox command x%x "
6997 					"cannot issue Data: x%x x%x\n",
6998 					pmbox->vport ? pmbox->vport->vpi : 0,
6999 					pmbox->u.mb.mbxCommand,
7000 					psli->sli_flag, flag);
7001 			goto out_not_finished;
7002 		}
7003 
7004 		/* Another mailbox command is still being processed, queue this
7005 		 * command to be processed later.
7006 		 */
7007 		lpfc_mbox_put(phba, pmbox);
7008 
7009 		/* Mbox cmd issue - BUSY */
7010 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7011 				"(%d):0308 Mbox cmd issue - BUSY Data: "
7012 				"x%x x%x x%x x%x\n",
7013 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
7014 				mbx->mbxCommand, phba->pport->port_state,
7015 				psli->sli_flag, flag);
7016 
7017 		psli->slistat.mbox_busy++;
7018 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7019 
7020 		if (pmbox->vport) {
7021 			lpfc_debugfs_disc_trc(pmbox->vport,
7022 				LPFC_DISC_TRC_MBOX_VPORT,
7023 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
7024 				(uint32_t)mbx->mbxCommand,
7025 				mbx->un.varWords[0], mbx->un.varWords[1]);
7026 		}
7027 		else {
7028 			lpfc_debugfs_disc_trc(phba->pport,
7029 				LPFC_DISC_TRC_MBOX,
7030 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
7031 				(uint32_t)mbx->mbxCommand,
7032 				mbx->un.varWords[0], mbx->un.varWords[1]);
7033 		}
7034 
7035 		return MBX_BUSY;
7036 	}
7037 
7038 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7039 
7040 	/* If we are not polling, we MUST be in SLI2 mode */
7041 	if (flag != MBX_POLL) {
7042 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
7043 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
7044 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7045 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7046 			/* Mbox command <mbxCommand> cannot issue */
7047 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7048 					"(%d):2531 Mailbox command x%x "
7049 					"cannot issue Data: x%x x%x\n",
7050 					pmbox->vport ? pmbox->vport->vpi : 0,
7051 					pmbox->u.mb.mbxCommand,
7052 					psli->sli_flag, flag);
7053 			goto out_not_finished;
7054 		}
7055 		/* timeout active mbox command */
7056 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
7057 					   1000);
7058 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
7059 	}
7060 
7061 	/* Mailbox cmd <cmd> issue */
7062 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7063 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
7064 			"x%x\n",
7065 			pmbox->vport ? pmbox->vport->vpi : 0,
7066 			mbx->mbxCommand, phba->pport->port_state,
7067 			psli->sli_flag, flag);
7068 
7069 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
7070 		if (pmbox->vport) {
7071 			lpfc_debugfs_disc_trc(pmbox->vport,
7072 				LPFC_DISC_TRC_MBOX_VPORT,
7073 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
7074 				(uint32_t)mbx->mbxCommand,
7075 				mbx->un.varWords[0], mbx->un.varWords[1]);
7076 		}
7077 		else {
7078 			lpfc_debugfs_disc_trc(phba->pport,
7079 				LPFC_DISC_TRC_MBOX,
7080 				"MBOX Send:       cmd:x%x mb:x%x x%x",
7081 				(uint32_t)mbx->mbxCommand,
7082 				mbx->un.varWords[0], mbx->un.varWords[1]);
7083 		}
7084 	}
7085 
7086 	psli->slistat.mbox_cmd++;
7087 	evtctr = psli->slistat.mbox_event;
7088 
7089 	/* next set own bit for the adapter and copy over command word */
7090 	mbx->mbxOwner = OWN_CHIP;
7091 
7092 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7093 		/* Populate mbox extension offset word. */
7094 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
7095 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
7096 				= (uint8_t *)phba->mbox_ext
7097 				  - (uint8_t *)phba->mbox;
7098 		}
7099 
7100 		/* Copy the mailbox extension data */
7101 		if (pmbox->in_ext_byte_len && pmbox->context2) {
7102 			lpfc_sli_pcimem_bcopy(pmbox->context2,
7103 				(uint8_t *)phba->mbox_ext,
7104 				pmbox->in_ext_byte_len);
7105 		}
7106 		/* Copy command data to host SLIM area */
7107 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
7108 	} else {
7109 		/* Populate mbox extension offset word. */
7110 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
7111 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
7112 				= MAILBOX_HBA_EXT_OFFSET;
7113 
7114 		/* Copy the mailbox extension data */
7115 		if (pmbox->in_ext_byte_len && pmbox->context2) {
7116 			lpfc_memcpy_to_slim(phba->MBslimaddr +
7117 				MAILBOX_HBA_EXT_OFFSET,
7118 				pmbox->context2, pmbox->in_ext_byte_len);
7119 
7120 		}
7121 		if (mbx->mbxCommand == MBX_CONFIG_PORT) {
7122 			/* copy command data into host mbox for cmpl */
7123 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
7124 		}
7125 
7126 		/* First copy mbox command data to HBA SLIM, skip past first
7127 		   word */
7128 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
7129 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
7130 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
7131 
7132 		/* Next copy over first word, with mbxOwner set */
7133 		ldata = *((uint32_t *)mbx);
7134 		to_slim = phba->MBslimaddr;
7135 		writel(ldata, to_slim);
7136 		readl(to_slim); /* flush */
7137 
7138 		if (mbx->mbxCommand == MBX_CONFIG_PORT) {
7139 			/* switch over to host mailbox */
7140 			psli->sli_flag |= LPFC_SLI_ACTIVE;
7141 		}
7142 	}
7143 
7144 	wmb();
7145 
7146 	switch (flag) {
7147 	case MBX_NOWAIT:
7148 		/* Set up reference to mailbox command */
7149 		psli->mbox_active = pmbox;
7150 		/* Interrupt board to do it */
7151 		writel(CA_MBATT, phba->CAregaddr);
7152 		readl(phba->CAregaddr); /* flush */
7153 		/* Don't wait for it to finish, just return */
7154 		break;
7155 
7156 	case MBX_POLL:
7157 		/* Set up null reference to mailbox command */
7158 		psli->mbox_active = NULL;
7159 		/* Interrupt board to do it */
7160 		writel(CA_MBATT, phba->CAregaddr);
7161 		readl(phba->CAregaddr); /* flush */
7162 
7163 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7164 			/* First read mbox status word */
7165 			word0 = *((uint32_t *)phba->mbox);
7166 			word0 = le32_to_cpu(word0);
7167 		} else {
7168 			/* First read mbox status word */
7169 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
7170 				spin_unlock_irqrestore(&phba->hbalock,
7171 						       drvr_flag);
7172 				goto out_not_finished;
7173 			}
7174 		}
7175 
7176 		/* Read the HBA Host Attention Register */
7177 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
7178 			spin_unlock_irqrestore(&phba->hbalock,
7179 						       drvr_flag);
7180 			goto out_not_finished;
7181 		}
7182 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
7183 							1000) + jiffies;
7184 		i = 0;
7185 		/* Wait for command to complete */
7186 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
7187 		       (!(ha_copy & HA_MBATT) &&
7188 			(phba->link_state > LPFC_WARM_START))) {
7189 			if (time_after(jiffies, timeout)) {
7190 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7191 				spin_unlock_irqrestore(&phba->hbalock,
7192 						       drvr_flag);
7193 				goto out_not_finished;
7194 			}
7195 
7196 			/* Check if we took a mbox interrupt while we were
7197 			   polling */
7198 			if (((word0 & OWN_CHIP) != OWN_CHIP)
7199 			    && (evtctr != psli->slistat.mbox_event))
7200 				break;
7201 
7202 			if (i++ > 10) {
7203 				spin_unlock_irqrestore(&phba->hbalock,
7204 						       drvr_flag);
7205 				msleep(1);
7206 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
7207 			}
7208 
7209 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7210 				/* First copy command data */
7211 				word0 = *((uint32_t *)phba->mbox);
7212 				word0 = le32_to_cpu(word0);
7213 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
7214 					MAILBOX_t *slimmb;
7215 					uint32_t slimword0;
7216 					/* Check real SLIM for any errors */
7217 					slimword0 = readl(phba->MBslimaddr);
7218 					slimmb = (MAILBOX_t *) & slimword0;
7219 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
7220 					    && slimmb->mbxStatus) {
7221 						psli->sli_flag &=
7222 						    ~LPFC_SLI_ACTIVE;
7223 						word0 = slimword0;
7224 					}
7225 				}
7226 			} else {
7227 				/* First copy command data */
7228 				word0 = readl(phba->MBslimaddr);
7229 			}
7230 			/* Read the HBA Host Attention Register */
7231 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
7232 				spin_unlock_irqrestore(&phba->hbalock,
7233 						       drvr_flag);
7234 				goto out_not_finished;
7235 			}
7236 		}
7237 
7238 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7239 			/* copy results back to user */
7240 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx, MAILBOX_CMD_SIZE);
7241 			/* Copy the mailbox extension data */
7242 			if (pmbox->out_ext_byte_len && pmbox->context2) {
7243 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
7244 						      pmbox->context2,
7245 						      pmbox->out_ext_byte_len);
7246 			}
7247 		} else {
7248 			/* First copy command data */
7249 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
7250 							MAILBOX_CMD_SIZE);
7251 			/* Copy the mailbox extension data */
7252 			if (pmbox->out_ext_byte_len && pmbox->context2) {
7253 				lpfc_memcpy_from_slim(pmbox->context2,
7254 					phba->MBslimaddr +
7255 					MAILBOX_HBA_EXT_OFFSET,
7256 					pmbox->out_ext_byte_len);
7257 			}
7258 		}
7259 
7260 		writel(HA_MBATT, phba->HAregaddr);
7261 		readl(phba->HAregaddr); /* flush */
7262 
7263 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7264 		status = mbx->mbxStatus;
7265 	}
7266 
7267 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7268 	return status;
7269 
7270 out_not_finished:
7271 	if (processing_queue) {
7272 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
7273 		lpfc_mbox_cmpl_put(phba, pmbox);
7274 	}
7275 	return MBX_NOT_FINISHED;
7276 }
7277 
7278 /**
7279  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
7280  * @phba: Pointer to HBA context object.
7281  *
7282  * The function blocks the posting of SLI4 asynchronous mailbox commands from
7283  * the driver internal pending mailbox queue. It will then try to wait out the
7284  * possible outstanding mailbox command before return.
7285  *
7286  * Returns:
7287  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
7288  * 	the outstanding mailbox command timed out.
7289  **/
7290 static int
7291 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
7292 {
7293 	struct lpfc_sli *psli = &phba->sli;
7294 	int rc = 0;
7295 	unsigned long timeout = 0;
7296 
7297 	/* Mark the asynchronous mailbox command posting as blocked */
7298 	spin_lock_irq(&phba->hbalock);
7299 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
7300 	/* Determine how long we might wait for the active mailbox
7301 	 * command to be gracefully completed by firmware.
7302 	 */
7303 	if (phba->sli.mbox_active)
7304 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
7305 						phba->sli.mbox_active) *
7306 						1000) + jiffies;
7307 	spin_unlock_irq(&phba->hbalock);
7308 
7309 	/* Make sure the mailbox is really active */
7310 	if (timeout)
7311 		lpfc_sli4_process_missed_mbox_completions(phba);
7312 
7313 	/* Wait for the outstnading mailbox command to complete */
7314 	while (phba->sli.mbox_active) {
7315 		/* Check active mailbox complete status every 2ms */
7316 		msleep(2);
7317 		if (time_after(jiffies, timeout)) {
7318 			/* Timeout, marked the outstanding cmd not complete */
7319 			rc = 1;
7320 			break;
7321 		}
7322 	}
7323 
7324 	/* Can not cleanly block async mailbox command, fails it */
7325 	if (rc) {
7326 		spin_lock_irq(&phba->hbalock);
7327 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7328 		spin_unlock_irq(&phba->hbalock);
7329 	}
7330 	return rc;
7331 }
7332 
7333 /**
7334  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
7335  * @phba: Pointer to HBA context object.
7336  *
7337  * The function unblocks and resume posting of SLI4 asynchronous mailbox
7338  * commands from the driver internal pending mailbox queue. It makes sure
7339  * that there is no outstanding mailbox command before resuming posting
7340  * asynchronous mailbox commands. If, for any reason, there is outstanding
7341  * mailbox command, it will try to wait it out before resuming asynchronous
7342  * mailbox command posting.
7343  **/
7344 static void
7345 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
7346 {
7347 	struct lpfc_sli *psli = &phba->sli;
7348 
7349 	spin_lock_irq(&phba->hbalock);
7350 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
7351 		/* Asynchronous mailbox posting is not blocked, do nothing */
7352 		spin_unlock_irq(&phba->hbalock);
7353 		return;
7354 	}
7355 
7356 	/* Outstanding synchronous mailbox command is guaranteed to be done,
7357 	 * successful or timeout, after timing-out the outstanding mailbox
7358 	 * command shall always be removed, so just unblock posting async
7359 	 * mailbox command and resume
7360 	 */
7361 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7362 	spin_unlock_irq(&phba->hbalock);
7363 
7364 	/* wake up worker thread to post asynchronlous mailbox command */
7365 	lpfc_worker_wake_up(phba);
7366 }
7367 
7368 /**
7369  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
7370  * @phba: Pointer to HBA context object.
7371  * @mboxq: Pointer to mailbox object.
7372  *
7373  * The function waits for the bootstrap mailbox register ready bit from
7374  * port for twice the regular mailbox command timeout value.
7375  *
7376  *      0 - no timeout on waiting for bootstrap mailbox register ready.
7377  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
7378  **/
7379 static int
7380 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
7381 {
7382 	uint32_t db_ready;
7383 	unsigned long timeout;
7384 	struct lpfc_register bmbx_reg;
7385 
7386 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
7387 				   * 1000) + jiffies;
7388 
7389 	do {
7390 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
7391 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
7392 		if (!db_ready)
7393 			msleep(2);
7394 
7395 		if (time_after(jiffies, timeout))
7396 			return MBXERR_ERROR;
7397 	} while (!db_ready);
7398 
7399 	return 0;
7400 }
7401 
7402 /**
7403  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
7404  * @phba: Pointer to HBA context object.
7405  * @mboxq: Pointer to mailbox object.
7406  *
7407  * The function posts a mailbox to the port.  The mailbox is expected
7408  * to be comletely filled in and ready for the port to operate on it.
7409  * This routine executes a synchronous completion operation on the
7410  * mailbox by polling for its completion.
7411  *
7412  * The caller must not be holding any locks when calling this routine.
7413  *
7414  * Returns:
7415  *	MBX_SUCCESS - mailbox posted successfully
7416  *	Any of the MBX error values.
7417  **/
7418 static int
7419 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
7420 {
7421 	int rc = MBX_SUCCESS;
7422 	unsigned long iflag;
7423 	uint32_t mcqe_status;
7424 	uint32_t mbx_cmnd;
7425 	struct lpfc_sli *psli = &phba->sli;
7426 	struct lpfc_mqe *mb = &mboxq->u.mqe;
7427 	struct lpfc_bmbx_create *mbox_rgn;
7428 	struct dma_address *dma_address;
7429 
7430 	/*
7431 	 * Only one mailbox can be active to the bootstrap mailbox region
7432 	 * at a time and there is no queueing provided.
7433 	 */
7434 	spin_lock_irqsave(&phba->hbalock, iflag);
7435 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
7436 		spin_unlock_irqrestore(&phba->hbalock, iflag);
7437 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7438 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
7439 				"cannot issue Data: x%x x%x\n",
7440 				mboxq->vport ? mboxq->vport->vpi : 0,
7441 				mboxq->u.mb.mbxCommand,
7442 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7443 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7444 				psli->sli_flag, MBX_POLL);
7445 		return MBXERR_ERROR;
7446 	}
7447 	/* The server grabs the token and owns it until release */
7448 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7449 	phba->sli.mbox_active = mboxq;
7450 	spin_unlock_irqrestore(&phba->hbalock, iflag);
7451 
7452 	/* wait for bootstrap mbox register for readyness */
7453 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7454 	if (rc)
7455 		goto exit;
7456 
7457 	/*
7458 	 * Initialize the bootstrap memory region to avoid stale data areas
7459 	 * in the mailbox post.  Then copy the caller's mailbox contents to
7460 	 * the bmbx mailbox region.
7461 	 */
7462 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
7463 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
7464 	lpfc_sli_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
7465 			      sizeof(struct lpfc_mqe));
7466 
7467 	/* Post the high mailbox dma address to the port and wait for ready. */
7468 	dma_address = &phba->sli4_hba.bmbx.dma_address;
7469 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
7470 
7471 	/* wait for bootstrap mbox register for hi-address write done */
7472 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7473 	if (rc)
7474 		goto exit;
7475 
7476 	/* Post the low mailbox dma address to the port. */
7477 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
7478 
7479 	/* wait for bootstrap mbox register for low address write done */
7480 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7481 	if (rc)
7482 		goto exit;
7483 
7484 	/*
7485 	 * Read the CQ to ensure the mailbox has completed.
7486 	 * If so, update the mailbox status so that the upper layers
7487 	 * can complete the request normally.
7488 	 */
7489 	lpfc_sli_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
7490 			      sizeof(struct lpfc_mqe));
7491 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
7492 	lpfc_sli_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
7493 			      sizeof(struct lpfc_mcqe));
7494 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
7495 	/*
7496 	 * When the CQE status indicates a failure and the mailbox status
7497 	 * indicates success then copy the CQE status into the mailbox status
7498 	 * (and prefix it with x4000).
7499 	 */
7500 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
7501 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
7502 			bf_set(lpfc_mqe_status, mb,
7503 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
7504 		rc = MBXERR_ERROR;
7505 	} else
7506 		lpfc_sli4_swap_str(phba, mboxq);
7507 
7508 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7509 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
7510 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
7511 			" x%x x%x CQ: x%x x%x x%x x%x\n",
7512 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
7513 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7514 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7515 			bf_get(lpfc_mqe_status, mb),
7516 			mb->un.mb_words[0], mb->un.mb_words[1],
7517 			mb->un.mb_words[2], mb->un.mb_words[3],
7518 			mb->un.mb_words[4], mb->un.mb_words[5],
7519 			mb->un.mb_words[6], mb->un.mb_words[7],
7520 			mb->un.mb_words[8], mb->un.mb_words[9],
7521 			mb->un.mb_words[10], mb->un.mb_words[11],
7522 			mb->un.mb_words[12], mboxq->mcqe.word0,
7523 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
7524 			mboxq->mcqe.trailer);
7525 exit:
7526 	/* We are holding the token, no needed for lock when release */
7527 	spin_lock_irqsave(&phba->hbalock, iflag);
7528 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7529 	phba->sli.mbox_active = NULL;
7530 	spin_unlock_irqrestore(&phba->hbalock, iflag);
7531 	return rc;
7532 }
7533 
7534 /**
7535  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
7536  * @phba: Pointer to HBA context object.
7537  * @pmbox: Pointer to mailbox object.
7538  * @flag: Flag indicating how the mailbox need to be processed.
7539  *
7540  * This function is called by discovery code and HBA management code to submit
7541  * a mailbox command to firmware with SLI-4 interface spec.
7542  *
7543  * Return codes the caller owns the mailbox command after the return of the
7544  * function.
7545  **/
7546 static int
7547 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
7548 		       uint32_t flag)
7549 {
7550 	struct lpfc_sli *psli = &phba->sli;
7551 	unsigned long iflags;
7552 	int rc;
7553 
7554 	/* dump from issue mailbox command if setup */
7555 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
7556 
7557 	rc = lpfc_mbox_dev_check(phba);
7558 	if (unlikely(rc)) {
7559 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7560 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
7561 				"cannot issue Data: x%x x%x\n",
7562 				mboxq->vport ? mboxq->vport->vpi : 0,
7563 				mboxq->u.mb.mbxCommand,
7564 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7565 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7566 				psli->sli_flag, flag);
7567 		goto out_not_finished;
7568 	}
7569 
7570 	/* Detect polling mode and jump to a handler */
7571 	if (!phba->sli4_hba.intr_enable) {
7572 		if (flag == MBX_POLL)
7573 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
7574 		else
7575 			rc = -EIO;
7576 		if (rc != MBX_SUCCESS)
7577 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7578 					"(%d):2541 Mailbox command x%x "
7579 					"(x%x/x%x) failure: "
7580 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
7581 					"Data: x%x x%x\n,",
7582 					mboxq->vport ? mboxq->vport->vpi : 0,
7583 					mboxq->u.mb.mbxCommand,
7584 					lpfc_sli_config_mbox_subsys_get(phba,
7585 									mboxq),
7586 					lpfc_sli_config_mbox_opcode_get(phba,
7587 									mboxq),
7588 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
7589 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
7590 					bf_get(lpfc_mcqe_ext_status,
7591 					       &mboxq->mcqe),
7592 					psli->sli_flag, flag);
7593 		return rc;
7594 	} else if (flag == MBX_POLL) {
7595 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7596 				"(%d):2542 Try to issue mailbox command "
7597 				"x%x (x%x/x%x) synchronously ahead of async"
7598 				"mailbox command queue: x%x x%x\n",
7599 				mboxq->vport ? mboxq->vport->vpi : 0,
7600 				mboxq->u.mb.mbxCommand,
7601 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7602 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7603 				psli->sli_flag, flag);
7604 		/* Try to block the asynchronous mailbox posting */
7605 		rc = lpfc_sli4_async_mbox_block(phba);
7606 		if (!rc) {
7607 			/* Successfully blocked, now issue sync mbox cmd */
7608 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
7609 			if (rc != MBX_SUCCESS)
7610 				lpfc_printf_log(phba, KERN_WARNING,
7611 					LOG_MBOX | LOG_SLI,
7612 					"(%d):2597 Sync Mailbox command "
7613 					"x%x (x%x/x%x) failure: "
7614 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
7615 					"Data: x%x x%x\n,",
7616 					mboxq->vport ? mboxq->vport->vpi : 0,
7617 					mboxq->u.mb.mbxCommand,
7618 					lpfc_sli_config_mbox_subsys_get(phba,
7619 									mboxq),
7620 					lpfc_sli_config_mbox_opcode_get(phba,
7621 									mboxq),
7622 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
7623 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
7624 					bf_get(lpfc_mcqe_ext_status,
7625 					       &mboxq->mcqe),
7626 					psli->sli_flag, flag);
7627 			/* Unblock the async mailbox posting afterward */
7628 			lpfc_sli4_async_mbox_unblock(phba);
7629 		}
7630 		return rc;
7631 	}
7632 
7633 	/* Now, interrupt mode asynchrous mailbox command */
7634 	rc = lpfc_mbox_cmd_check(phba, mboxq);
7635 	if (rc) {
7636 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7637 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
7638 				"cannot issue Data: x%x x%x\n",
7639 				mboxq->vport ? mboxq->vport->vpi : 0,
7640 				mboxq->u.mb.mbxCommand,
7641 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7642 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7643 				psli->sli_flag, flag);
7644 		goto out_not_finished;
7645 	}
7646 
7647 	/* Put the mailbox command to the driver internal FIFO */
7648 	psli->slistat.mbox_busy++;
7649 	spin_lock_irqsave(&phba->hbalock, iflags);
7650 	lpfc_mbox_put(phba, mboxq);
7651 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7652 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7653 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
7654 			"x%x (x%x/x%x) x%x x%x x%x\n",
7655 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
7656 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7657 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7658 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7659 			phba->pport->port_state,
7660 			psli->sli_flag, MBX_NOWAIT);
7661 	/* Wake up worker thread to transport mailbox command from head */
7662 	lpfc_worker_wake_up(phba);
7663 
7664 	return MBX_BUSY;
7665 
7666 out_not_finished:
7667 	return MBX_NOT_FINISHED;
7668 }
7669 
7670 /**
7671  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
7672  * @phba: Pointer to HBA context object.
7673  *
7674  * This function is called by worker thread to send a mailbox command to
7675  * SLI4 HBA firmware.
7676  *
7677  **/
7678 int
7679 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
7680 {
7681 	struct lpfc_sli *psli = &phba->sli;
7682 	LPFC_MBOXQ_t *mboxq;
7683 	int rc = MBX_SUCCESS;
7684 	unsigned long iflags;
7685 	struct lpfc_mqe *mqe;
7686 	uint32_t mbx_cmnd;
7687 
7688 	/* Check interrupt mode before post async mailbox command */
7689 	if (unlikely(!phba->sli4_hba.intr_enable))
7690 		return MBX_NOT_FINISHED;
7691 
7692 	/* Check for mailbox command service token */
7693 	spin_lock_irqsave(&phba->hbalock, iflags);
7694 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
7695 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7696 		return MBX_NOT_FINISHED;
7697 	}
7698 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
7699 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7700 		return MBX_NOT_FINISHED;
7701 	}
7702 	if (unlikely(phba->sli.mbox_active)) {
7703 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7704 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7705 				"0384 There is pending active mailbox cmd\n");
7706 		return MBX_NOT_FINISHED;
7707 	}
7708 	/* Take the mailbox command service token */
7709 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7710 
7711 	/* Get the next mailbox command from head of queue */
7712 	mboxq = lpfc_mbox_get(phba);
7713 
7714 	/* If no more mailbox command waiting for post, we're done */
7715 	if (!mboxq) {
7716 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7717 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7718 		return MBX_SUCCESS;
7719 	}
7720 	phba->sli.mbox_active = mboxq;
7721 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7722 
7723 	/* Check device readiness for posting mailbox command */
7724 	rc = lpfc_mbox_dev_check(phba);
7725 	if (unlikely(rc))
7726 		/* Driver clean routine will clean up pending mailbox */
7727 		goto out_not_finished;
7728 
7729 	/* Prepare the mbox command to be posted */
7730 	mqe = &mboxq->u.mqe;
7731 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
7732 
7733 	/* Start timer for the mbox_tmo and log some mailbox post messages */
7734 	mod_timer(&psli->mbox_tmo, (jiffies +
7735 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
7736 
7737 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7738 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
7739 			"x%x x%x\n",
7740 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
7741 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7742 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7743 			phba->pport->port_state, psli->sli_flag);
7744 
7745 	if (mbx_cmnd != MBX_HEARTBEAT) {
7746 		if (mboxq->vport) {
7747 			lpfc_debugfs_disc_trc(mboxq->vport,
7748 				LPFC_DISC_TRC_MBOX_VPORT,
7749 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
7750 				mbx_cmnd, mqe->un.mb_words[0],
7751 				mqe->un.mb_words[1]);
7752 		} else {
7753 			lpfc_debugfs_disc_trc(phba->pport,
7754 				LPFC_DISC_TRC_MBOX,
7755 				"MBOX Send: cmd:x%x mb:x%x x%x",
7756 				mbx_cmnd, mqe->un.mb_words[0],
7757 				mqe->un.mb_words[1]);
7758 		}
7759 	}
7760 	psli->slistat.mbox_cmd++;
7761 
7762 	/* Post the mailbox command to the port */
7763 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
7764 	if (rc != MBX_SUCCESS) {
7765 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7766 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
7767 				"cannot issue Data: x%x x%x\n",
7768 				mboxq->vport ? mboxq->vport->vpi : 0,
7769 				mboxq->u.mb.mbxCommand,
7770 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7771 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7772 				psli->sli_flag, MBX_NOWAIT);
7773 		goto out_not_finished;
7774 	}
7775 
7776 	return rc;
7777 
7778 out_not_finished:
7779 	spin_lock_irqsave(&phba->hbalock, iflags);
7780 	if (phba->sli.mbox_active) {
7781 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
7782 		__lpfc_mbox_cmpl_put(phba, mboxq);
7783 		/* Release the token */
7784 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7785 		phba->sli.mbox_active = NULL;
7786 	}
7787 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7788 
7789 	return MBX_NOT_FINISHED;
7790 }
7791 
7792 /**
7793  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
7794  * @phba: Pointer to HBA context object.
7795  * @pmbox: Pointer to mailbox object.
7796  * @flag: Flag indicating how the mailbox need to be processed.
7797  *
7798  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
7799  * the API jump table function pointer from the lpfc_hba struct.
7800  *
7801  * Return codes the caller owns the mailbox command after the return of the
7802  * function.
7803  **/
7804 int
7805 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
7806 {
7807 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
7808 }
7809 
7810 /**
7811  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
7812  * @phba: The hba struct for which this call is being executed.
7813  * @dev_grp: The HBA PCI-Device group number.
7814  *
7815  * This routine sets up the mbox interface API function jump table in @phba
7816  * struct.
7817  * Returns: 0 - success, -ENODEV - failure.
7818  **/
7819 int
7820 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7821 {
7822 
7823 	switch (dev_grp) {
7824 	case LPFC_PCI_DEV_LP:
7825 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
7826 		phba->lpfc_sli_handle_slow_ring_event =
7827 				lpfc_sli_handle_slow_ring_event_s3;
7828 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
7829 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
7830 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
7831 		break;
7832 	case LPFC_PCI_DEV_OC:
7833 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
7834 		phba->lpfc_sli_handle_slow_ring_event =
7835 				lpfc_sli_handle_slow_ring_event_s4;
7836 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
7837 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
7838 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
7839 		break;
7840 	default:
7841 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7842 				"1420 Invalid HBA PCI-device group: 0x%x\n",
7843 				dev_grp);
7844 		return -ENODEV;
7845 		break;
7846 	}
7847 	return 0;
7848 }
7849 
7850 /**
7851  * __lpfc_sli_ringtx_put - Add an iocb to the txq
7852  * @phba: Pointer to HBA context object.
7853  * @pring: Pointer to driver SLI ring object.
7854  * @piocb: Pointer to address of newly added command iocb.
7855  *
7856  * This function is called with hbalock held to add a command
7857  * iocb to the txq when SLI layer cannot submit the command iocb
7858  * to the ring.
7859  **/
7860 void
7861 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
7862 		    struct lpfc_iocbq *piocb)
7863 {
7864 	/* Insert the caller's iocb in the txq tail for later processing. */
7865 	list_add_tail(&piocb->list, &pring->txq);
7866 }
7867 
7868 /**
7869  * lpfc_sli_next_iocb - Get the next iocb in the txq
7870  * @phba: Pointer to HBA context object.
7871  * @pring: Pointer to driver SLI ring object.
7872  * @piocb: Pointer to address of newly added command iocb.
7873  *
7874  * This function is called with hbalock held before a new
7875  * iocb is submitted to the firmware. This function checks
7876  * txq to flush the iocbs in txq to Firmware before
7877  * submitting new iocbs to the Firmware.
7878  * If there are iocbs in the txq which need to be submitted
7879  * to firmware, lpfc_sli_next_iocb returns the first element
7880  * of the txq after dequeuing it from txq.
7881  * If there is no iocb in the txq then the function will return
7882  * *piocb and *piocb is set to NULL. Caller needs to check
7883  * *piocb to find if there are more commands in the txq.
7884  **/
7885 static struct lpfc_iocbq *
7886 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
7887 		   struct lpfc_iocbq **piocb)
7888 {
7889 	struct lpfc_iocbq * nextiocb;
7890 
7891 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
7892 	if (!nextiocb) {
7893 		nextiocb = *piocb;
7894 		*piocb = NULL;
7895 	}
7896 
7897 	return nextiocb;
7898 }
7899 
7900 /**
7901  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
7902  * @phba: Pointer to HBA context object.
7903  * @ring_number: SLI ring number to issue iocb on.
7904  * @piocb: Pointer to command iocb.
7905  * @flag: Flag indicating if this command can be put into txq.
7906  *
7907  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
7908  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
7909  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
7910  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
7911  * this function allows only iocbs for posting buffers. This function finds
7912  * next available slot in the command ring and posts the command to the
7913  * available slot and writes the port attention register to request HBA start
7914  * processing new iocb. If there is no slot available in the ring and
7915  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
7916  * the function returns IOCB_BUSY.
7917  *
7918  * This function is called with hbalock held. The function will return success
7919  * after it successfully submit the iocb to firmware or after adding to the
7920  * txq.
7921  **/
7922 static int
7923 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
7924 		    struct lpfc_iocbq *piocb, uint32_t flag)
7925 {
7926 	struct lpfc_iocbq *nextiocb;
7927 	IOCB_t *iocb;
7928 	struct lpfc_sli_ring *pring = &phba->sli.ring[ring_number];
7929 
7930 	if (piocb->iocb_cmpl && (!piocb->vport) &&
7931 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
7932 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
7933 		lpfc_printf_log(phba, KERN_ERR,
7934 				LOG_SLI | LOG_VPORT,
7935 				"1807 IOCB x%x failed. No vport\n",
7936 				piocb->iocb.ulpCommand);
7937 		dump_stack();
7938 		return IOCB_ERROR;
7939 	}
7940 
7941 
7942 	/* If the PCI channel is in offline state, do not post iocbs. */
7943 	if (unlikely(pci_channel_offline(phba->pcidev)))
7944 		return IOCB_ERROR;
7945 
7946 	/* If HBA has a deferred error attention, fail the iocb. */
7947 	if (unlikely(phba->hba_flag & DEFER_ERATT))
7948 		return IOCB_ERROR;
7949 
7950 	/*
7951 	 * We should never get an IOCB if we are in a < LINK_DOWN state
7952 	 */
7953 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
7954 		return IOCB_ERROR;
7955 
7956 	/*
7957 	 * Check to see if we are blocking IOCB processing because of a
7958 	 * outstanding event.
7959 	 */
7960 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
7961 		goto iocb_busy;
7962 
7963 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
7964 		/*
7965 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
7966 		 * can be issued if the link is not up.
7967 		 */
7968 		switch (piocb->iocb.ulpCommand) {
7969 		case CMD_GEN_REQUEST64_CR:
7970 		case CMD_GEN_REQUEST64_CX:
7971 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
7972 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
7973 					FC_RCTL_DD_UNSOL_CMD) ||
7974 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
7975 					MENLO_TRANSPORT_TYPE))
7976 
7977 				goto iocb_busy;
7978 			break;
7979 		case CMD_QUE_RING_BUF_CN:
7980 		case CMD_QUE_RING_BUF64_CN:
7981 			/*
7982 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
7983 			 * completion, iocb_cmpl MUST be 0.
7984 			 */
7985 			if (piocb->iocb_cmpl)
7986 				piocb->iocb_cmpl = NULL;
7987 			/*FALLTHROUGH*/
7988 		case CMD_CREATE_XRI_CR:
7989 		case CMD_CLOSE_XRI_CN:
7990 		case CMD_CLOSE_XRI_CX:
7991 			break;
7992 		default:
7993 			goto iocb_busy;
7994 		}
7995 
7996 	/*
7997 	 * For FCP commands, we must be in a state where we can process link
7998 	 * attention events.
7999 	 */
8000 	} else if (unlikely(pring->ringno == phba->sli.fcp_ring &&
8001 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
8002 		goto iocb_busy;
8003 	}
8004 
8005 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
8006 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
8007 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
8008 
8009 	if (iocb)
8010 		lpfc_sli_update_ring(phba, pring);
8011 	else
8012 		lpfc_sli_update_full_ring(phba, pring);
8013 
8014 	if (!piocb)
8015 		return IOCB_SUCCESS;
8016 
8017 	goto out_busy;
8018 
8019  iocb_busy:
8020 	pring->stats.iocb_cmd_delay++;
8021 
8022  out_busy:
8023 
8024 	if (!(flag & SLI_IOCB_RET_IOCB)) {
8025 		__lpfc_sli_ringtx_put(phba, pring, piocb);
8026 		return IOCB_SUCCESS;
8027 	}
8028 
8029 	return IOCB_BUSY;
8030 }
8031 
8032 /**
8033  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
8034  * @phba: Pointer to HBA context object.
8035  * @piocb: Pointer to command iocb.
8036  * @sglq: Pointer to the scatter gather queue object.
8037  *
8038  * This routine converts the bpl or bde that is in the IOCB
8039  * to a sgl list for the sli4 hardware. The physical address
8040  * of the bpl/bde is converted back to a virtual address.
8041  * If the IOCB contains a BPL then the list of BDE's is
8042  * converted to sli4_sge's. If the IOCB contains a single
8043  * BDE then it is converted to a single sli_sge.
8044  * The IOCB is still in cpu endianess so the contents of
8045  * the bpl can be used without byte swapping.
8046  *
8047  * Returns valid XRI = Success, NO_XRI = Failure.
8048 **/
8049 static uint16_t
8050 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
8051 		struct lpfc_sglq *sglq)
8052 {
8053 	uint16_t xritag = NO_XRI;
8054 	struct ulp_bde64 *bpl = NULL;
8055 	struct ulp_bde64 bde;
8056 	struct sli4_sge *sgl  = NULL;
8057 	struct lpfc_dmabuf *dmabuf;
8058 	IOCB_t *icmd;
8059 	int numBdes = 0;
8060 	int i = 0;
8061 	uint32_t offset = 0; /* accumulated offset in the sg request list */
8062 	int inbound = 0; /* number of sg reply entries inbound from firmware */
8063 
8064 	if (!piocbq || !sglq)
8065 		return xritag;
8066 
8067 	sgl  = (struct sli4_sge *)sglq->sgl;
8068 	icmd = &piocbq->iocb;
8069 	if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
8070 		return sglq->sli4_xritag;
8071 	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
8072 		numBdes = icmd->un.genreq64.bdl.bdeSize /
8073 				sizeof(struct ulp_bde64);
8074 		/* The addrHigh and addrLow fields within the IOCB
8075 		 * have not been byteswapped yet so there is no
8076 		 * need to swap them back.
8077 		 */
8078 		if (piocbq->context3)
8079 			dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
8080 		else
8081 			return xritag;
8082 
8083 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
8084 		if (!bpl)
8085 			return xritag;
8086 
8087 		for (i = 0; i < numBdes; i++) {
8088 			/* Should already be byte swapped. */
8089 			sgl->addr_hi = bpl->addrHigh;
8090 			sgl->addr_lo = bpl->addrLow;
8091 
8092 			sgl->word2 = le32_to_cpu(sgl->word2);
8093 			if ((i+1) == numBdes)
8094 				bf_set(lpfc_sli4_sge_last, sgl, 1);
8095 			else
8096 				bf_set(lpfc_sli4_sge_last, sgl, 0);
8097 			/* swap the size field back to the cpu so we
8098 			 * can assign it to the sgl.
8099 			 */
8100 			bde.tus.w = le32_to_cpu(bpl->tus.w);
8101 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
8102 			/* The offsets in the sgl need to be accumulated
8103 			 * separately for the request and reply lists.
8104 			 * The request is always first, the reply follows.
8105 			 */
8106 			if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
8107 				/* add up the reply sg entries */
8108 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
8109 					inbound++;
8110 				/* first inbound? reset the offset */
8111 				if (inbound == 1)
8112 					offset = 0;
8113 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
8114 				bf_set(lpfc_sli4_sge_type, sgl,
8115 					LPFC_SGE_TYPE_DATA);
8116 				offset += bde.tus.f.bdeSize;
8117 			}
8118 			sgl->word2 = cpu_to_le32(sgl->word2);
8119 			bpl++;
8120 			sgl++;
8121 		}
8122 	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
8123 			/* The addrHigh and addrLow fields of the BDE have not
8124 			 * been byteswapped yet so they need to be swapped
8125 			 * before putting them in the sgl.
8126 			 */
8127 			sgl->addr_hi =
8128 				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
8129 			sgl->addr_lo =
8130 				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
8131 			sgl->word2 = le32_to_cpu(sgl->word2);
8132 			bf_set(lpfc_sli4_sge_last, sgl, 1);
8133 			sgl->word2 = cpu_to_le32(sgl->word2);
8134 			sgl->sge_len =
8135 				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
8136 	}
8137 	return sglq->sli4_xritag;
8138 }
8139 
8140 /**
8141  * lpfc_sli_iocb2wqe - Convert the IOCB to a work queue entry.
8142  * @phba: Pointer to HBA context object.
8143  * @piocb: Pointer to command iocb.
8144  * @wqe: Pointer to the work queue entry.
8145  *
8146  * This routine converts the iocb command to its Work Queue Entry
8147  * equivalent. The wqe pointer should not have any fields set when
8148  * this routine is called because it will memcpy over them.
8149  * This routine does not set the CQ_ID or the WQEC bits in the
8150  * wqe.
8151  *
8152  * Returns: 0 = Success, IOCB_ERROR = Failure.
8153  **/
8154 static int
8155 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
8156 		union lpfc_wqe *wqe)
8157 {
8158 	uint32_t xmit_len = 0, total_len = 0;
8159 	uint8_t ct = 0;
8160 	uint32_t fip;
8161 	uint32_t abort_tag;
8162 	uint8_t command_type = ELS_COMMAND_NON_FIP;
8163 	uint8_t cmnd;
8164 	uint16_t xritag;
8165 	uint16_t abrt_iotag;
8166 	struct lpfc_iocbq *abrtiocbq;
8167 	struct ulp_bde64 *bpl = NULL;
8168 	uint32_t els_id = LPFC_ELS_ID_DEFAULT;
8169 	int numBdes, i;
8170 	struct ulp_bde64 bde;
8171 	struct lpfc_nodelist *ndlp;
8172 	uint32_t *pcmd;
8173 	uint32_t if_type;
8174 
8175 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
8176 	/* The fcp commands will set command type */
8177 	if (iocbq->iocb_flag &  LPFC_IO_FCP)
8178 		command_type = FCP_COMMAND;
8179 	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
8180 		command_type = ELS_COMMAND_FIP;
8181 	else
8182 		command_type = ELS_COMMAND_NON_FIP;
8183 
8184 	/* Some of the fields are in the right position already */
8185 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
8186 	abort_tag = (uint32_t) iocbq->iotag;
8187 	xritag = iocbq->sli4_xritag;
8188 	wqe->generic.wqe_com.word7 = 0; /* The ct field has moved so reset */
8189 	wqe->generic.wqe_com.word10 = 0;
8190 	/* words0-2 bpl convert bde */
8191 	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
8192 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
8193 				sizeof(struct ulp_bde64);
8194 		bpl  = (struct ulp_bde64 *)
8195 			((struct lpfc_dmabuf *)iocbq->context3)->virt;
8196 		if (!bpl)
8197 			return IOCB_ERROR;
8198 
8199 		/* Should already be byte swapped. */
8200 		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
8201 		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
8202 		/* swap the size field back to the cpu so we
8203 		 * can assign it to the sgl.
8204 		 */
8205 		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
8206 		xmit_len = wqe->generic.bde.tus.f.bdeSize;
8207 		total_len = 0;
8208 		for (i = 0; i < numBdes; i++) {
8209 			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
8210 			total_len += bde.tus.f.bdeSize;
8211 		}
8212 	} else
8213 		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
8214 
8215 	iocbq->iocb.ulpIoTag = iocbq->iotag;
8216 	cmnd = iocbq->iocb.ulpCommand;
8217 
8218 	switch (iocbq->iocb.ulpCommand) {
8219 	case CMD_ELS_REQUEST64_CR:
8220 		if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
8221 			ndlp = iocbq->context_un.ndlp;
8222 		else
8223 			ndlp = (struct lpfc_nodelist *)iocbq->context1;
8224 		if (!iocbq->iocb.ulpLe) {
8225 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8226 				"2007 Only Limited Edition cmd Format"
8227 				" supported 0x%x\n",
8228 				iocbq->iocb.ulpCommand);
8229 			return IOCB_ERROR;
8230 		}
8231 
8232 		wqe->els_req.payload_len = xmit_len;
8233 		/* Els_reguest64 has a TMO */
8234 		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
8235 			iocbq->iocb.ulpTimeout);
8236 		/* Need a VF for word 4 set the vf bit*/
8237 		bf_set(els_req64_vf, &wqe->els_req, 0);
8238 		/* And a VFID for word 12 */
8239 		bf_set(els_req64_vfid, &wqe->els_req, 0);
8240 		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
8241 		bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8242 		       iocbq->iocb.ulpContext);
8243 		bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
8244 		bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
8245 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
8246 		if (command_type == ELS_COMMAND_FIP)
8247 			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
8248 					>> LPFC_FIP_ELS_ID_SHIFT);
8249 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
8250 					iocbq->context2)->virt);
8251 		if_type = bf_get(lpfc_sli_intf_if_type,
8252 					&phba->sli4_hba.sli_intf);
8253 		if (if_type == LPFC_SLI_INTF_IF_TYPE_2) {
8254 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
8255 				*pcmd == ELS_CMD_SCR ||
8256 				*pcmd == ELS_CMD_FDISC ||
8257 				*pcmd == ELS_CMD_LOGO ||
8258 				*pcmd == ELS_CMD_PLOGI)) {
8259 				bf_set(els_req64_sp, &wqe->els_req, 1);
8260 				bf_set(els_req64_sid, &wqe->els_req,
8261 					iocbq->vport->fc_myDID);
8262 				if ((*pcmd == ELS_CMD_FLOGI) &&
8263 					!(phba->fc_topology ==
8264 						LPFC_TOPOLOGY_LOOP))
8265 					bf_set(els_req64_sid, &wqe->els_req, 0);
8266 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
8267 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8268 					phba->vpi_ids[iocbq->vport->vpi]);
8269 			} else if (pcmd && iocbq->context1) {
8270 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
8271 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8272 					phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8273 			}
8274 		}
8275 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
8276 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8277 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
8278 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
8279 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
8280 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
8281 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
8282 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
8283 		wqe->els_req.max_response_payload_len = total_len - xmit_len;
8284 		break;
8285 	case CMD_XMIT_SEQUENCE64_CX:
8286 		bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
8287 		       iocbq->iocb.un.ulpWord[3]);
8288 		bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
8289 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
8290 		/* The entire sequence is transmitted for this IOCB */
8291 		xmit_len = total_len;
8292 		cmnd = CMD_XMIT_SEQUENCE64_CR;
8293 		if (phba->link_flag & LS_LOOPBACK_MODE)
8294 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
8295 	case CMD_XMIT_SEQUENCE64_CR:
8296 		/* word3 iocb=io_tag32 wqe=reserved */
8297 		wqe->xmit_sequence.rsvd3 = 0;
8298 		/* word4 relative_offset memcpy */
8299 		/* word5 r_ctl/df_ctl memcpy */
8300 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
8301 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
8302 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
8303 		       LPFC_WQE_IOD_WRITE);
8304 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
8305 		       LPFC_WQE_LENLOC_WORD12);
8306 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
8307 		wqe->xmit_sequence.xmit_len = xmit_len;
8308 		command_type = OTHER_COMMAND;
8309 		break;
8310 	case CMD_XMIT_BCAST64_CN:
8311 		/* word3 iocb=iotag32 wqe=seq_payload_len */
8312 		wqe->xmit_bcast64.seq_payload_len = xmit_len;
8313 		/* word4 iocb=rsvd wqe=rsvd */
8314 		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
8315 		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
8316 		bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
8317 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8318 		bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
8319 		bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
8320 		bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
8321 		       LPFC_WQE_LENLOC_WORD3);
8322 		bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
8323 		break;
8324 	case CMD_FCP_IWRITE64_CR:
8325 		command_type = FCP_COMMAND_DATA_OUT;
8326 		/* word3 iocb=iotag wqe=payload_offset_len */
8327 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8328 		bf_set(payload_offset_len, &wqe->fcp_iwrite,
8329 		       xmit_len + sizeof(struct fcp_rsp));
8330 		bf_set(cmd_buff_len, &wqe->fcp_iwrite,
8331 		       0);
8332 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
8333 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
8334 		bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
8335 		       iocbq->iocb.ulpFCP2Rcvy);
8336 		bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
8337 		/* Always open the exchange */
8338 		bf_set(wqe_xc, &wqe->fcp_iwrite.wqe_com, 0);
8339 		bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
8340 		bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
8341 		       LPFC_WQE_LENLOC_WORD4);
8342 		bf_set(wqe_ebde_cnt, &wqe->fcp_iwrite.wqe_com, 0);
8343 		bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
8344 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
8345 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8346 			bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
8347 			if (phba->cfg_XLanePriority) {
8348 				bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
8349 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
8350 				       (phba->cfg_XLanePriority << 1));
8351 			}
8352 		}
8353 		break;
8354 	case CMD_FCP_IREAD64_CR:
8355 		/* word3 iocb=iotag wqe=payload_offset_len */
8356 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8357 		bf_set(payload_offset_len, &wqe->fcp_iread,
8358 		       xmit_len + sizeof(struct fcp_rsp));
8359 		bf_set(cmd_buff_len, &wqe->fcp_iread,
8360 		       0);
8361 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
8362 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
8363 		bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
8364 		       iocbq->iocb.ulpFCP2Rcvy);
8365 		bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
8366 		/* Always open the exchange */
8367 		bf_set(wqe_xc, &wqe->fcp_iread.wqe_com, 0);
8368 		bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
8369 		bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
8370 		       LPFC_WQE_LENLOC_WORD4);
8371 		bf_set(wqe_ebde_cnt, &wqe->fcp_iread.wqe_com, 0);
8372 		bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
8373 		bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
8374 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8375 			bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
8376 			if (phba->cfg_XLanePriority) {
8377 				bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
8378 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
8379 				       (phba->cfg_XLanePriority << 1));
8380 			}
8381 		}
8382 		break;
8383 	case CMD_FCP_ICMND64_CR:
8384 		/* word3 iocb=iotag wqe=payload_offset_len */
8385 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8386 		bf_set(payload_offset_len, &wqe->fcp_icmd,
8387 		       xmit_len + sizeof(struct fcp_rsp));
8388 		bf_set(cmd_buff_len, &wqe->fcp_icmd,
8389 		       0);
8390 		/* word3 iocb=IO_TAG wqe=reserved */
8391 		bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
8392 		/* Always open the exchange */
8393 		bf_set(wqe_xc, &wqe->fcp_icmd.wqe_com, 0);
8394 		bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
8395 		bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
8396 		bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
8397 		bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
8398 		       LPFC_WQE_LENLOC_NONE);
8399 		bf_set(wqe_ebde_cnt, &wqe->fcp_icmd.wqe_com, 0);
8400 		bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
8401 		       iocbq->iocb.ulpFCP2Rcvy);
8402 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8403 			bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
8404 			if (phba->cfg_XLanePriority) {
8405 				bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
8406 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
8407 				       (phba->cfg_XLanePriority << 1));
8408 			}
8409 		}
8410 		break;
8411 	case CMD_GEN_REQUEST64_CR:
8412 		/* For this command calculate the xmit length of the
8413 		 * request bde.
8414 		 */
8415 		xmit_len = 0;
8416 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
8417 			sizeof(struct ulp_bde64);
8418 		for (i = 0; i < numBdes; i++) {
8419 			bde.tus.w = le32_to_cpu(bpl[i].tus.w);
8420 			if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
8421 				break;
8422 			xmit_len += bde.tus.f.bdeSize;
8423 		}
8424 		/* word3 iocb=IO_TAG wqe=request_payload_len */
8425 		wqe->gen_req.request_payload_len = xmit_len;
8426 		/* word4 iocb=parameter wqe=relative_offset memcpy */
8427 		/* word5 [rctl, type, df_ctl, la] copied in memcpy */
8428 		/* word6 context tag copied in memcpy */
8429 		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
8430 			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
8431 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8432 				"2015 Invalid CT %x command 0x%x\n",
8433 				ct, iocbq->iocb.ulpCommand);
8434 			return IOCB_ERROR;
8435 		}
8436 		bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
8437 		bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
8438 		bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
8439 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
8440 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
8441 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
8442 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
8443 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
8444 		wqe->gen_req.max_response_payload_len = total_len - xmit_len;
8445 		command_type = OTHER_COMMAND;
8446 		break;
8447 	case CMD_XMIT_ELS_RSP64_CX:
8448 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
8449 		/* words0-2 BDE memcpy */
8450 		/* word3 iocb=iotag32 wqe=response_payload_len */
8451 		wqe->xmit_els_rsp.response_payload_len = xmit_len;
8452 		/* word4 */
8453 		wqe->xmit_els_rsp.word4 = 0;
8454 		/* word5 iocb=rsvd wge=did */
8455 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
8456 			 iocbq->iocb.un.xseq64.xmit_els_remoteID);
8457 
8458 		if_type = bf_get(lpfc_sli_intf_if_type,
8459 					&phba->sli4_hba.sli_intf);
8460 		if (if_type == LPFC_SLI_INTF_IF_TYPE_2) {
8461 			if (iocbq->vport->fc_flag & FC_PT2PT) {
8462 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
8463 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
8464 					iocbq->vport->fc_myDID);
8465 				if (iocbq->vport->fc_myDID == Fabric_DID) {
8466 					bf_set(wqe_els_did,
8467 						&wqe->xmit_els_rsp.wqe_dest, 0);
8468 				}
8469 			}
8470 		}
8471 		bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
8472 		       ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8473 		bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
8474 		bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
8475 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
8476 		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
8477 			bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
8478 			       phba->vpi_ids[iocbq->vport->vpi]);
8479 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
8480 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
8481 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
8482 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
8483 		       LPFC_WQE_LENLOC_WORD3);
8484 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
8485 		bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
8486 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8487 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
8488 					iocbq->context2)->virt);
8489 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
8490 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
8491 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
8492 					iocbq->vport->fc_myDID);
8493 				bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
8494 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
8495 					phba->vpi_ids[phba->pport->vpi]);
8496 		}
8497 		command_type = OTHER_COMMAND;
8498 		break;
8499 	case CMD_CLOSE_XRI_CN:
8500 	case CMD_ABORT_XRI_CN:
8501 	case CMD_ABORT_XRI_CX:
8502 		/* words 0-2 memcpy should be 0 rserved */
8503 		/* port will send abts */
8504 		abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
8505 		if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
8506 			abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
8507 			fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
8508 		} else
8509 			fip = 0;
8510 
8511 		if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
8512 			/*
8513 			 * The link is down, or the command was ELS_FIP
8514 			 * so the fw does not need to send abts
8515 			 * on the wire.
8516 			 */
8517 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
8518 		else
8519 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
8520 		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
8521 		/* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
8522 		wqe->abort_cmd.rsrvd5 = 0;
8523 		bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
8524 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8525 		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
8526 		/*
8527 		 * The abort handler will send us CMD_ABORT_XRI_CN or
8528 		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
8529 		 */
8530 		bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
8531 		bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
8532 		bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
8533 		       LPFC_WQE_LENLOC_NONE);
8534 		cmnd = CMD_ABORT_XRI_CX;
8535 		command_type = OTHER_COMMAND;
8536 		xritag = 0;
8537 		break;
8538 	case CMD_XMIT_BLS_RSP64_CX:
8539 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
8540 		/* As BLS ABTS RSP WQE is very different from other WQEs,
8541 		 * we re-construct this WQE here based on information in
8542 		 * iocbq from scratch.
8543 		 */
8544 		memset(wqe, 0, sizeof(union lpfc_wqe));
8545 		/* OX_ID is invariable to who sent ABTS to CT exchange */
8546 		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
8547 		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
8548 		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
8549 		    LPFC_ABTS_UNSOL_INT) {
8550 			/* ABTS sent by initiator to CT exchange, the
8551 			 * RX_ID field will be filled with the newly
8552 			 * allocated responder XRI.
8553 			 */
8554 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
8555 			       iocbq->sli4_xritag);
8556 		} else {
8557 			/* ABTS sent by responder to CT exchange, the
8558 			 * RX_ID field will be filled with the responder
8559 			 * RX_ID from ABTS.
8560 			 */
8561 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
8562 			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
8563 		}
8564 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
8565 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
8566 
8567 		/* Use CT=VPI */
8568 		bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
8569 			ndlp->nlp_DID);
8570 		bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
8571 			iocbq->iocb.ulpContext);
8572 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
8573 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
8574 			phba->vpi_ids[phba->pport->vpi]);
8575 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
8576 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
8577 		       LPFC_WQE_LENLOC_NONE);
8578 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
8579 		command_type = OTHER_COMMAND;
8580 		if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
8581 			bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
8582 			       bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
8583 			bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
8584 			       bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
8585 			bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
8586 			       bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
8587 		}
8588 
8589 		break;
8590 	case CMD_XRI_ABORTED_CX:
8591 	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
8592 	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
8593 	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
8594 	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
8595 	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
8596 	default:
8597 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8598 				"2014 Invalid command 0x%x\n",
8599 				iocbq->iocb.ulpCommand);
8600 		return IOCB_ERROR;
8601 		break;
8602 	}
8603 
8604 	if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
8605 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
8606 	else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
8607 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
8608 	else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
8609 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
8610 	iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
8611 			      LPFC_IO_DIF_INSERT);
8612 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
8613 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
8614 	wqe->generic.wqe_com.abort_tag = abort_tag;
8615 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
8616 	bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
8617 	bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
8618 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
8619 	return 0;
8620 }
8621 
8622 /**
8623  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
8624  * @phba: Pointer to HBA context object.
8625  * @ring_number: SLI ring number to issue iocb on.
8626  * @piocb: Pointer to command iocb.
8627  * @flag: Flag indicating if this command can be put into txq.
8628  *
8629  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
8630  * an iocb command to an HBA with SLI-4 interface spec.
8631  *
8632  * This function is called with hbalock held. The function will return success
8633  * after it successfully submit the iocb to firmware or after adding to the
8634  * txq.
8635  **/
8636 static int
8637 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
8638 			 struct lpfc_iocbq *piocb, uint32_t flag)
8639 {
8640 	struct lpfc_sglq *sglq;
8641 	union lpfc_wqe wqe;
8642 	struct lpfc_queue *wq;
8643 	struct lpfc_sli_ring *pring = &phba->sli.ring[ring_number];
8644 
8645 	if (piocb->sli4_xritag == NO_XRI) {
8646 		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
8647 		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
8648 			sglq = NULL;
8649 		else {
8650 			if (!list_empty(&pring->txq)) {
8651 				if (!(flag & SLI_IOCB_RET_IOCB)) {
8652 					__lpfc_sli_ringtx_put(phba,
8653 						pring, piocb);
8654 					return IOCB_SUCCESS;
8655 				} else {
8656 					return IOCB_BUSY;
8657 				}
8658 			} else {
8659 				sglq = __lpfc_sli_get_sglq(phba, piocb);
8660 				if (!sglq) {
8661 					if (!(flag & SLI_IOCB_RET_IOCB)) {
8662 						__lpfc_sli_ringtx_put(phba,
8663 								pring,
8664 								piocb);
8665 						return IOCB_SUCCESS;
8666 					} else
8667 						return IOCB_BUSY;
8668 				}
8669 			}
8670 		}
8671 	} else if (piocb->iocb_flag &  LPFC_IO_FCP) {
8672 		/* These IO's already have an XRI and a mapped sgl. */
8673 		sglq = NULL;
8674 	} else {
8675 		/*
8676 		 * This is a continuation of a commandi,(CX) so this
8677 		 * sglq is on the active list
8678 		 */
8679 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
8680 		if (!sglq)
8681 			return IOCB_ERROR;
8682 	}
8683 
8684 	if (sglq) {
8685 		piocb->sli4_lxritag = sglq->sli4_lxritag;
8686 		piocb->sli4_xritag = sglq->sli4_xritag;
8687 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
8688 			return IOCB_ERROR;
8689 	}
8690 
8691 	if (lpfc_sli4_iocb2wqe(phba, piocb, &wqe))
8692 		return IOCB_ERROR;
8693 
8694 	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
8695 	    (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
8696 		if (!phba->cfg_fof || (!(piocb->iocb_flag & LPFC_IO_OAS))) {
8697 			wq = phba->sli4_hba.fcp_wq[piocb->fcp_wqidx];
8698 		} else {
8699 			wq = phba->sli4_hba.oas_wq;
8700 		}
8701 		if (lpfc_sli4_wq_put(wq, &wqe))
8702 			return IOCB_ERROR;
8703 	} else {
8704 		if (unlikely(!phba->sli4_hba.els_wq))
8705 			return IOCB_ERROR;
8706 		if (lpfc_sli4_wq_put(phba->sli4_hba.els_wq, &wqe))
8707 			return IOCB_ERROR;
8708 	}
8709 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
8710 
8711 	return 0;
8712 }
8713 
8714 /**
8715  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
8716  *
8717  * This routine wraps the actual lockless version for issusing IOCB function
8718  * pointer from the lpfc_hba struct.
8719  *
8720  * Return codes:
8721  * 	IOCB_ERROR - Error
8722  * 	IOCB_SUCCESS - Success
8723  * 	IOCB_BUSY - Busy
8724  **/
8725 int
8726 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
8727 		struct lpfc_iocbq *piocb, uint32_t flag)
8728 {
8729 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
8730 }
8731 
8732 /**
8733  * lpfc_sli_api_table_setup - Set up sli api function jump table
8734  * @phba: The hba struct for which this call is being executed.
8735  * @dev_grp: The HBA PCI-Device group number.
8736  *
8737  * This routine sets up the SLI interface API function jump table in @phba
8738  * struct.
8739  * Returns: 0 - success, -ENODEV - failure.
8740  **/
8741 int
8742 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8743 {
8744 
8745 	switch (dev_grp) {
8746 	case LPFC_PCI_DEV_LP:
8747 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
8748 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
8749 		break;
8750 	case LPFC_PCI_DEV_OC:
8751 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
8752 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
8753 		break;
8754 	default:
8755 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8756 				"1419 Invalid HBA PCI-device group: 0x%x\n",
8757 				dev_grp);
8758 		return -ENODEV;
8759 		break;
8760 	}
8761 	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
8762 	return 0;
8763 }
8764 
8765 /**
8766  * lpfc_sli_calc_ring - Calculates which ring to use
8767  * @phba: Pointer to HBA context object.
8768  * @ring_number: Initial ring
8769  * @piocb: Pointer to command iocb.
8770  *
8771  * For SLI4, FCP IO can deferred to one fo many WQs, based on
8772  * fcp_wqidx, thus we need to calculate the corresponding ring.
8773  * Since ABORTS must go on the same WQ of the command they are
8774  * aborting, we use command's fcp_wqidx.
8775  */
8776 int
8777 lpfc_sli_calc_ring(struct lpfc_hba *phba, uint32_t ring_number,
8778 		    struct lpfc_iocbq *piocb)
8779 {
8780 	if (phba->sli_rev < LPFC_SLI_REV4)
8781 		return ring_number;
8782 
8783 	if (piocb->iocb_flag &  (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
8784 		if (!(phba->cfg_fof) ||
8785 				(!(piocb->iocb_flag & LPFC_IO_FOF))) {
8786 			if (unlikely(!phba->sli4_hba.fcp_wq))
8787 				return LPFC_HBA_ERROR;
8788 			/*
8789 			 * for abort iocb fcp_wqidx should already
8790 			 * be setup based on what work queue we used.
8791 			 */
8792 			if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX))
8793 				piocb->fcp_wqidx =
8794 					lpfc_sli4_scmd_to_wqidx_distr(phba,
8795 							      piocb->context1);
8796 			ring_number = MAX_SLI3_CONFIGURED_RINGS +
8797 				piocb->fcp_wqidx;
8798 		} else {
8799 			if (unlikely(!phba->sli4_hba.oas_wq))
8800 				return LPFC_HBA_ERROR;
8801 			piocb->fcp_wqidx = 0;
8802 			ring_number =  LPFC_FCP_OAS_RING;
8803 		}
8804 	}
8805 	return ring_number;
8806 }
8807 
8808 /**
8809  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
8810  * @phba: Pointer to HBA context object.
8811  * @pring: Pointer to driver SLI ring object.
8812  * @piocb: Pointer to command iocb.
8813  * @flag: Flag indicating if this command can be put into txq.
8814  *
8815  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
8816  * function. This function gets the hbalock and calls
8817  * __lpfc_sli_issue_iocb function and will return the error returned
8818  * by __lpfc_sli_issue_iocb function. This wrapper is used by
8819  * functions which do not hold hbalock.
8820  **/
8821 int
8822 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
8823 		    struct lpfc_iocbq *piocb, uint32_t flag)
8824 {
8825 	struct lpfc_fcp_eq_hdl *fcp_eq_hdl;
8826 	struct lpfc_sli_ring *pring;
8827 	struct lpfc_queue *fpeq;
8828 	struct lpfc_eqe *eqe;
8829 	unsigned long iflags;
8830 	int rc, idx;
8831 
8832 	if (phba->sli_rev == LPFC_SLI_REV4) {
8833 		ring_number = lpfc_sli_calc_ring(phba, ring_number, piocb);
8834 		if (unlikely(ring_number == LPFC_HBA_ERROR))
8835 			return IOCB_ERROR;
8836 		idx = piocb->fcp_wqidx;
8837 
8838 		pring = &phba->sli.ring[ring_number];
8839 		spin_lock_irqsave(&pring->ring_lock, iflags);
8840 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
8841 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
8842 
8843 		if (lpfc_fcp_look_ahead && (piocb->iocb_flag &  LPFC_IO_FCP)) {
8844 			fcp_eq_hdl = &phba->sli4_hba.fcp_eq_hdl[idx];
8845 
8846 			if (atomic_dec_and_test(&fcp_eq_hdl->
8847 				fcp_eq_in_use)) {
8848 
8849 				/* Get associated EQ with this index */
8850 				fpeq = phba->sli4_hba.hba_eq[idx];
8851 
8852 				/* Turn off interrupts from this EQ */
8853 				lpfc_sli4_eq_clr_intr(fpeq);
8854 
8855 				/*
8856 				 * Process all the events on FCP EQ
8857 				 */
8858 				while ((eqe = lpfc_sli4_eq_get(fpeq))) {
8859 					lpfc_sli4_hba_handle_eqe(phba,
8860 						eqe, idx);
8861 					fpeq->EQ_processed++;
8862 				}
8863 
8864 				/* Always clear and re-arm the EQ */
8865 				lpfc_sli4_eq_release(fpeq,
8866 					LPFC_QUEUE_REARM);
8867 			}
8868 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
8869 		}
8870 	} else {
8871 		/* For now, SLI2/3 will still use hbalock */
8872 		spin_lock_irqsave(&phba->hbalock, iflags);
8873 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
8874 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8875 	}
8876 	return rc;
8877 }
8878 
8879 /**
8880  * lpfc_extra_ring_setup - Extra ring setup function
8881  * @phba: Pointer to HBA context object.
8882  *
8883  * This function is called while driver attaches with the
8884  * HBA to setup the extra ring. The extra ring is used
8885  * only when driver needs to support target mode functionality
8886  * or IP over FC functionalities.
8887  *
8888  * This function is called with no lock held.
8889  **/
8890 static int
8891 lpfc_extra_ring_setup( struct lpfc_hba *phba)
8892 {
8893 	struct lpfc_sli *psli;
8894 	struct lpfc_sli_ring *pring;
8895 
8896 	psli = &phba->sli;
8897 
8898 	/* Adjust cmd/rsp ring iocb entries more evenly */
8899 
8900 	/* Take some away from the FCP ring */
8901 	pring = &psli->ring[psli->fcp_ring];
8902 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
8903 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
8904 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
8905 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
8906 
8907 	/* and give them to the extra ring */
8908 	pring = &psli->ring[psli->extra_ring];
8909 
8910 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
8911 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
8912 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
8913 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
8914 
8915 	/* Setup default profile for this ring */
8916 	pring->iotag_max = 4096;
8917 	pring->num_mask = 1;
8918 	pring->prt[0].profile = 0;      /* Mask 0 */
8919 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
8920 	pring->prt[0].type = phba->cfg_multi_ring_type;
8921 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
8922 	return 0;
8923 }
8924 
8925 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
8926  * @phba: Pointer to HBA context object.
8927  * @iocbq: Pointer to iocb object.
8928  *
8929  * The async_event handler calls this routine when it receives
8930  * an ASYNC_STATUS_CN event from the port.  The port generates
8931  * this event when an Abort Sequence request to an rport fails
8932  * twice in succession.  The abort could be originated by the
8933  * driver or by the port.  The ABTS could have been for an ELS
8934  * or FCP IO.  The port only generates this event when an ABTS
8935  * fails to complete after one retry.
8936  */
8937 static void
8938 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
8939 			  struct lpfc_iocbq *iocbq)
8940 {
8941 	struct lpfc_nodelist *ndlp = NULL;
8942 	uint16_t rpi = 0, vpi = 0;
8943 	struct lpfc_vport *vport = NULL;
8944 
8945 	/* The rpi in the ulpContext is vport-sensitive. */
8946 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
8947 	rpi = iocbq->iocb.ulpContext;
8948 
8949 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
8950 			"3092 Port generated ABTS async event "
8951 			"on vpi %d rpi %d status 0x%x\n",
8952 			vpi, rpi, iocbq->iocb.ulpStatus);
8953 
8954 	vport = lpfc_find_vport_by_vpid(phba, vpi);
8955 	if (!vport)
8956 		goto err_exit;
8957 	ndlp = lpfc_findnode_rpi(vport, rpi);
8958 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp))
8959 		goto err_exit;
8960 
8961 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
8962 		lpfc_sli_abts_recover_port(vport, ndlp);
8963 	return;
8964 
8965  err_exit:
8966 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
8967 			"3095 Event Context not found, no "
8968 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
8969 			iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
8970 			vpi, rpi);
8971 }
8972 
8973 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
8974  * @phba: pointer to HBA context object.
8975  * @ndlp: nodelist pointer for the impacted rport.
8976  * @axri: pointer to the wcqe containing the failed exchange.
8977  *
8978  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
8979  * port.  The port generates this event when an abort exchange request to an
8980  * rport fails twice in succession with no reply.  The abort could be originated
8981  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
8982  */
8983 void
8984 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
8985 			   struct lpfc_nodelist *ndlp,
8986 			   struct sli4_wcqe_xri_aborted *axri)
8987 {
8988 	struct lpfc_vport *vport;
8989 	uint32_t ext_status = 0;
8990 
8991 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
8992 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
8993 				"3115 Node Context not found, driver "
8994 				"ignoring abts err event\n");
8995 		return;
8996 	}
8997 
8998 	vport = ndlp->vport;
8999 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9000 			"3116 Port generated FCP XRI ABORT event on "
9001 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
9002 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
9003 			bf_get(lpfc_wcqe_xa_xri, axri),
9004 			bf_get(lpfc_wcqe_xa_status, axri),
9005 			axri->parameter);
9006 
9007 	/*
9008 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
9009 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
9010 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
9011 	 */
9012 	ext_status = axri->parameter & IOERR_PARAM_MASK;
9013 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
9014 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
9015 		lpfc_sli_abts_recover_port(vport, ndlp);
9016 }
9017 
9018 /**
9019  * lpfc_sli_async_event_handler - ASYNC iocb handler function
9020  * @phba: Pointer to HBA context object.
9021  * @pring: Pointer to driver SLI ring object.
9022  * @iocbq: Pointer to iocb object.
9023  *
9024  * This function is called by the slow ring event handler
9025  * function when there is an ASYNC event iocb in the ring.
9026  * This function is called with no lock held.
9027  * Currently this function handles only temperature related
9028  * ASYNC events. The function decodes the temperature sensor
9029  * event message and posts events for the management applications.
9030  **/
9031 static void
9032 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
9033 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
9034 {
9035 	IOCB_t *icmd;
9036 	uint16_t evt_code;
9037 	struct temp_event temp_event_data;
9038 	struct Scsi_Host *shost;
9039 	uint32_t *iocb_w;
9040 
9041 	icmd = &iocbq->iocb;
9042 	evt_code = icmd->un.asyncstat.evt_code;
9043 
9044 	switch (evt_code) {
9045 	case ASYNC_TEMP_WARN:
9046 	case ASYNC_TEMP_SAFE:
9047 		temp_event_data.data = (uint32_t) icmd->ulpContext;
9048 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
9049 		if (evt_code == ASYNC_TEMP_WARN) {
9050 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
9051 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
9052 				"0347 Adapter is very hot, please take "
9053 				"corrective action. temperature : %d Celsius\n",
9054 				(uint32_t) icmd->ulpContext);
9055 		} else {
9056 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
9057 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
9058 				"0340 Adapter temperature is OK now. "
9059 				"temperature : %d Celsius\n",
9060 				(uint32_t) icmd->ulpContext);
9061 		}
9062 
9063 		/* Send temperature change event to applications */
9064 		shost = lpfc_shost_from_vport(phba->pport);
9065 		fc_host_post_vendor_event(shost, fc_get_event_number(),
9066 			sizeof(temp_event_data), (char *) &temp_event_data,
9067 			LPFC_NL_VENDOR_ID);
9068 		break;
9069 	case ASYNC_STATUS_CN:
9070 		lpfc_sli_abts_err_handler(phba, iocbq);
9071 		break;
9072 	default:
9073 		iocb_w = (uint32_t *) icmd;
9074 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9075 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
9076 			" evt_code 0x%x\n"
9077 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
9078 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
9079 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
9080 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
9081 			pring->ringno, icmd->un.asyncstat.evt_code,
9082 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
9083 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
9084 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
9085 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
9086 
9087 		break;
9088 	}
9089 }
9090 
9091 
9092 /**
9093  * lpfc_sli_setup - SLI ring setup function
9094  * @phba: Pointer to HBA context object.
9095  *
9096  * lpfc_sli_setup sets up rings of the SLI interface with
9097  * number of iocbs per ring and iotags. This function is
9098  * called while driver attach to the HBA and before the
9099  * interrupts are enabled. So there is no need for locking.
9100  *
9101  * This function always returns 0.
9102  **/
9103 int
9104 lpfc_sli_setup(struct lpfc_hba *phba)
9105 {
9106 	int i, totiocbsize = 0;
9107 	struct lpfc_sli *psli = &phba->sli;
9108 	struct lpfc_sli_ring *pring;
9109 
9110 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
9111 	if (phba->sli_rev == LPFC_SLI_REV4)
9112 		psli->num_rings += phba->cfg_fcp_io_channel;
9113 	psli->sli_flag = 0;
9114 	psli->fcp_ring = LPFC_FCP_RING;
9115 	psli->next_ring = LPFC_FCP_NEXT_RING;
9116 	psli->extra_ring = LPFC_EXTRA_RING;
9117 
9118 	psli->iocbq_lookup = NULL;
9119 	psli->iocbq_lookup_len = 0;
9120 	psli->last_iotag = 0;
9121 
9122 	for (i = 0; i < psli->num_rings; i++) {
9123 		pring = &psli->ring[i];
9124 		switch (i) {
9125 		case LPFC_FCP_RING:	/* ring 0 - FCP */
9126 			/* numCiocb and numRiocb are used in config_port */
9127 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
9128 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
9129 			pring->sli.sli3.numCiocb +=
9130 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
9131 			pring->sli.sli3.numRiocb +=
9132 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
9133 			pring->sli.sli3.numCiocb +=
9134 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
9135 			pring->sli.sli3.numRiocb +=
9136 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
9137 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9138 							SLI3_IOCB_CMD_SIZE :
9139 							SLI2_IOCB_CMD_SIZE;
9140 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9141 							SLI3_IOCB_RSP_SIZE :
9142 							SLI2_IOCB_RSP_SIZE;
9143 			pring->iotag_ctr = 0;
9144 			pring->iotag_max =
9145 			    (phba->cfg_hba_queue_depth * 2);
9146 			pring->fast_iotag = pring->iotag_max;
9147 			pring->num_mask = 0;
9148 			break;
9149 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
9150 			/* numCiocb and numRiocb are used in config_port */
9151 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
9152 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
9153 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9154 							SLI3_IOCB_CMD_SIZE :
9155 							SLI2_IOCB_CMD_SIZE;
9156 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9157 							SLI3_IOCB_RSP_SIZE :
9158 							SLI2_IOCB_RSP_SIZE;
9159 			pring->iotag_max = phba->cfg_hba_queue_depth;
9160 			pring->num_mask = 0;
9161 			break;
9162 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
9163 			/* numCiocb and numRiocb are used in config_port */
9164 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
9165 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
9166 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9167 							SLI3_IOCB_CMD_SIZE :
9168 							SLI2_IOCB_CMD_SIZE;
9169 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9170 							SLI3_IOCB_RSP_SIZE :
9171 							SLI2_IOCB_RSP_SIZE;
9172 			pring->fast_iotag = 0;
9173 			pring->iotag_ctr = 0;
9174 			pring->iotag_max = 4096;
9175 			pring->lpfc_sli_rcv_async_status =
9176 				lpfc_sli_async_event_handler;
9177 			pring->num_mask = LPFC_MAX_RING_MASK;
9178 			pring->prt[0].profile = 0;	/* Mask 0 */
9179 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
9180 			pring->prt[0].type = FC_TYPE_ELS;
9181 			pring->prt[0].lpfc_sli_rcv_unsol_event =
9182 			    lpfc_els_unsol_event;
9183 			pring->prt[1].profile = 0;	/* Mask 1 */
9184 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
9185 			pring->prt[1].type = FC_TYPE_ELS;
9186 			pring->prt[1].lpfc_sli_rcv_unsol_event =
9187 			    lpfc_els_unsol_event;
9188 			pring->prt[2].profile = 0;	/* Mask 2 */
9189 			/* NameServer Inquiry */
9190 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
9191 			/* NameServer */
9192 			pring->prt[2].type = FC_TYPE_CT;
9193 			pring->prt[2].lpfc_sli_rcv_unsol_event =
9194 			    lpfc_ct_unsol_event;
9195 			pring->prt[3].profile = 0;	/* Mask 3 */
9196 			/* NameServer response */
9197 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
9198 			/* NameServer */
9199 			pring->prt[3].type = FC_TYPE_CT;
9200 			pring->prt[3].lpfc_sli_rcv_unsol_event =
9201 			    lpfc_ct_unsol_event;
9202 			break;
9203 		}
9204 		totiocbsize += (pring->sli.sli3.numCiocb *
9205 			pring->sli.sli3.sizeCiocb) +
9206 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
9207 	}
9208 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
9209 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
9210 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
9211 		       "SLI2 SLIM Data: x%x x%lx\n",
9212 		       phba->brd_no, totiocbsize,
9213 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
9214 	}
9215 	if (phba->cfg_multi_ring_support == 2)
9216 		lpfc_extra_ring_setup(phba);
9217 
9218 	return 0;
9219 }
9220 
9221 /**
9222  * lpfc_sli_queue_setup - Queue initialization function
9223  * @phba: Pointer to HBA context object.
9224  *
9225  * lpfc_sli_queue_setup sets up mailbox queues and iocb queues for each
9226  * ring. This function also initializes ring indices of each ring.
9227  * This function is called during the initialization of the SLI
9228  * interface of an HBA.
9229  * This function is called with no lock held and always returns
9230  * 1.
9231  **/
9232 int
9233 lpfc_sli_queue_setup(struct lpfc_hba *phba)
9234 {
9235 	struct lpfc_sli *psli;
9236 	struct lpfc_sli_ring *pring;
9237 	int i;
9238 
9239 	psli = &phba->sli;
9240 	spin_lock_irq(&phba->hbalock);
9241 	INIT_LIST_HEAD(&psli->mboxq);
9242 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
9243 	/* Initialize list headers for txq and txcmplq as double linked lists */
9244 	for (i = 0; i < psli->num_rings; i++) {
9245 		pring = &psli->ring[i];
9246 		pring->ringno = i;
9247 		pring->sli.sli3.next_cmdidx  = 0;
9248 		pring->sli.sli3.local_getidx = 0;
9249 		pring->sli.sli3.cmdidx = 0;
9250 		pring->flag = 0;
9251 		INIT_LIST_HEAD(&pring->txq);
9252 		INIT_LIST_HEAD(&pring->txcmplq);
9253 		INIT_LIST_HEAD(&pring->iocb_continueq);
9254 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
9255 		INIT_LIST_HEAD(&pring->postbufq);
9256 		spin_lock_init(&pring->ring_lock);
9257 	}
9258 	spin_unlock_irq(&phba->hbalock);
9259 	return 1;
9260 }
9261 
9262 /**
9263  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
9264  * @phba: Pointer to HBA context object.
9265  *
9266  * This routine flushes the mailbox command subsystem. It will unconditionally
9267  * flush all the mailbox commands in the three possible stages in the mailbox
9268  * command sub-system: pending mailbox command queue; the outstanding mailbox
9269  * command; and completed mailbox command queue. It is caller's responsibility
9270  * to make sure that the driver is in the proper state to flush the mailbox
9271  * command sub-system. Namely, the posting of mailbox commands into the
9272  * pending mailbox command queue from the various clients must be stopped;
9273  * either the HBA is in a state that it will never works on the outstanding
9274  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
9275  * mailbox command has been completed.
9276  **/
9277 static void
9278 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
9279 {
9280 	LIST_HEAD(completions);
9281 	struct lpfc_sli *psli = &phba->sli;
9282 	LPFC_MBOXQ_t *pmb;
9283 	unsigned long iflag;
9284 
9285 	/* Flush all the mailbox commands in the mbox system */
9286 	spin_lock_irqsave(&phba->hbalock, iflag);
9287 	/* The pending mailbox command queue */
9288 	list_splice_init(&phba->sli.mboxq, &completions);
9289 	/* The outstanding active mailbox command */
9290 	if (psli->mbox_active) {
9291 		list_add_tail(&psli->mbox_active->list, &completions);
9292 		psli->mbox_active = NULL;
9293 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9294 	}
9295 	/* The completed mailbox command queue */
9296 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
9297 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9298 
9299 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
9300 	while (!list_empty(&completions)) {
9301 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
9302 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
9303 		if (pmb->mbox_cmpl)
9304 			pmb->mbox_cmpl(phba, pmb);
9305 	}
9306 }
9307 
9308 /**
9309  * lpfc_sli_host_down - Vport cleanup function
9310  * @vport: Pointer to virtual port object.
9311  *
9312  * lpfc_sli_host_down is called to clean up the resources
9313  * associated with a vport before destroying virtual
9314  * port data structures.
9315  * This function does following operations:
9316  * - Free discovery resources associated with this virtual
9317  *   port.
9318  * - Free iocbs associated with this virtual port in
9319  *   the txq.
9320  * - Send abort for all iocb commands associated with this
9321  *   vport in txcmplq.
9322  *
9323  * This function is called with no lock held and always returns 1.
9324  **/
9325 int
9326 lpfc_sli_host_down(struct lpfc_vport *vport)
9327 {
9328 	LIST_HEAD(completions);
9329 	struct lpfc_hba *phba = vport->phba;
9330 	struct lpfc_sli *psli = &phba->sli;
9331 	struct lpfc_sli_ring *pring;
9332 	struct lpfc_iocbq *iocb, *next_iocb;
9333 	int i;
9334 	unsigned long flags = 0;
9335 	uint16_t prev_pring_flag;
9336 
9337 	lpfc_cleanup_discovery_resources(vport);
9338 
9339 	spin_lock_irqsave(&phba->hbalock, flags);
9340 	for (i = 0; i < psli->num_rings; i++) {
9341 		pring = &psli->ring[i];
9342 		prev_pring_flag = pring->flag;
9343 		/* Only slow rings */
9344 		if (pring->ringno == LPFC_ELS_RING) {
9345 			pring->flag |= LPFC_DEFERRED_RING_EVENT;
9346 			/* Set the lpfc data pending flag */
9347 			set_bit(LPFC_DATA_READY, &phba->data_flags);
9348 		}
9349 		/*
9350 		 * Error everything on the txq since these iocbs have not been
9351 		 * given to the FW yet.
9352 		 */
9353 		list_for_each_entry_safe(iocb, next_iocb, &pring->txq, list) {
9354 			if (iocb->vport != vport)
9355 				continue;
9356 			list_move_tail(&iocb->list, &completions);
9357 		}
9358 
9359 		/* Next issue ABTS for everything on the txcmplq */
9360 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq,
9361 									list) {
9362 			if (iocb->vport != vport)
9363 				continue;
9364 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
9365 		}
9366 
9367 		pring->flag = prev_pring_flag;
9368 	}
9369 
9370 	spin_unlock_irqrestore(&phba->hbalock, flags);
9371 
9372 	/* Cancel all the IOCBs from the completions list */
9373 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
9374 			      IOERR_SLI_DOWN);
9375 	return 1;
9376 }
9377 
9378 /**
9379  * lpfc_sli_hba_down - Resource cleanup function for the HBA
9380  * @phba: Pointer to HBA context object.
9381  *
9382  * This function cleans up all iocb, buffers, mailbox commands
9383  * while shutting down the HBA. This function is called with no
9384  * lock held and always returns 1.
9385  * This function does the following to cleanup driver resources:
9386  * - Free discovery resources for each virtual port
9387  * - Cleanup any pending fabric iocbs
9388  * - Iterate through the iocb txq and free each entry
9389  *   in the list.
9390  * - Free up any buffer posted to the HBA
9391  * - Free mailbox commands in the mailbox queue.
9392  **/
9393 int
9394 lpfc_sli_hba_down(struct lpfc_hba *phba)
9395 {
9396 	LIST_HEAD(completions);
9397 	struct lpfc_sli *psli = &phba->sli;
9398 	struct lpfc_sli_ring *pring;
9399 	struct lpfc_dmabuf *buf_ptr;
9400 	unsigned long flags = 0;
9401 	int i;
9402 
9403 	/* Shutdown the mailbox command sub-system */
9404 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
9405 
9406 	lpfc_hba_down_prep(phba);
9407 
9408 	lpfc_fabric_abort_hba(phba);
9409 
9410 	spin_lock_irqsave(&phba->hbalock, flags);
9411 	for (i = 0; i < psli->num_rings; i++) {
9412 		pring = &psli->ring[i];
9413 		/* Only slow rings */
9414 		if (pring->ringno == LPFC_ELS_RING) {
9415 			pring->flag |= LPFC_DEFERRED_RING_EVENT;
9416 			/* Set the lpfc data pending flag */
9417 			set_bit(LPFC_DATA_READY, &phba->data_flags);
9418 		}
9419 
9420 		/*
9421 		 * Error everything on the txq since these iocbs have not been
9422 		 * given to the FW yet.
9423 		 */
9424 		list_splice_init(&pring->txq, &completions);
9425 	}
9426 	spin_unlock_irqrestore(&phba->hbalock, flags);
9427 
9428 	/* Cancel all the IOCBs from the completions list */
9429 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
9430 			      IOERR_SLI_DOWN);
9431 
9432 	spin_lock_irqsave(&phba->hbalock, flags);
9433 	list_splice_init(&phba->elsbuf, &completions);
9434 	phba->elsbuf_cnt = 0;
9435 	phba->elsbuf_prev_cnt = 0;
9436 	spin_unlock_irqrestore(&phba->hbalock, flags);
9437 
9438 	while (!list_empty(&completions)) {
9439 		list_remove_head(&completions, buf_ptr,
9440 			struct lpfc_dmabuf, list);
9441 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
9442 		kfree(buf_ptr);
9443 	}
9444 
9445 	/* Return any active mbox cmds */
9446 	del_timer_sync(&psli->mbox_tmo);
9447 
9448 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
9449 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9450 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
9451 
9452 	return 1;
9453 }
9454 
9455 /**
9456  * lpfc_sli_pcimem_bcopy - SLI memory copy function
9457  * @srcp: Source memory pointer.
9458  * @destp: Destination memory pointer.
9459  * @cnt: Number of words required to be copied.
9460  *
9461  * This function is used for copying data between driver memory
9462  * and the SLI memory. This function also changes the endianness
9463  * of each word if native endianness is different from SLI
9464  * endianness. This function can be called with or without
9465  * lock.
9466  **/
9467 void
9468 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
9469 {
9470 	uint32_t *src = srcp;
9471 	uint32_t *dest = destp;
9472 	uint32_t ldata;
9473 	int i;
9474 
9475 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
9476 		ldata = *src;
9477 		ldata = le32_to_cpu(ldata);
9478 		*dest = ldata;
9479 		src++;
9480 		dest++;
9481 	}
9482 }
9483 
9484 
9485 /**
9486  * lpfc_sli_bemem_bcopy - SLI memory copy function
9487  * @srcp: Source memory pointer.
9488  * @destp: Destination memory pointer.
9489  * @cnt: Number of words required to be copied.
9490  *
9491  * This function is used for copying data between a data structure
9492  * with big endian representation to local endianness.
9493  * This function can be called with or without lock.
9494  **/
9495 void
9496 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
9497 {
9498 	uint32_t *src = srcp;
9499 	uint32_t *dest = destp;
9500 	uint32_t ldata;
9501 	int i;
9502 
9503 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
9504 		ldata = *src;
9505 		ldata = be32_to_cpu(ldata);
9506 		*dest = ldata;
9507 		src++;
9508 		dest++;
9509 	}
9510 }
9511 
9512 /**
9513  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
9514  * @phba: Pointer to HBA context object.
9515  * @pring: Pointer to driver SLI ring object.
9516  * @mp: Pointer to driver buffer object.
9517  *
9518  * This function is called with no lock held.
9519  * It always return zero after adding the buffer to the postbufq
9520  * buffer list.
9521  **/
9522 int
9523 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9524 			 struct lpfc_dmabuf *mp)
9525 {
9526 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
9527 	   later */
9528 	spin_lock_irq(&phba->hbalock);
9529 	list_add_tail(&mp->list, &pring->postbufq);
9530 	pring->postbufq_cnt++;
9531 	spin_unlock_irq(&phba->hbalock);
9532 	return 0;
9533 }
9534 
9535 /**
9536  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
9537  * @phba: Pointer to HBA context object.
9538  *
9539  * When HBQ is enabled, buffers are searched based on tags. This function
9540  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
9541  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
9542  * does not conflict with tags of buffer posted for unsolicited events.
9543  * The function returns the allocated tag. The function is called with
9544  * no locks held.
9545  **/
9546 uint32_t
9547 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
9548 {
9549 	spin_lock_irq(&phba->hbalock);
9550 	phba->buffer_tag_count++;
9551 	/*
9552 	 * Always set the QUE_BUFTAG_BIT to distiguish between
9553 	 * a tag assigned by HBQ.
9554 	 */
9555 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
9556 	spin_unlock_irq(&phba->hbalock);
9557 	return phba->buffer_tag_count;
9558 }
9559 
9560 /**
9561  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
9562  * @phba: Pointer to HBA context object.
9563  * @pring: Pointer to driver SLI ring object.
9564  * @tag: Buffer tag.
9565  *
9566  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
9567  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
9568  * iocb is posted to the response ring with the tag of the buffer.
9569  * This function searches the pring->postbufq list using the tag
9570  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
9571  * iocb. If the buffer is found then lpfc_dmabuf object of the
9572  * buffer is returned to the caller else NULL is returned.
9573  * This function is called with no lock held.
9574  **/
9575 struct lpfc_dmabuf *
9576 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9577 			uint32_t tag)
9578 {
9579 	struct lpfc_dmabuf *mp, *next_mp;
9580 	struct list_head *slp = &pring->postbufq;
9581 
9582 	/* Search postbufq, from the beginning, looking for a match on tag */
9583 	spin_lock_irq(&phba->hbalock);
9584 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
9585 		if (mp->buffer_tag == tag) {
9586 			list_del_init(&mp->list);
9587 			pring->postbufq_cnt--;
9588 			spin_unlock_irq(&phba->hbalock);
9589 			return mp;
9590 		}
9591 	}
9592 
9593 	spin_unlock_irq(&phba->hbalock);
9594 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9595 			"0402 Cannot find virtual addr for buffer tag on "
9596 			"ring %d Data x%lx x%p x%p x%x\n",
9597 			pring->ringno, (unsigned long) tag,
9598 			slp->next, slp->prev, pring->postbufq_cnt);
9599 
9600 	return NULL;
9601 }
9602 
9603 /**
9604  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
9605  * @phba: Pointer to HBA context object.
9606  * @pring: Pointer to driver SLI ring object.
9607  * @phys: DMA address of the buffer.
9608  *
9609  * This function searches the buffer list using the dma_address
9610  * of unsolicited event to find the driver's lpfc_dmabuf object
9611  * corresponding to the dma_address. The function returns the
9612  * lpfc_dmabuf object if a buffer is found else it returns NULL.
9613  * This function is called by the ct and els unsolicited event
9614  * handlers to get the buffer associated with the unsolicited
9615  * event.
9616  *
9617  * This function is called with no lock held.
9618  **/
9619 struct lpfc_dmabuf *
9620 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9621 			 dma_addr_t phys)
9622 {
9623 	struct lpfc_dmabuf *mp, *next_mp;
9624 	struct list_head *slp = &pring->postbufq;
9625 
9626 	/* Search postbufq, from the beginning, looking for a match on phys */
9627 	spin_lock_irq(&phba->hbalock);
9628 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
9629 		if (mp->phys == phys) {
9630 			list_del_init(&mp->list);
9631 			pring->postbufq_cnt--;
9632 			spin_unlock_irq(&phba->hbalock);
9633 			return mp;
9634 		}
9635 	}
9636 
9637 	spin_unlock_irq(&phba->hbalock);
9638 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9639 			"0410 Cannot find virtual addr for mapped buf on "
9640 			"ring %d Data x%llx x%p x%p x%x\n",
9641 			pring->ringno, (unsigned long long)phys,
9642 			slp->next, slp->prev, pring->postbufq_cnt);
9643 	return NULL;
9644 }
9645 
9646 /**
9647  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
9648  * @phba: Pointer to HBA context object.
9649  * @cmdiocb: Pointer to driver command iocb object.
9650  * @rspiocb: Pointer to driver response iocb object.
9651  *
9652  * This function is the completion handler for the abort iocbs for
9653  * ELS commands. This function is called from the ELS ring event
9654  * handler with no lock held. This function frees memory resources
9655  * associated with the abort iocb.
9656  **/
9657 static void
9658 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
9659 			struct lpfc_iocbq *rspiocb)
9660 {
9661 	IOCB_t *irsp = &rspiocb->iocb;
9662 	uint16_t abort_iotag, abort_context;
9663 	struct lpfc_iocbq *abort_iocb = NULL;
9664 
9665 	if (irsp->ulpStatus) {
9666 
9667 		/*
9668 		 * Assume that the port already completed and returned, or
9669 		 * will return the iocb. Just Log the message.
9670 		 */
9671 		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
9672 		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
9673 
9674 		spin_lock_irq(&phba->hbalock);
9675 		if (phba->sli_rev < LPFC_SLI_REV4) {
9676 			if (abort_iotag != 0 &&
9677 				abort_iotag <= phba->sli.last_iotag)
9678 				abort_iocb =
9679 					phba->sli.iocbq_lookup[abort_iotag];
9680 		} else
9681 			/* For sli4 the abort_tag is the XRI,
9682 			 * so the abort routine puts the iotag  of the iocb
9683 			 * being aborted in the context field of the abort
9684 			 * IOCB.
9685 			 */
9686 			abort_iocb = phba->sli.iocbq_lookup[abort_context];
9687 
9688 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
9689 				"0327 Cannot abort els iocb %p "
9690 				"with tag %x context %x, abort status %x, "
9691 				"abort code %x\n",
9692 				abort_iocb, abort_iotag, abort_context,
9693 				irsp->ulpStatus, irsp->un.ulpWord[4]);
9694 
9695 		spin_unlock_irq(&phba->hbalock);
9696 	}
9697 	lpfc_sli_release_iocbq(phba, cmdiocb);
9698 	return;
9699 }
9700 
9701 /**
9702  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
9703  * @phba: Pointer to HBA context object.
9704  * @cmdiocb: Pointer to driver command iocb object.
9705  * @rspiocb: Pointer to driver response iocb object.
9706  *
9707  * The function is called from SLI ring event handler with no
9708  * lock held. This function is the completion handler for ELS commands
9709  * which are aborted. The function frees memory resources used for
9710  * the aborted ELS commands.
9711  **/
9712 static void
9713 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
9714 		     struct lpfc_iocbq *rspiocb)
9715 {
9716 	IOCB_t *irsp = &rspiocb->iocb;
9717 
9718 	/* ELS cmd tag <ulpIoTag> completes */
9719 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
9720 			"0139 Ignoring ELS cmd tag x%x completion Data: "
9721 			"x%x x%x x%x\n",
9722 			irsp->ulpIoTag, irsp->ulpStatus,
9723 			irsp->un.ulpWord[4], irsp->ulpTimeout);
9724 	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
9725 		lpfc_ct_free_iocb(phba, cmdiocb);
9726 	else
9727 		lpfc_els_free_iocb(phba, cmdiocb);
9728 	return;
9729 }
9730 
9731 /**
9732  * lpfc_sli_abort_iotag_issue - Issue abort for a command iocb
9733  * @phba: Pointer to HBA context object.
9734  * @pring: Pointer to driver SLI ring object.
9735  * @cmdiocb: Pointer to driver command iocb object.
9736  *
9737  * This function issues an abort iocb for the provided command iocb down to
9738  * the port. Other than the case the outstanding command iocb is an abort
9739  * request, this function issues abort out unconditionally. This function is
9740  * called with hbalock held. The function returns 0 when it fails due to
9741  * memory allocation failure or when the command iocb is an abort request.
9742  **/
9743 static int
9744 lpfc_sli_abort_iotag_issue(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9745 			   struct lpfc_iocbq *cmdiocb)
9746 {
9747 	struct lpfc_vport *vport = cmdiocb->vport;
9748 	struct lpfc_iocbq *abtsiocbp;
9749 	IOCB_t *icmd = NULL;
9750 	IOCB_t *iabt = NULL;
9751 	int ring_number;
9752 	int retval;
9753 	unsigned long iflags;
9754 
9755 	/*
9756 	 * There are certain command types we don't want to abort.  And we
9757 	 * don't want to abort commands that are already in the process of
9758 	 * being aborted.
9759 	 */
9760 	icmd = &cmdiocb->iocb;
9761 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
9762 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
9763 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
9764 		return 0;
9765 
9766 	/* issue ABTS for this IOCB based on iotag */
9767 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
9768 	if (abtsiocbp == NULL)
9769 		return 0;
9770 
9771 	/* This signals the response to set the correct status
9772 	 * before calling the completion handler
9773 	 */
9774 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
9775 
9776 	iabt = &abtsiocbp->iocb;
9777 	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
9778 	iabt->un.acxri.abortContextTag = icmd->ulpContext;
9779 	if (phba->sli_rev == LPFC_SLI_REV4) {
9780 		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
9781 		iabt->un.acxri.abortContextTag = cmdiocb->iotag;
9782 	}
9783 	else
9784 		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
9785 	iabt->ulpLe = 1;
9786 	iabt->ulpClass = icmd->ulpClass;
9787 
9788 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
9789 	abtsiocbp->fcp_wqidx = cmdiocb->fcp_wqidx;
9790 	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
9791 		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
9792 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
9793 		abtsiocbp->iocb_flag |= LPFC_IO_FOF;
9794 
9795 	if (phba->link_state >= LPFC_LINK_UP)
9796 		iabt->ulpCommand = CMD_ABORT_XRI_CN;
9797 	else
9798 		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
9799 
9800 	abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
9801 
9802 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
9803 			 "0339 Abort xri x%x, original iotag x%x, "
9804 			 "abort cmd iotag x%x\n",
9805 			 iabt->un.acxri.abortIoTag,
9806 			 iabt->un.acxri.abortContextTag,
9807 			 abtsiocbp->iotag);
9808 
9809 	if (phba->sli_rev == LPFC_SLI_REV4) {
9810 		ring_number =
9811 			lpfc_sli_calc_ring(phba, pring->ringno, abtsiocbp);
9812 		if (unlikely(ring_number == LPFC_HBA_ERROR))
9813 			return 0;
9814 		pring = &phba->sli.ring[ring_number];
9815 		/* Note: both hbalock and ring_lock need to be set here */
9816 		spin_lock_irqsave(&pring->ring_lock, iflags);
9817 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
9818 			abtsiocbp, 0);
9819 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
9820 	} else {
9821 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
9822 			abtsiocbp, 0);
9823 	}
9824 
9825 	if (retval)
9826 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
9827 
9828 	/*
9829 	 * Caller to this routine should check for IOCB_ERROR
9830 	 * and handle it properly.  This routine no longer removes
9831 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
9832 	 */
9833 	return retval;
9834 }
9835 
9836 /**
9837  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
9838  * @phba: Pointer to HBA context object.
9839  * @pring: Pointer to driver SLI ring object.
9840  * @cmdiocb: Pointer to driver command iocb object.
9841  *
9842  * This function issues an abort iocb for the provided command iocb. In case
9843  * of unloading, the abort iocb will not be issued to commands on the ELS
9844  * ring. Instead, the callback function shall be changed to those commands
9845  * so that nothing happens when them finishes. This function is called with
9846  * hbalock held. The function returns 0 when the command iocb is an abort
9847  * request.
9848  **/
9849 int
9850 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9851 			   struct lpfc_iocbq *cmdiocb)
9852 {
9853 	struct lpfc_vport *vport = cmdiocb->vport;
9854 	int retval = IOCB_ERROR;
9855 	IOCB_t *icmd = NULL;
9856 
9857 	/*
9858 	 * There are certain command types we don't want to abort.  And we
9859 	 * don't want to abort commands that are already in the process of
9860 	 * being aborted.
9861 	 */
9862 	icmd = &cmdiocb->iocb;
9863 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
9864 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
9865 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
9866 		return 0;
9867 
9868 	/*
9869 	 * If we're unloading, don't abort iocb on the ELS ring, but change
9870 	 * the callback so that nothing happens when it finishes.
9871 	 */
9872 	if ((vport->load_flag & FC_UNLOADING) &&
9873 	    (pring->ringno == LPFC_ELS_RING)) {
9874 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
9875 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
9876 		else
9877 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
9878 		goto abort_iotag_exit;
9879 	}
9880 
9881 	/* Now, we try to issue the abort to the cmdiocb out */
9882 	retval = lpfc_sli_abort_iotag_issue(phba, pring, cmdiocb);
9883 
9884 abort_iotag_exit:
9885 	/*
9886 	 * Caller to this routine should check for IOCB_ERROR
9887 	 * and handle it properly.  This routine no longer removes
9888 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
9889 	 */
9890 	return retval;
9891 }
9892 
9893 /**
9894  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
9895  * @phba: pointer to lpfc HBA data structure.
9896  *
9897  * This routine will abort all pending and outstanding iocbs to an HBA.
9898  **/
9899 void
9900 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
9901 {
9902 	struct lpfc_sli *psli = &phba->sli;
9903 	struct lpfc_sli_ring *pring;
9904 	int i;
9905 
9906 	for (i = 0; i < psli->num_rings; i++) {
9907 		pring = &psli->ring[i];
9908 		lpfc_sli_abort_iocb_ring(phba, pring);
9909 	}
9910 }
9911 
9912 /**
9913  * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
9914  * @iocbq: Pointer to driver iocb object.
9915  * @vport: Pointer to driver virtual port object.
9916  * @tgt_id: SCSI ID of the target.
9917  * @lun_id: LUN ID of the scsi device.
9918  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
9919  *
9920  * This function acts as an iocb filter for functions which abort or count
9921  * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
9922  * 0 if the filtering criteria is met for the given iocb and will return
9923  * 1 if the filtering criteria is not met.
9924  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
9925  * given iocb is for the SCSI device specified by vport, tgt_id and
9926  * lun_id parameter.
9927  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
9928  * given iocb is for the SCSI target specified by vport and tgt_id
9929  * parameters.
9930  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
9931  * given iocb is for the SCSI host associated with the given vport.
9932  * This function is called with no locks held.
9933  **/
9934 static int
9935 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
9936 			   uint16_t tgt_id, uint64_t lun_id,
9937 			   lpfc_ctx_cmd ctx_cmd)
9938 {
9939 	struct lpfc_scsi_buf *lpfc_cmd;
9940 	int rc = 1;
9941 
9942 	if (!(iocbq->iocb_flag &  LPFC_IO_FCP))
9943 		return rc;
9944 
9945 	if (iocbq->vport != vport)
9946 		return rc;
9947 
9948 	lpfc_cmd = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
9949 
9950 	if (lpfc_cmd->pCmd == NULL)
9951 		return rc;
9952 
9953 	switch (ctx_cmd) {
9954 	case LPFC_CTX_LUN:
9955 		if ((lpfc_cmd->rdata->pnode) &&
9956 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
9957 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
9958 			rc = 0;
9959 		break;
9960 	case LPFC_CTX_TGT:
9961 		if ((lpfc_cmd->rdata->pnode) &&
9962 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
9963 			rc = 0;
9964 		break;
9965 	case LPFC_CTX_HOST:
9966 		rc = 0;
9967 		break;
9968 	default:
9969 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
9970 			__func__, ctx_cmd);
9971 		break;
9972 	}
9973 
9974 	return rc;
9975 }
9976 
9977 /**
9978  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
9979  * @vport: Pointer to virtual port.
9980  * @tgt_id: SCSI ID of the target.
9981  * @lun_id: LUN ID of the scsi device.
9982  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
9983  *
9984  * This function returns number of FCP commands pending for the vport.
9985  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
9986  * commands pending on the vport associated with SCSI device specified
9987  * by tgt_id and lun_id parameters.
9988  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
9989  * commands pending on the vport associated with SCSI target specified
9990  * by tgt_id parameter.
9991  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
9992  * commands pending on the vport.
9993  * This function returns the number of iocbs which satisfy the filter.
9994  * This function is called without any lock held.
9995  **/
9996 int
9997 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
9998 		  lpfc_ctx_cmd ctx_cmd)
9999 {
10000 	struct lpfc_hba *phba = vport->phba;
10001 	struct lpfc_iocbq *iocbq;
10002 	int sum, i;
10003 
10004 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
10005 		iocbq = phba->sli.iocbq_lookup[i];
10006 
10007 		if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
10008 						ctx_cmd) == 0)
10009 			sum++;
10010 	}
10011 
10012 	return sum;
10013 }
10014 
10015 /**
10016  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
10017  * @phba: Pointer to HBA context object
10018  * @cmdiocb: Pointer to command iocb object.
10019  * @rspiocb: Pointer to response iocb object.
10020  *
10021  * This function is called when an aborted FCP iocb completes. This
10022  * function is called by the ring event handler with no lock held.
10023  * This function frees the iocb.
10024  **/
10025 void
10026 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
10027 			struct lpfc_iocbq *rspiocb)
10028 {
10029 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10030 			"3096 ABORT_XRI_CN completing on rpi x%x "
10031 			"original iotag x%x, abort cmd iotag x%x "
10032 			"status 0x%x, reason 0x%x\n",
10033 			cmdiocb->iocb.un.acxri.abortContextTag,
10034 			cmdiocb->iocb.un.acxri.abortIoTag,
10035 			cmdiocb->iotag, rspiocb->iocb.ulpStatus,
10036 			rspiocb->iocb.un.ulpWord[4]);
10037 	lpfc_sli_release_iocbq(phba, cmdiocb);
10038 	return;
10039 }
10040 
10041 /**
10042  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
10043  * @vport: Pointer to virtual port.
10044  * @pring: Pointer to driver SLI ring object.
10045  * @tgt_id: SCSI ID of the target.
10046  * @lun_id: LUN ID of the scsi device.
10047  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10048  *
10049  * This function sends an abort command for every SCSI command
10050  * associated with the given virtual port pending on the ring
10051  * filtered by lpfc_sli_validate_fcp_iocb function.
10052  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
10053  * FCP iocbs associated with lun specified by tgt_id and lun_id
10054  * parameters
10055  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
10056  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
10057  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
10058  * FCP iocbs associated with virtual port.
10059  * This function returns number of iocbs it failed to abort.
10060  * This function is called with no locks held.
10061  **/
10062 int
10063 lpfc_sli_abort_iocb(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
10064 		    uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd abort_cmd)
10065 {
10066 	struct lpfc_hba *phba = vport->phba;
10067 	struct lpfc_iocbq *iocbq;
10068 	struct lpfc_iocbq *abtsiocb;
10069 	IOCB_t *cmd = NULL;
10070 	int errcnt = 0, ret_val = 0;
10071 	int i;
10072 
10073 	for (i = 1; i <= phba->sli.last_iotag; i++) {
10074 		iocbq = phba->sli.iocbq_lookup[i];
10075 
10076 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
10077 					       abort_cmd) != 0)
10078 			continue;
10079 
10080 		/*
10081 		 * If the iocbq is already being aborted, don't take a second
10082 		 * action, but do count it.
10083 		 */
10084 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
10085 			continue;
10086 
10087 		/* issue ABTS for this IOCB based on iotag */
10088 		abtsiocb = lpfc_sli_get_iocbq(phba);
10089 		if (abtsiocb == NULL) {
10090 			errcnt++;
10091 			continue;
10092 		}
10093 
10094 		/* indicate the IO is being aborted by the driver. */
10095 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
10096 
10097 		cmd = &iocbq->iocb;
10098 		abtsiocb->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
10099 		abtsiocb->iocb.un.acxri.abortContextTag = cmd->ulpContext;
10100 		if (phba->sli_rev == LPFC_SLI_REV4)
10101 			abtsiocb->iocb.un.acxri.abortIoTag = iocbq->sli4_xritag;
10102 		else
10103 			abtsiocb->iocb.un.acxri.abortIoTag = cmd->ulpIoTag;
10104 		abtsiocb->iocb.ulpLe = 1;
10105 		abtsiocb->iocb.ulpClass = cmd->ulpClass;
10106 		abtsiocb->vport = vport;
10107 
10108 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
10109 		abtsiocb->fcp_wqidx = iocbq->fcp_wqidx;
10110 		if (iocbq->iocb_flag & LPFC_IO_FCP)
10111 			abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
10112 		if (iocbq->iocb_flag & LPFC_IO_FOF)
10113 			abtsiocb->iocb_flag |= LPFC_IO_FOF;
10114 
10115 		if (lpfc_is_link_up(phba))
10116 			abtsiocb->iocb.ulpCommand = CMD_ABORT_XRI_CN;
10117 		else
10118 			abtsiocb->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
10119 
10120 		/* Setup callback routine and issue the command. */
10121 		abtsiocb->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
10122 		ret_val = lpfc_sli_issue_iocb(phba, pring->ringno,
10123 					      abtsiocb, 0);
10124 		if (ret_val == IOCB_ERROR) {
10125 			lpfc_sli_release_iocbq(phba, abtsiocb);
10126 			errcnt++;
10127 			continue;
10128 		}
10129 	}
10130 
10131 	return errcnt;
10132 }
10133 
10134 /**
10135  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
10136  * @vport: Pointer to virtual port.
10137  * @pring: Pointer to driver SLI ring object.
10138  * @tgt_id: SCSI ID of the target.
10139  * @lun_id: LUN ID of the scsi device.
10140  * @taskmgmt_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10141  *
10142  * This function sends an abort command for every SCSI command
10143  * associated with the given virtual port pending on the ring
10144  * filtered by lpfc_sli_validate_fcp_iocb function.
10145  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
10146  * FCP iocbs associated with lun specified by tgt_id and lun_id
10147  * parameters
10148  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
10149  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
10150  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
10151  * FCP iocbs associated with virtual port.
10152  * This function returns number of iocbs it aborted .
10153  * This function is called with no locks held right after a taskmgmt
10154  * command is sent.
10155  **/
10156 int
10157 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
10158 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
10159 {
10160 	struct lpfc_hba *phba = vport->phba;
10161 	struct lpfc_scsi_buf *lpfc_cmd;
10162 	struct lpfc_iocbq *abtsiocbq;
10163 	struct lpfc_nodelist *ndlp;
10164 	struct lpfc_iocbq *iocbq;
10165 	IOCB_t *icmd;
10166 	int sum, i, ret_val;
10167 	unsigned long iflags;
10168 	struct lpfc_sli_ring *pring_s4;
10169 	uint32_t ring_number;
10170 
10171 	spin_lock_irq(&phba->hbalock);
10172 
10173 	/* all I/Os are in process of being flushed */
10174 	if (phba->hba_flag & HBA_FCP_IOQ_FLUSH) {
10175 		spin_unlock_irq(&phba->hbalock);
10176 		return 0;
10177 	}
10178 	sum = 0;
10179 
10180 	for (i = 1; i <= phba->sli.last_iotag; i++) {
10181 		iocbq = phba->sli.iocbq_lookup[i];
10182 
10183 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
10184 					       cmd) != 0)
10185 			continue;
10186 
10187 		/*
10188 		 * If the iocbq is already being aborted, don't take a second
10189 		 * action, but do count it.
10190 		 */
10191 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
10192 			continue;
10193 
10194 		/* issue ABTS for this IOCB based on iotag */
10195 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
10196 		if (abtsiocbq == NULL)
10197 			continue;
10198 
10199 		icmd = &iocbq->iocb;
10200 		abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
10201 		abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
10202 		if (phba->sli_rev == LPFC_SLI_REV4)
10203 			abtsiocbq->iocb.un.acxri.abortIoTag =
10204 							 iocbq->sli4_xritag;
10205 		else
10206 			abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
10207 		abtsiocbq->iocb.ulpLe = 1;
10208 		abtsiocbq->iocb.ulpClass = icmd->ulpClass;
10209 		abtsiocbq->vport = vport;
10210 
10211 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
10212 		abtsiocbq->fcp_wqidx = iocbq->fcp_wqidx;
10213 		if (iocbq->iocb_flag & LPFC_IO_FCP)
10214 			abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
10215 		if (iocbq->iocb_flag & LPFC_IO_FOF)
10216 			abtsiocbq->iocb_flag |= LPFC_IO_FOF;
10217 
10218 		lpfc_cmd = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
10219 		ndlp = lpfc_cmd->rdata->pnode;
10220 
10221 		if (lpfc_is_link_up(phba) &&
10222 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
10223 			abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
10224 		else
10225 			abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
10226 
10227 		/* Setup callback routine and issue the command. */
10228 		abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
10229 
10230 		/*
10231 		 * Indicate the IO is being aborted by the driver and set
10232 		 * the caller's flag into the aborted IO.
10233 		 */
10234 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
10235 
10236 		if (phba->sli_rev == LPFC_SLI_REV4) {
10237 			ring_number = MAX_SLI3_CONFIGURED_RINGS +
10238 					 iocbq->fcp_wqidx;
10239 			pring_s4 = &phba->sli.ring[ring_number];
10240 			/* Note: both hbalock and ring_lock must be set here */
10241 			spin_lock_irqsave(&pring_s4->ring_lock, iflags);
10242 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
10243 							abtsiocbq, 0);
10244 			spin_unlock_irqrestore(&pring_s4->ring_lock, iflags);
10245 		} else {
10246 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
10247 							abtsiocbq, 0);
10248 		}
10249 
10250 
10251 		if (ret_val == IOCB_ERROR)
10252 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
10253 		else
10254 			sum++;
10255 	}
10256 	spin_unlock_irq(&phba->hbalock);
10257 	return sum;
10258 }
10259 
10260 /**
10261  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
10262  * @phba: Pointer to HBA context object.
10263  * @cmdiocbq: Pointer to command iocb.
10264  * @rspiocbq: Pointer to response iocb.
10265  *
10266  * This function is the completion handler for iocbs issued using
10267  * lpfc_sli_issue_iocb_wait function. This function is called by the
10268  * ring event handler function without any lock held. This function
10269  * can be called from both worker thread context and interrupt
10270  * context. This function also can be called from other thread which
10271  * cleans up the SLI layer objects.
10272  * This function copy the contents of the response iocb to the
10273  * response iocb memory object provided by the caller of
10274  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
10275  * sleeps for the iocb completion.
10276  **/
10277 static void
10278 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
10279 			struct lpfc_iocbq *cmdiocbq,
10280 			struct lpfc_iocbq *rspiocbq)
10281 {
10282 	wait_queue_head_t *pdone_q;
10283 	unsigned long iflags;
10284 	struct lpfc_scsi_buf *lpfc_cmd;
10285 
10286 	spin_lock_irqsave(&phba->hbalock, iflags);
10287 	if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
10288 
10289 		/*
10290 		 * A time out has occurred for the iocb.  If a time out
10291 		 * completion handler has been supplied, call it.  Otherwise,
10292 		 * just free the iocbq.
10293 		 */
10294 
10295 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10296 		cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
10297 		cmdiocbq->wait_iocb_cmpl = NULL;
10298 		if (cmdiocbq->iocb_cmpl)
10299 			(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
10300 		else
10301 			lpfc_sli_release_iocbq(phba, cmdiocbq);
10302 		return;
10303 	}
10304 
10305 	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
10306 	if (cmdiocbq->context2 && rspiocbq)
10307 		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
10308 		       &rspiocbq->iocb, sizeof(IOCB_t));
10309 
10310 	/* Set the exchange busy flag for task management commands */
10311 	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
10312 		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
10313 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_scsi_buf,
10314 			cur_iocbq);
10315 		lpfc_cmd->exch_busy = rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY;
10316 	}
10317 
10318 	pdone_q = cmdiocbq->context_un.wait_queue;
10319 	if (pdone_q)
10320 		wake_up(pdone_q);
10321 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10322 	return;
10323 }
10324 
10325 /**
10326  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
10327  * @phba: Pointer to HBA context object..
10328  * @piocbq: Pointer to command iocb.
10329  * @flag: Flag to test.
10330  *
10331  * This routine grabs the hbalock and then test the iocb_flag to
10332  * see if the passed in flag is set.
10333  * Returns:
10334  * 1 if flag is set.
10335  * 0 if flag is not set.
10336  **/
10337 static int
10338 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
10339 		 struct lpfc_iocbq *piocbq, uint32_t flag)
10340 {
10341 	unsigned long iflags;
10342 	int ret;
10343 
10344 	spin_lock_irqsave(&phba->hbalock, iflags);
10345 	ret = piocbq->iocb_flag & flag;
10346 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10347 	return ret;
10348 
10349 }
10350 
10351 /**
10352  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
10353  * @phba: Pointer to HBA context object..
10354  * @pring: Pointer to sli ring.
10355  * @piocb: Pointer to command iocb.
10356  * @prspiocbq: Pointer to response iocb.
10357  * @timeout: Timeout in number of seconds.
10358  *
10359  * This function issues the iocb to firmware and waits for the
10360  * iocb to complete. The iocb_cmpl field of the shall be used
10361  * to handle iocbs which time out. If the field is NULL, the
10362  * function shall free the iocbq structure.  If more clean up is
10363  * needed, the caller is expected to provide a completion function
10364  * that will provide the needed clean up.  If the iocb command is
10365  * not completed within timeout seconds, the function will either
10366  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
10367  * completion function set in the iocb_cmpl field and then return
10368  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
10369  * resources if this function returns IOCB_TIMEDOUT.
10370  * The function waits for the iocb completion using an
10371  * non-interruptible wait.
10372  * This function will sleep while waiting for iocb completion.
10373  * So, this function should not be called from any context which
10374  * does not allow sleeping. Due to the same reason, this function
10375  * cannot be called with interrupt disabled.
10376  * This function assumes that the iocb completions occur while
10377  * this function sleep. So, this function cannot be called from
10378  * the thread which process iocb completion for this ring.
10379  * This function clears the iocb_flag of the iocb object before
10380  * issuing the iocb and the iocb completion handler sets this
10381  * flag and wakes this thread when the iocb completes.
10382  * The contents of the response iocb will be copied to prspiocbq
10383  * by the completion handler when the command completes.
10384  * This function returns IOCB_SUCCESS when success.
10385  * This function is called with no lock held.
10386  **/
10387 int
10388 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
10389 			 uint32_t ring_number,
10390 			 struct lpfc_iocbq *piocb,
10391 			 struct lpfc_iocbq *prspiocbq,
10392 			 uint32_t timeout)
10393 {
10394 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
10395 	long timeleft, timeout_req = 0;
10396 	int retval = IOCB_SUCCESS;
10397 	uint32_t creg_val;
10398 	struct lpfc_iocbq *iocb;
10399 	int txq_cnt = 0;
10400 	int txcmplq_cnt = 0;
10401 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
10402 	unsigned long iflags;
10403 	bool iocb_completed = true;
10404 
10405 	/*
10406 	 * If the caller has provided a response iocbq buffer, then context2
10407 	 * is NULL or its an error.
10408 	 */
10409 	if (prspiocbq) {
10410 		if (piocb->context2)
10411 			return IOCB_ERROR;
10412 		piocb->context2 = prspiocbq;
10413 	}
10414 
10415 	piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
10416 	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
10417 	piocb->context_un.wait_queue = &done_q;
10418 	piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
10419 
10420 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
10421 		if (lpfc_readl(phba->HCregaddr, &creg_val))
10422 			return IOCB_ERROR;
10423 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
10424 		writel(creg_val, phba->HCregaddr);
10425 		readl(phba->HCregaddr); /* flush */
10426 	}
10427 
10428 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
10429 				     SLI_IOCB_RET_IOCB);
10430 	if (retval == IOCB_SUCCESS) {
10431 		timeout_req = msecs_to_jiffies(timeout * 1000);
10432 		timeleft = wait_event_timeout(done_q,
10433 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
10434 				timeout_req);
10435 		spin_lock_irqsave(&phba->hbalock, iflags);
10436 		if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
10437 
10438 			/*
10439 			 * IOCB timed out.  Inform the wake iocb wait
10440 			 * completion function and set local status
10441 			 */
10442 
10443 			iocb_completed = false;
10444 			piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
10445 		}
10446 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10447 		if (iocb_completed) {
10448 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10449 					"0331 IOCB wake signaled\n");
10450 			/* Note: we are not indicating if the IOCB has a success
10451 			 * status or not - that's for the caller to check.
10452 			 * IOCB_SUCCESS means just that the command was sent and
10453 			 * completed. Not that it completed successfully.
10454 			 * */
10455 		} else if (timeleft == 0) {
10456 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10457 					"0338 IOCB wait timeout error - no "
10458 					"wake response Data x%x\n", timeout);
10459 			retval = IOCB_TIMEDOUT;
10460 		} else {
10461 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10462 					"0330 IOCB wake NOT set, "
10463 					"Data x%x x%lx\n",
10464 					timeout, (timeleft / jiffies));
10465 			retval = IOCB_TIMEDOUT;
10466 		}
10467 	} else if (retval == IOCB_BUSY) {
10468 		if (phba->cfg_log_verbose & LOG_SLI) {
10469 			list_for_each_entry(iocb, &pring->txq, list) {
10470 				txq_cnt++;
10471 			}
10472 			list_for_each_entry(iocb, &pring->txcmplq, list) {
10473 				txcmplq_cnt++;
10474 			}
10475 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10476 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
10477 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
10478 		}
10479 		return retval;
10480 	} else {
10481 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10482 				"0332 IOCB wait issue failed, Data x%x\n",
10483 				retval);
10484 		retval = IOCB_ERROR;
10485 	}
10486 
10487 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
10488 		if (lpfc_readl(phba->HCregaddr, &creg_val))
10489 			return IOCB_ERROR;
10490 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
10491 		writel(creg_val, phba->HCregaddr);
10492 		readl(phba->HCregaddr); /* flush */
10493 	}
10494 
10495 	if (prspiocbq)
10496 		piocb->context2 = NULL;
10497 
10498 	piocb->context_un.wait_queue = NULL;
10499 	piocb->iocb_cmpl = NULL;
10500 	return retval;
10501 }
10502 
10503 /**
10504  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
10505  * @phba: Pointer to HBA context object.
10506  * @pmboxq: Pointer to driver mailbox object.
10507  * @timeout: Timeout in number of seconds.
10508  *
10509  * This function issues the mailbox to firmware and waits for the
10510  * mailbox command to complete. If the mailbox command is not
10511  * completed within timeout seconds, it returns MBX_TIMEOUT.
10512  * The function waits for the mailbox completion using an
10513  * interruptible wait. If the thread is woken up due to a
10514  * signal, MBX_TIMEOUT error is returned to the caller. Caller
10515  * should not free the mailbox resources, if this function returns
10516  * MBX_TIMEOUT.
10517  * This function will sleep while waiting for mailbox completion.
10518  * So, this function should not be called from any context which
10519  * does not allow sleeping. Due to the same reason, this function
10520  * cannot be called with interrupt disabled.
10521  * This function assumes that the mailbox completion occurs while
10522  * this function sleep. So, this function cannot be called from
10523  * the worker thread which processes mailbox completion.
10524  * This function is called in the context of HBA management
10525  * applications.
10526  * This function returns MBX_SUCCESS when successful.
10527  * This function is called with no lock held.
10528  **/
10529 int
10530 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
10531 			 uint32_t timeout)
10532 {
10533 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
10534 	MAILBOX_t *mb = NULL;
10535 	int retval;
10536 	unsigned long flag;
10537 
10538 	/* The caller might set context1 for extended buffer */
10539 	if (pmboxq->context1)
10540 		mb = (MAILBOX_t *)pmboxq->context1;
10541 
10542 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
10543 	/* setup wake call as IOCB callback */
10544 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
10545 	/* setup context field to pass wait_queue pointer to wake function  */
10546 	pmboxq->context1 = &done_q;
10547 
10548 	/* now issue the command */
10549 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
10550 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
10551 		wait_event_interruptible_timeout(done_q,
10552 				pmboxq->mbox_flag & LPFC_MBX_WAKE,
10553 				msecs_to_jiffies(timeout * 1000));
10554 
10555 		spin_lock_irqsave(&phba->hbalock, flag);
10556 		/* restore the possible extended buffer for free resource */
10557 		pmboxq->context1 = (uint8_t *)mb;
10558 		/*
10559 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
10560 		 * else do not free the resources.
10561 		 */
10562 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
10563 			retval = MBX_SUCCESS;
10564 		} else {
10565 			retval = MBX_TIMEOUT;
10566 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
10567 		}
10568 		spin_unlock_irqrestore(&phba->hbalock, flag);
10569 	} else {
10570 		/* restore the possible extended buffer for free resource */
10571 		pmboxq->context1 = (uint8_t *)mb;
10572 	}
10573 
10574 	return retval;
10575 }
10576 
10577 /**
10578  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
10579  * @phba: Pointer to HBA context.
10580  *
10581  * This function is called to shutdown the driver's mailbox sub-system.
10582  * It first marks the mailbox sub-system is in a block state to prevent
10583  * the asynchronous mailbox command from issued off the pending mailbox
10584  * command queue. If the mailbox command sub-system shutdown is due to
10585  * HBA error conditions such as EEH or ERATT, this routine shall invoke
10586  * the mailbox sub-system flush routine to forcefully bring down the
10587  * mailbox sub-system. Otherwise, if it is due to normal condition (such
10588  * as with offline or HBA function reset), this routine will wait for the
10589  * outstanding mailbox command to complete before invoking the mailbox
10590  * sub-system flush routine to gracefully bring down mailbox sub-system.
10591  **/
10592 void
10593 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
10594 {
10595 	struct lpfc_sli *psli = &phba->sli;
10596 	unsigned long timeout;
10597 
10598 	if (mbx_action == LPFC_MBX_NO_WAIT) {
10599 		/* delay 100ms for port state */
10600 		msleep(100);
10601 		lpfc_sli_mbox_sys_flush(phba);
10602 		return;
10603 	}
10604 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
10605 
10606 	spin_lock_irq(&phba->hbalock);
10607 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
10608 
10609 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
10610 		/* Determine how long we might wait for the active mailbox
10611 		 * command to be gracefully completed by firmware.
10612 		 */
10613 		if (phba->sli.mbox_active)
10614 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
10615 						phba->sli.mbox_active) *
10616 						1000) + jiffies;
10617 		spin_unlock_irq(&phba->hbalock);
10618 
10619 		while (phba->sli.mbox_active) {
10620 			/* Check active mailbox complete status every 2ms */
10621 			msleep(2);
10622 			if (time_after(jiffies, timeout))
10623 				/* Timeout, let the mailbox flush routine to
10624 				 * forcefully release active mailbox command
10625 				 */
10626 				break;
10627 		}
10628 	} else
10629 		spin_unlock_irq(&phba->hbalock);
10630 
10631 	lpfc_sli_mbox_sys_flush(phba);
10632 }
10633 
10634 /**
10635  * lpfc_sli_eratt_read - read sli-3 error attention events
10636  * @phba: Pointer to HBA context.
10637  *
10638  * This function is called to read the SLI3 device error attention registers
10639  * for possible error attention events. The caller must hold the hostlock
10640  * with spin_lock_irq().
10641  *
10642  * This function returns 1 when there is Error Attention in the Host Attention
10643  * Register and returns 0 otherwise.
10644  **/
10645 static int
10646 lpfc_sli_eratt_read(struct lpfc_hba *phba)
10647 {
10648 	uint32_t ha_copy;
10649 
10650 	/* Read chip Host Attention (HA) register */
10651 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
10652 		goto unplug_err;
10653 
10654 	if (ha_copy & HA_ERATT) {
10655 		/* Read host status register to retrieve error event */
10656 		if (lpfc_sli_read_hs(phba))
10657 			goto unplug_err;
10658 
10659 		/* Check if there is a deferred error condition is active */
10660 		if ((HS_FFER1 & phba->work_hs) &&
10661 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
10662 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
10663 			phba->hba_flag |= DEFER_ERATT;
10664 			/* Clear all interrupt enable conditions */
10665 			writel(0, phba->HCregaddr);
10666 			readl(phba->HCregaddr);
10667 		}
10668 
10669 		/* Set the driver HA work bitmap */
10670 		phba->work_ha |= HA_ERATT;
10671 		/* Indicate polling handles this ERATT */
10672 		phba->hba_flag |= HBA_ERATT_HANDLED;
10673 		return 1;
10674 	}
10675 	return 0;
10676 
10677 unplug_err:
10678 	/* Set the driver HS work bitmap */
10679 	phba->work_hs |= UNPLUG_ERR;
10680 	/* Set the driver HA work bitmap */
10681 	phba->work_ha |= HA_ERATT;
10682 	/* Indicate polling handles this ERATT */
10683 	phba->hba_flag |= HBA_ERATT_HANDLED;
10684 	return 1;
10685 }
10686 
10687 /**
10688  * lpfc_sli4_eratt_read - read sli-4 error attention events
10689  * @phba: Pointer to HBA context.
10690  *
10691  * This function is called to read the SLI4 device error attention registers
10692  * for possible error attention events. The caller must hold the hostlock
10693  * with spin_lock_irq().
10694  *
10695  * This function returns 1 when there is Error Attention in the Host Attention
10696  * Register and returns 0 otherwise.
10697  **/
10698 static int
10699 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
10700 {
10701 	uint32_t uerr_sta_hi, uerr_sta_lo;
10702 	uint32_t if_type, portsmphr;
10703 	struct lpfc_register portstat_reg;
10704 
10705 	/*
10706 	 * For now, use the SLI4 device internal unrecoverable error
10707 	 * registers for error attention. This can be changed later.
10708 	 */
10709 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10710 	switch (if_type) {
10711 	case LPFC_SLI_INTF_IF_TYPE_0:
10712 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
10713 			&uerr_sta_lo) ||
10714 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
10715 			&uerr_sta_hi)) {
10716 			phba->work_hs |= UNPLUG_ERR;
10717 			phba->work_ha |= HA_ERATT;
10718 			phba->hba_flag |= HBA_ERATT_HANDLED;
10719 			return 1;
10720 		}
10721 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
10722 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
10723 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10724 					"1423 HBA Unrecoverable error: "
10725 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
10726 					"ue_mask_lo_reg=0x%x, "
10727 					"ue_mask_hi_reg=0x%x\n",
10728 					uerr_sta_lo, uerr_sta_hi,
10729 					phba->sli4_hba.ue_mask_lo,
10730 					phba->sli4_hba.ue_mask_hi);
10731 			phba->work_status[0] = uerr_sta_lo;
10732 			phba->work_status[1] = uerr_sta_hi;
10733 			phba->work_ha |= HA_ERATT;
10734 			phba->hba_flag |= HBA_ERATT_HANDLED;
10735 			return 1;
10736 		}
10737 		break;
10738 	case LPFC_SLI_INTF_IF_TYPE_2:
10739 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
10740 			&portstat_reg.word0) ||
10741 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
10742 			&portsmphr)){
10743 			phba->work_hs |= UNPLUG_ERR;
10744 			phba->work_ha |= HA_ERATT;
10745 			phba->hba_flag |= HBA_ERATT_HANDLED;
10746 			return 1;
10747 		}
10748 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
10749 			phba->work_status[0] =
10750 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
10751 			phba->work_status[1] =
10752 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
10753 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10754 					"2885 Port Status Event: "
10755 					"port status reg 0x%x, "
10756 					"port smphr reg 0x%x, "
10757 					"error 1=0x%x, error 2=0x%x\n",
10758 					portstat_reg.word0,
10759 					portsmphr,
10760 					phba->work_status[0],
10761 					phba->work_status[1]);
10762 			phba->work_ha |= HA_ERATT;
10763 			phba->hba_flag |= HBA_ERATT_HANDLED;
10764 			return 1;
10765 		}
10766 		break;
10767 	case LPFC_SLI_INTF_IF_TYPE_1:
10768 	default:
10769 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10770 				"2886 HBA Error Attention on unsupported "
10771 				"if type %d.", if_type);
10772 		return 1;
10773 	}
10774 
10775 	return 0;
10776 }
10777 
10778 /**
10779  * lpfc_sli_check_eratt - check error attention events
10780  * @phba: Pointer to HBA context.
10781  *
10782  * This function is called from timer soft interrupt context to check HBA's
10783  * error attention register bit for error attention events.
10784  *
10785  * This function returns 1 when there is Error Attention in the Host Attention
10786  * Register and returns 0 otherwise.
10787  **/
10788 int
10789 lpfc_sli_check_eratt(struct lpfc_hba *phba)
10790 {
10791 	uint32_t ha_copy;
10792 
10793 	/* If somebody is waiting to handle an eratt, don't process it
10794 	 * here. The brdkill function will do this.
10795 	 */
10796 	if (phba->link_flag & LS_IGNORE_ERATT)
10797 		return 0;
10798 
10799 	/* Check if interrupt handler handles this ERATT */
10800 	spin_lock_irq(&phba->hbalock);
10801 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
10802 		/* Interrupt handler has handled ERATT */
10803 		spin_unlock_irq(&phba->hbalock);
10804 		return 0;
10805 	}
10806 
10807 	/*
10808 	 * If there is deferred error attention, do not check for error
10809 	 * attention
10810 	 */
10811 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
10812 		spin_unlock_irq(&phba->hbalock);
10813 		return 0;
10814 	}
10815 
10816 	/* If PCI channel is offline, don't process it */
10817 	if (unlikely(pci_channel_offline(phba->pcidev))) {
10818 		spin_unlock_irq(&phba->hbalock);
10819 		return 0;
10820 	}
10821 
10822 	switch (phba->sli_rev) {
10823 	case LPFC_SLI_REV2:
10824 	case LPFC_SLI_REV3:
10825 		/* Read chip Host Attention (HA) register */
10826 		ha_copy = lpfc_sli_eratt_read(phba);
10827 		break;
10828 	case LPFC_SLI_REV4:
10829 		/* Read device Uncoverable Error (UERR) registers */
10830 		ha_copy = lpfc_sli4_eratt_read(phba);
10831 		break;
10832 	default:
10833 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10834 				"0299 Invalid SLI revision (%d)\n",
10835 				phba->sli_rev);
10836 		ha_copy = 0;
10837 		break;
10838 	}
10839 	spin_unlock_irq(&phba->hbalock);
10840 
10841 	return ha_copy;
10842 }
10843 
10844 /**
10845  * lpfc_intr_state_check - Check device state for interrupt handling
10846  * @phba: Pointer to HBA context.
10847  *
10848  * This inline routine checks whether a device or its PCI slot is in a state
10849  * that the interrupt should be handled.
10850  *
10851  * This function returns 0 if the device or the PCI slot is in a state that
10852  * interrupt should be handled, otherwise -EIO.
10853  */
10854 static inline int
10855 lpfc_intr_state_check(struct lpfc_hba *phba)
10856 {
10857 	/* If the pci channel is offline, ignore all the interrupts */
10858 	if (unlikely(pci_channel_offline(phba->pcidev)))
10859 		return -EIO;
10860 
10861 	/* Update device level interrupt statistics */
10862 	phba->sli.slistat.sli_intr++;
10863 
10864 	/* Ignore all interrupts during initialization. */
10865 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
10866 		return -EIO;
10867 
10868 	return 0;
10869 }
10870 
10871 /**
10872  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
10873  * @irq: Interrupt number.
10874  * @dev_id: The device context pointer.
10875  *
10876  * This function is directly called from the PCI layer as an interrupt
10877  * service routine when device with SLI-3 interface spec is enabled with
10878  * MSI-X multi-message interrupt mode and there are slow-path events in
10879  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
10880  * interrupt mode, this function is called as part of the device-level
10881  * interrupt handler. When the PCI slot is in error recovery or the HBA
10882  * is undergoing initialization, the interrupt handler will not process
10883  * the interrupt. The link attention and ELS ring attention events are
10884  * handled by the worker thread. The interrupt handler signals the worker
10885  * thread and returns for these events. This function is called without
10886  * any lock held. It gets the hbalock to access and update SLI data
10887  * structures.
10888  *
10889  * This function returns IRQ_HANDLED when interrupt is handled else it
10890  * returns IRQ_NONE.
10891  **/
10892 irqreturn_t
10893 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
10894 {
10895 	struct lpfc_hba  *phba;
10896 	uint32_t ha_copy, hc_copy;
10897 	uint32_t work_ha_copy;
10898 	unsigned long status;
10899 	unsigned long iflag;
10900 	uint32_t control;
10901 
10902 	MAILBOX_t *mbox, *pmbox;
10903 	struct lpfc_vport *vport;
10904 	struct lpfc_nodelist *ndlp;
10905 	struct lpfc_dmabuf *mp;
10906 	LPFC_MBOXQ_t *pmb;
10907 	int rc;
10908 
10909 	/*
10910 	 * Get the driver's phba structure from the dev_id and
10911 	 * assume the HBA is not interrupting.
10912 	 */
10913 	phba = (struct lpfc_hba *)dev_id;
10914 
10915 	if (unlikely(!phba))
10916 		return IRQ_NONE;
10917 
10918 	/*
10919 	 * Stuff needs to be attented to when this function is invoked as an
10920 	 * individual interrupt handler in MSI-X multi-message interrupt mode
10921 	 */
10922 	if (phba->intr_type == MSIX) {
10923 		/* Check device state for handling interrupt */
10924 		if (lpfc_intr_state_check(phba))
10925 			return IRQ_NONE;
10926 		/* Need to read HA REG for slow-path events */
10927 		spin_lock_irqsave(&phba->hbalock, iflag);
10928 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
10929 			goto unplug_error;
10930 		/* If somebody is waiting to handle an eratt don't process it
10931 		 * here. The brdkill function will do this.
10932 		 */
10933 		if (phba->link_flag & LS_IGNORE_ERATT)
10934 			ha_copy &= ~HA_ERATT;
10935 		/* Check the need for handling ERATT in interrupt handler */
10936 		if (ha_copy & HA_ERATT) {
10937 			if (phba->hba_flag & HBA_ERATT_HANDLED)
10938 				/* ERATT polling has handled ERATT */
10939 				ha_copy &= ~HA_ERATT;
10940 			else
10941 				/* Indicate interrupt handler handles ERATT */
10942 				phba->hba_flag |= HBA_ERATT_HANDLED;
10943 		}
10944 
10945 		/*
10946 		 * If there is deferred error attention, do not check for any
10947 		 * interrupt.
10948 		 */
10949 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
10950 			spin_unlock_irqrestore(&phba->hbalock, iflag);
10951 			return IRQ_NONE;
10952 		}
10953 
10954 		/* Clear up only attention source related to slow-path */
10955 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
10956 			goto unplug_error;
10957 
10958 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
10959 			HC_LAINT_ENA | HC_ERINT_ENA),
10960 			phba->HCregaddr);
10961 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
10962 			phba->HAregaddr);
10963 		writel(hc_copy, phba->HCregaddr);
10964 		readl(phba->HAregaddr); /* flush */
10965 		spin_unlock_irqrestore(&phba->hbalock, iflag);
10966 	} else
10967 		ha_copy = phba->ha_copy;
10968 
10969 	work_ha_copy = ha_copy & phba->work_ha_mask;
10970 
10971 	if (work_ha_copy) {
10972 		if (work_ha_copy & HA_LATT) {
10973 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
10974 				/*
10975 				 * Turn off Link Attention interrupts
10976 				 * until CLEAR_LA done
10977 				 */
10978 				spin_lock_irqsave(&phba->hbalock, iflag);
10979 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
10980 				if (lpfc_readl(phba->HCregaddr, &control))
10981 					goto unplug_error;
10982 				control &= ~HC_LAINT_ENA;
10983 				writel(control, phba->HCregaddr);
10984 				readl(phba->HCregaddr); /* flush */
10985 				spin_unlock_irqrestore(&phba->hbalock, iflag);
10986 			}
10987 			else
10988 				work_ha_copy &= ~HA_LATT;
10989 		}
10990 
10991 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
10992 			/*
10993 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
10994 			 * the only slow ring.
10995 			 */
10996 			status = (work_ha_copy &
10997 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
10998 			status >>= (4*LPFC_ELS_RING);
10999 			if (status & HA_RXMASK) {
11000 				spin_lock_irqsave(&phba->hbalock, iflag);
11001 				if (lpfc_readl(phba->HCregaddr, &control))
11002 					goto unplug_error;
11003 
11004 				lpfc_debugfs_slow_ring_trc(phba,
11005 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
11006 				control, status,
11007 				(uint32_t)phba->sli.slistat.sli_intr);
11008 
11009 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
11010 					lpfc_debugfs_slow_ring_trc(phba,
11011 						"ISR Disable ring:"
11012 						"pwork:x%x hawork:x%x wait:x%x",
11013 						phba->work_ha, work_ha_copy,
11014 						(uint32_t)((unsigned long)
11015 						&phba->work_waitq));
11016 
11017 					control &=
11018 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
11019 					writel(control, phba->HCregaddr);
11020 					readl(phba->HCregaddr); /* flush */
11021 				}
11022 				else {
11023 					lpfc_debugfs_slow_ring_trc(phba,
11024 						"ISR slow ring:   pwork:"
11025 						"x%x hawork:x%x wait:x%x",
11026 						phba->work_ha, work_ha_copy,
11027 						(uint32_t)((unsigned long)
11028 						&phba->work_waitq));
11029 				}
11030 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11031 			}
11032 		}
11033 		spin_lock_irqsave(&phba->hbalock, iflag);
11034 		if (work_ha_copy & HA_ERATT) {
11035 			if (lpfc_sli_read_hs(phba))
11036 				goto unplug_error;
11037 			/*
11038 			 * Check if there is a deferred error condition
11039 			 * is active
11040 			 */
11041 			if ((HS_FFER1 & phba->work_hs) &&
11042 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
11043 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
11044 				  phba->work_hs)) {
11045 				phba->hba_flag |= DEFER_ERATT;
11046 				/* Clear all interrupt enable conditions */
11047 				writel(0, phba->HCregaddr);
11048 				readl(phba->HCregaddr);
11049 			}
11050 		}
11051 
11052 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
11053 			pmb = phba->sli.mbox_active;
11054 			pmbox = &pmb->u.mb;
11055 			mbox = phba->mbox;
11056 			vport = pmb->vport;
11057 
11058 			/* First check out the status word */
11059 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
11060 			if (pmbox->mbxOwner != OWN_HOST) {
11061 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11062 				/*
11063 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
11064 				 * mbxStatus <status>
11065 				 */
11066 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11067 						LOG_SLI,
11068 						"(%d):0304 Stray Mailbox "
11069 						"Interrupt mbxCommand x%x "
11070 						"mbxStatus x%x\n",
11071 						(vport ? vport->vpi : 0),
11072 						pmbox->mbxCommand,
11073 						pmbox->mbxStatus);
11074 				/* clear mailbox attention bit */
11075 				work_ha_copy &= ~HA_MBATT;
11076 			} else {
11077 				phba->sli.mbox_active = NULL;
11078 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11079 				phba->last_completion_time = jiffies;
11080 				del_timer(&phba->sli.mbox_tmo);
11081 				if (pmb->mbox_cmpl) {
11082 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
11083 							MAILBOX_CMD_SIZE);
11084 					if (pmb->out_ext_byte_len &&
11085 						pmb->context2)
11086 						lpfc_sli_pcimem_bcopy(
11087 						phba->mbox_ext,
11088 						pmb->context2,
11089 						pmb->out_ext_byte_len);
11090 				}
11091 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
11092 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
11093 
11094 					lpfc_debugfs_disc_trc(vport,
11095 						LPFC_DISC_TRC_MBOX_VPORT,
11096 						"MBOX dflt rpi: : "
11097 						"status:x%x rpi:x%x",
11098 						(uint32_t)pmbox->mbxStatus,
11099 						pmbox->un.varWords[0], 0);
11100 
11101 					if (!pmbox->mbxStatus) {
11102 						mp = (struct lpfc_dmabuf *)
11103 							(pmb->context1);
11104 						ndlp = (struct lpfc_nodelist *)
11105 							pmb->context2;
11106 
11107 						/* Reg_LOGIN of dflt RPI was
11108 						 * successful. new lets get
11109 						 * rid of the RPI using the
11110 						 * same mbox buffer.
11111 						 */
11112 						lpfc_unreg_login(phba,
11113 							vport->vpi,
11114 							pmbox->un.varWords[0],
11115 							pmb);
11116 						pmb->mbox_cmpl =
11117 							lpfc_mbx_cmpl_dflt_rpi;
11118 						pmb->context1 = mp;
11119 						pmb->context2 = ndlp;
11120 						pmb->vport = vport;
11121 						rc = lpfc_sli_issue_mbox(phba,
11122 								pmb,
11123 								MBX_NOWAIT);
11124 						if (rc != MBX_BUSY)
11125 							lpfc_printf_log(phba,
11126 							KERN_ERR,
11127 							LOG_MBOX | LOG_SLI,
11128 							"0350 rc should have"
11129 							"been MBX_BUSY\n");
11130 						if (rc != MBX_NOT_FINISHED)
11131 							goto send_current_mbox;
11132 					}
11133 				}
11134 				spin_lock_irqsave(
11135 						&phba->pport->work_port_lock,
11136 						iflag);
11137 				phba->pport->work_port_events &=
11138 					~WORKER_MBOX_TMO;
11139 				spin_unlock_irqrestore(
11140 						&phba->pport->work_port_lock,
11141 						iflag);
11142 				lpfc_mbox_cmpl_put(phba, pmb);
11143 			}
11144 		} else
11145 			spin_unlock_irqrestore(&phba->hbalock, iflag);
11146 
11147 		if ((work_ha_copy & HA_MBATT) &&
11148 		    (phba->sli.mbox_active == NULL)) {
11149 send_current_mbox:
11150 			/* Process next mailbox command if there is one */
11151 			do {
11152 				rc = lpfc_sli_issue_mbox(phba, NULL,
11153 							 MBX_NOWAIT);
11154 			} while (rc == MBX_NOT_FINISHED);
11155 			if (rc != MBX_SUCCESS)
11156 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11157 						LOG_SLI, "0349 rc should be "
11158 						"MBX_SUCCESS\n");
11159 		}
11160 
11161 		spin_lock_irqsave(&phba->hbalock, iflag);
11162 		phba->work_ha |= work_ha_copy;
11163 		spin_unlock_irqrestore(&phba->hbalock, iflag);
11164 		lpfc_worker_wake_up(phba);
11165 	}
11166 	return IRQ_HANDLED;
11167 unplug_error:
11168 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11169 	return IRQ_HANDLED;
11170 
11171 } /* lpfc_sli_sp_intr_handler */
11172 
11173 /**
11174  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
11175  * @irq: Interrupt number.
11176  * @dev_id: The device context pointer.
11177  *
11178  * This function is directly called from the PCI layer as an interrupt
11179  * service routine when device with SLI-3 interface spec is enabled with
11180  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
11181  * ring event in the HBA. However, when the device is enabled with either
11182  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
11183  * device-level interrupt handler. When the PCI slot is in error recovery
11184  * or the HBA is undergoing initialization, the interrupt handler will not
11185  * process the interrupt. The SCSI FCP fast-path ring event are handled in
11186  * the intrrupt context. This function is called without any lock held.
11187  * It gets the hbalock to access and update SLI data structures.
11188  *
11189  * This function returns IRQ_HANDLED when interrupt is handled else it
11190  * returns IRQ_NONE.
11191  **/
11192 irqreturn_t
11193 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
11194 {
11195 	struct lpfc_hba  *phba;
11196 	uint32_t ha_copy;
11197 	unsigned long status;
11198 	unsigned long iflag;
11199 
11200 	/* Get the driver's phba structure from the dev_id and
11201 	 * assume the HBA is not interrupting.
11202 	 */
11203 	phba = (struct lpfc_hba *) dev_id;
11204 
11205 	if (unlikely(!phba))
11206 		return IRQ_NONE;
11207 
11208 	/*
11209 	 * Stuff needs to be attented to when this function is invoked as an
11210 	 * individual interrupt handler in MSI-X multi-message interrupt mode
11211 	 */
11212 	if (phba->intr_type == MSIX) {
11213 		/* Check device state for handling interrupt */
11214 		if (lpfc_intr_state_check(phba))
11215 			return IRQ_NONE;
11216 		/* Need to read HA REG for FCP ring and other ring events */
11217 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
11218 			return IRQ_HANDLED;
11219 		/* Clear up only attention source related to fast-path */
11220 		spin_lock_irqsave(&phba->hbalock, iflag);
11221 		/*
11222 		 * If there is deferred error attention, do not check for
11223 		 * any interrupt.
11224 		 */
11225 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11226 			spin_unlock_irqrestore(&phba->hbalock, iflag);
11227 			return IRQ_NONE;
11228 		}
11229 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
11230 			phba->HAregaddr);
11231 		readl(phba->HAregaddr); /* flush */
11232 		spin_unlock_irqrestore(&phba->hbalock, iflag);
11233 	} else
11234 		ha_copy = phba->ha_copy;
11235 
11236 	/*
11237 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
11238 	 */
11239 	ha_copy &= ~(phba->work_ha_mask);
11240 
11241 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
11242 	status >>= (4*LPFC_FCP_RING);
11243 	if (status & HA_RXMASK)
11244 		lpfc_sli_handle_fast_ring_event(phba,
11245 						&phba->sli.ring[LPFC_FCP_RING],
11246 						status);
11247 
11248 	if (phba->cfg_multi_ring_support == 2) {
11249 		/*
11250 		 * Process all events on extra ring. Take the optimized path
11251 		 * for extra ring IO.
11252 		 */
11253 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
11254 		status >>= (4*LPFC_EXTRA_RING);
11255 		if (status & HA_RXMASK) {
11256 			lpfc_sli_handle_fast_ring_event(phba,
11257 					&phba->sli.ring[LPFC_EXTRA_RING],
11258 					status);
11259 		}
11260 	}
11261 	return IRQ_HANDLED;
11262 }  /* lpfc_sli_fp_intr_handler */
11263 
11264 /**
11265  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
11266  * @irq: Interrupt number.
11267  * @dev_id: The device context pointer.
11268  *
11269  * This function is the HBA device-level interrupt handler to device with
11270  * SLI-3 interface spec, called from the PCI layer when either MSI or
11271  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
11272  * requires driver attention. This function invokes the slow-path interrupt
11273  * attention handling function and fast-path interrupt attention handling
11274  * function in turn to process the relevant HBA attention events. This
11275  * function is called without any lock held. It gets the hbalock to access
11276  * and update SLI data structures.
11277  *
11278  * This function returns IRQ_HANDLED when interrupt is handled, else it
11279  * returns IRQ_NONE.
11280  **/
11281 irqreturn_t
11282 lpfc_sli_intr_handler(int irq, void *dev_id)
11283 {
11284 	struct lpfc_hba  *phba;
11285 	irqreturn_t sp_irq_rc, fp_irq_rc;
11286 	unsigned long status1, status2;
11287 	uint32_t hc_copy;
11288 
11289 	/*
11290 	 * Get the driver's phba structure from the dev_id and
11291 	 * assume the HBA is not interrupting.
11292 	 */
11293 	phba = (struct lpfc_hba *) dev_id;
11294 
11295 	if (unlikely(!phba))
11296 		return IRQ_NONE;
11297 
11298 	/* Check device state for handling interrupt */
11299 	if (lpfc_intr_state_check(phba))
11300 		return IRQ_NONE;
11301 
11302 	spin_lock(&phba->hbalock);
11303 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
11304 		spin_unlock(&phba->hbalock);
11305 		return IRQ_HANDLED;
11306 	}
11307 
11308 	if (unlikely(!phba->ha_copy)) {
11309 		spin_unlock(&phba->hbalock);
11310 		return IRQ_NONE;
11311 	} else if (phba->ha_copy & HA_ERATT) {
11312 		if (phba->hba_flag & HBA_ERATT_HANDLED)
11313 			/* ERATT polling has handled ERATT */
11314 			phba->ha_copy &= ~HA_ERATT;
11315 		else
11316 			/* Indicate interrupt handler handles ERATT */
11317 			phba->hba_flag |= HBA_ERATT_HANDLED;
11318 	}
11319 
11320 	/*
11321 	 * If there is deferred error attention, do not check for any interrupt.
11322 	 */
11323 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11324 		spin_unlock(&phba->hbalock);
11325 		return IRQ_NONE;
11326 	}
11327 
11328 	/* Clear attention sources except link and error attentions */
11329 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
11330 		spin_unlock(&phba->hbalock);
11331 		return IRQ_HANDLED;
11332 	}
11333 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
11334 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
11335 		phba->HCregaddr);
11336 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
11337 	writel(hc_copy, phba->HCregaddr);
11338 	readl(phba->HAregaddr); /* flush */
11339 	spin_unlock(&phba->hbalock);
11340 
11341 	/*
11342 	 * Invokes slow-path host attention interrupt handling as appropriate.
11343 	 */
11344 
11345 	/* status of events with mailbox and link attention */
11346 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
11347 
11348 	/* status of events with ELS ring */
11349 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
11350 	status2 >>= (4*LPFC_ELS_RING);
11351 
11352 	if (status1 || (status2 & HA_RXMASK))
11353 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
11354 	else
11355 		sp_irq_rc = IRQ_NONE;
11356 
11357 	/*
11358 	 * Invoke fast-path host attention interrupt handling as appropriate.
11359 	 */
11360 
11361 	/* status of events with FCP ring */
11362 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
11363 	status1 >>= (4*LPFC_FCP_RING);
11364 
11365 	/* status of events with extra ring */
11366 	if (phba->cfg_multi_ring_support == 2) {
11367 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
11368 		status2 >>= (4*LPFC_EXTRA_RING);
11369 	} else
11370 		status2 = 0;
11371 
11372 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
11373 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
11374 	else
11375 		fp_irq_rc = IRQ_NONE;
11376 
11377 	/* Return device-level interrupt handling status */
11378 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
11379 }  /* lpfc_sli_intr_handler */
11380 
11381 /**
11382  * lpfc_sli4_fcp_xri_abort_event_proc - Process fcp xri abort event
11383  * @phba: pointer to lpfc hba data structure.
11384  *
11385  * This routine is invoked by the worker thread to process all the pending
11386  * SLI4 FCP abort XRI events.
11387  **/
11388 void lpfc_sli4_fcp_xri_abort_event_proc(struct lpfc_hba *phba)
11389 {
11390 	struct lpfc_cq_event *cq_event;
11391 
11392 	/* First, declare the fcp xri abort event has been handled */
11393 	spin_lock_irq(&phba->hbalock);
11394 	phba->hba_flag &= ~FCP_XRI_ABORT_EVENT;
11395 	spin_unlock_irq(&phba->hbalock);
11396 	/* Now, handle all the fcp xri abort events */
11397 	while (!list_empty(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue)) {
11398 		/* Get the first event from the head of the event queue */
11399 		spin_lock_irq(&phba->hbalock);
11400 		list_remove_head(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue,
11401 				 cq_event, struct lpfc_cq_event, list);
11402 		spin_unlock_irq(&phba->hbalock);
11403 		/* Notify aborted XRI for FCP work queue */
11404 		lpfc_sli4_fcp_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
11405 		/* Free the event processed back to the free pool */
11406 		lpfc_sli4_cq_event_release(phba, cq_event);
11407 	}
11408 }
11409 
11410 /**
11411  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
11412  * @phba: pointer to lpfc hba data structure.
11413  *
11414  * This routine is invoked by the worker thread to process all the pending
11415  * SLI4 els abort xri events.
11416  **/
11417 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
11418 {
11419 	struct lpfc_cq_event *cq_event;
11420 
11421 	/* First, declare the els xri abort event has been handled */
11422 	spin_lock_irq(&phba->hbalock);
11423 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
11424 	spin_unlock_irq(&phba->hbalock);
11425 	/* Now, handle all the els xri abort events */
11426 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
11427 		/* Get the first event from the head of the event queue */
11428 		spin_lock_irq(&phba->hbalock);
11429 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
11430 				 cq_event, struct lpfc_cq_event, list);
11431 		spin_unlock_irq(&phba->hbalock);
11432 		/* Notify aborted XRI for ELS work queue */
11433 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
11434 		/* Free the event processed back to the free pool */
11435 		lpfc_sli4_cq_event_release(phba, cq_event);
11436 	}
11437 }
11438 
11439 /**
11440  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
11441  * @phba: pointer to lpfc hba data structure
11442  * @pIocbIn: pointer to the rspiocbq
11443  * @pIocbOut: pointer to the cmdiocbq
11444  * @wcqe: pointer to the complete wcqe
11445  *
11446  * This routine transfers the fields of a command iocbq to a response iocbq
11447  * by copying all the IOCB fields from command iocbq and transferring the
11448  * completion status information from the complete wcqe.
11449  **/
11450 static void
11451 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
11452 			      struct lpfc_iocbq *pIocbIn,
11453 			      struct lpfc_iocbq *pIocbOut,
11454 			      struct lpfc_wcqe_complete *wcqe)
11455 {
11456 	int numBdes, i;
11457 	unsigned long iflags;
11458 	uint32_t status, max_response;
11459 	struct lpfc_dmabuf *dmabuf;
11460 	struct ulp_bde64 *bpl, bde;
11461 	size_t offset = offsetof(struct lpfc_iocbq, iocb);
11462 
11463 	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
11464 	       sizeof(struct lpfc_iocbq) - offset);
11465 	/* Map WCQE parameters into irspiocb parameters */
11466 	status = bf_get(lpfc_wcqe_c_status, wcqe);
11467 	pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
11468 	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
11469 		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
11470 			pIocbIn->iocb.un.fcpi.fcpi_parm =
11471 					pIocbOut->iocb.un.fcpi.fcpi_parm -
11472 					wcqe->total_data_placed;
11473 		else
11474 			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
11475 	else {
11476 		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
11477 		switch (pIocbOut->iocb.ulpCommand) {
11478 		case CMD_ELS_REQUEST64_CR:
11479 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
11480 			bpl  = (struct ulp_bde64 *)dmabuf->virt;
11481 			bde.tus.w = le32_to_cpu(bpl[1].tus.w);
11482 			max_response = bde.tus.f.bdeSize;
11483 			break;
11484 		case CMD_GEN_REQUEST64_CR:
11485 			max_response = 0;
11486 			if (!pIocbOut->context3)
11487 				break;
11488 			numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
11489 					sizeof(struct ulp_bde64);
11490 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
11491 			bpl = (struct ulp_bde64 *)dmabuf->virt;
11492 			for (i = 0; i < numBdes; i++) {
11493 				bde.tus.w = le32_to_cpu(bpl[i].tus.w);
11494 				if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
11495 					max_response += bde.tus.f.bdeSize;
11496 			}
11497 			break;
11498 		default:
11499 			max_response = wcqe->total_data_placed;
11500 			break;
11501 		}
11502 		if (max_response < wcqe->total_data_placed)
11503 			pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
11504 		else
11505 			pIocbIn->iocb.un.genreq64.bdl.bdeSize =
11506 				wcqe->total_data_placed;
11507 	}
11508 
11509 	/* Convert BG errors for completion status */
11510 	if (status == CQE_STATUS_DI_ERROR) {
11511 		pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
11512 
11513 		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
11514 			pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
11515 		else
11516 			pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
11517 
11518 		pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
11519 		if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
11520 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11521 				BGS_GUARD_ERR_MASK;
11522 		if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
11523 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11524 				BGS_APPTAG_ERR_MASK;
11525 		if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
11526 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11527 				BGS_REFTAG_ERR_MASK;
11528 
11529 		/* Check to see if there was any good data before the error */
11530 		if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
11531 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11532 				BGS_HI_WATER_MARK_PRESENT_MASK;
11533 			pIocbIn->iocb.unsli3.sli3_bg.bghm =
11534 				wcqe->total_data_placed;
11535 		}
11536 
11537 		/*
11538 		* Set ALL the error bits to indicate we don't know what
11539 		* type of error it is.
11540 		*/
11541 		if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
11542 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11543 				(BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
11544 				BGS_GUARD_ERR_MASK);
11545 	}
11546 
11547 	/* Pick up HBA exchange busy condition */
11548 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
11549 		spin_lock_irqsave(&phba->hbalock, iflags);
11550 		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
11551 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11552 	}
11553 }
11554 
11555 /**
11556  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
11557  * @phba: Pointer to HBA context object.
11558  * @wcqe: Pointer to work-queue completion queue entry.
11559  *
11560  * This routine handles an ELS work-queue completion event and construct
11561  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
11562  * discovery engine to handle.
11563  *
11564  * Return: Pointer to the receive IOCBQ, NULL otherwise.
11565  **/
11566 static struct lpfc_iocbq *
11567 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
11568 			       struct lpfc_iocbq *irspiocbq)
11569 {
11570 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
11571 	struct lpfc_iocbq *cmdiocbq;
11572 	struct lpfc_wcqe_complete *wcqe;
11573 	unsigned long iflags;
11574 
11575 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
11576 	spin_lock_irqsave(&pring->ring_lock, iflags);
11577 	pring->stats.iocb_event++;
11578 	/* Look up the ELS command IOCB and create pseudo response IOCB */
11579 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
11580 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
11581 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
11582 
11583 	if (unlikely(!cmdiocbq)) {
11584 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11585 				"0386 ELS complete with no corresponding "
11586 				"cmdiocb: iotag (%d)\n",
11587 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
11588 		lpfc_sli_release_iocbq(phba, irspiocbq);
11589 		return NULL;
11590 	}
11591 
11592 	/* Fake the irspiocbq and copy necessary response information */
11593 	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
11594 
11595 	return irspiocbq;
11596 }
11597 
11598 /**
11599  * lpfc_sli4_sp_handle_async_event - Handle an asynchroous event
11600  * @phba: Pointer to HBA context object.
11601  * @cqe: Pointer to mailbox completion queue entry.
11602  *
11603  * This routine process a mailbox completion queue entry with asynchrous
11604  * event.
11605  *
11606  * Return: true if work posted to worker thread, otherwise false.
11607  **/
11608 static bool
11609 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
11610 {
11611 	struct lpfc_cq_event *cq_event;
11612 	unsigned long iflags;
11613 
11614 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11615 			"0392 Async Event: word0:x%x, word1:x%x, "
11616 			"word2:x%x, word3:x%x\n", mcqe->word0,
11617 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
11618 
11619 	/* Allocate a new internal CQ_EVENT entry */
11620 	cq_event = lpfc_sli4_cq_event_alloc(phba);
11621 	if (!cq_event) {
11622 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11623 				"0394 Failed to allocate CQ_EVENT entry\n");
11624 		return false;
11625 	}
11626 
11627 	/* Move the CQE into an asynchronous event entry */
11628 	memcpy(&cq_event->cqe, mcqe, sizeof(struct lpfc_mcqe));
11629 	spin_lock_irqsave(&phba->hbalock, iflags);
11630 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
11631 	/* Set the async event flag */
11632 	phba->hba_flag |= ASYNC_EVENT;
11633 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11634 
11635 	return true;
11636 }
11637 
11638 /**
11639  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
11640  * @phba: Pointer to HBA context object.
11641  * @cqe: Pointer to mailbox completion queue entry.
11642  *
11643  * This routine process a mailbox completion queue entry with mailbox
11644  * completion event.
11645  *
11646  * Return: true if work posted to worker thread, otherwise false.
11647  **/
11648 static bool
11649 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
11650 {
11651 	uint32_t mcqe_status;
11652 	MAILBOX_t *mbox, *pmbox;
11653 	struct lpfc_mqe *mqe;
11654 	struct lpfc_vport *vport;
11655 	struct lpfc_nodelist *ndlp;
11656 	struct lpfc_dmabuf *mp;
11657 	unsigned long iflags;
11658 	LPFC_MBOXQ_t *pmb;
11659 	bool workposted = false;
11660 	int rc;
11661 
11662 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
11663 	if (!bf_get(lpfc_trailer_completed, mcqe))
11664 		goto out_no_mqe_complete;
11665 
11666 	/* Get the reference to the active mbox command */
11667 	spin_lock_irqsave(&phba->hbalock, iflags);
11668 	pmb = phba->sli.mbox_active;
11669 	if (unlikely(!pmb)) {
11670 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
11671 				"1832 No pending MBOX command to handle\n");
11672 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11673 		goto out_no_mqe_complete;
11674 	}
11675 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11676 	mqe = &pmb->u.mqe;
11677 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
11678 	mbox = phba->mbox;
11679 	vport = pmb->vport;
11680 
11681 	/* Reset heartbeat timer */
11682 	phba->last_completion_time = jiffies;
11683 	del_timer(&phba->sli.mbox_tmo);
11684 
11685 	/* Move mbox data to caller's mailbox region, do endian swapping */
11686 	if (pmb->mbox_cmpl && mbox)
11687 		lpfc_sli_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
11688 
11689 	/*
11690 	 * For mcqe errors, conditionally move a modified error code to
11691 	 * the mbox so that the error will not be missed.
11692 	 */
11693 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
11694 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
11695 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
11696 			bf_set(lpfc_mqe_status, mqe,
11697 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
11698 	}
11699 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
11700 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
11701 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
11702 				      "MBOX dflt rpi: status:x%x rpi:x%x",
11703 				      mcqe_status,
11704 				      pmbox->un.varWords[0], 0);
11705 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
11706 			mp = (struct lpfc_dmabuf *)(pmb->context1);
11707 			ndlp = (struct lpfc_nodelist *)pmb->context2;
11708 			/* Reg_LOGIN of dflt RPI was successful. Now lets get
11709 			 * RID of the PPI using the same mbox buffer.
11710 			 */
11711 			lpfc_unreg_login(phba, vport->vpi,
11712 					 pmbox->un.varWords[0], pmb);
11713 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
11714 			pmb->context1 = mp;
11715 			pmb->context2 = ndlp;
11716 			pmb->vport = vport;
11717 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
11718 			if (rc != MBX_BUSY)
11719 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11720 						LOG_SLI, "0385 rc should "
11721 						"have been MBX_BUSY\n");
11722 			if (rc != MBX_NOT_FINISHED)
11723 				goto send_current_mbox;
11724 		}
11725 	}
11726 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
11727 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
11728 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
11729 
11730 	/* There is mailbox completion work to do */
11731 	spin_lock_irqsave(&phba->hbalock, iflags);
11732 	__lpfc_mbox_cmpl_put(phba, pmb);
11733 	phba->work_ha |= HA_MBATT;
11734 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11735 	workposted = true;
11736 
11737 send_current_mbox:
11738 	spin_lock_irqsave(&phba->hbalock, iflags);
11739 	/* Release the mailbox command posting token */
11740 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11741 	/* Setting active mailbox pointer need to be in sync to flag clear */
11742 	phba->sli.mbox_active = NULL;
11743 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11744 	/* Wake up worker thread to post the next pending mailbox command */
11745 	lpfc_worker_wake_up(phba);
11746 out_no_mqe_complete:
11747 	if (bf_get(lpfc_trailer_consumed, mcqe))
11748 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
11749 	return workposted;
11750 }
11751 
11752 /**
11753  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
11754  * @phba: Pointer to HBA context object.
11755  * @cqe: Pointer to mailbox completion queue entry.
11756  *
11757  * This routine process a mailbox completion queue entry, it invokes the
11758  * proper mailbox complete handling or asynchrous event handling routine
11759  * according to the MCQE's async bit.
11760  *
11761  * Return: true if work posted to worker thread, otherwise false.
11762  **/
11763 static bool
11764 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_cqe *cqe)
11765 {
11766 	struct lpfc_mcqe mcqe;
11767 	bool workposted;
11768 
11769 	/* Copy the mailbox MCQE and convert endian order as needed */
11770 	lpfc_sli_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
11771 
11772 	/* Invoke the proper event handling routine */
11773 	if (!bf_get(lpfc_trailer_async, &mcqe))
11774 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
11775 	else
11776 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
11777 	return workposted;
11778 }
11779 
11780 /**
11781  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
11782  * @phba: Pointer to HBA context object.
11783  * @cq: Pointer to associated CQ
11784  * @wcqe: Pointer to work-queue completion queue entry.
11785  *
11786  * This routine handles an ELS work-queue completion event.
11787  *
11788  * Return: true if work posted to worker thread, otherwise false.
11789  **/
11790 static bool
11791 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
11792 			     struct lpfc_wcqe_complete *wcqe)
11793 {
11794 	struct lpfc_iocbq *irspiocbq;
11795 	unsigned long iflags;
11796 	struct lpfc_sli_ring *pring = cq->pring;
11797 	int txq_cnt = 0;
11798 	int txcmplq_cnt = 0;
11799 	int fcp_txcmplq_cnt = 0;
11800 
11801 	/* Get an irspiocbq for later ELS response processing use */
11802 	irspiocbq = lpfc_sli_get_iocbq(phba);
11803 	if (!irspiocbq) {
11804 		if (!list_empty(&pring->txq))
11805 			txq_cnt++;
11806 		if (!list_empty(&pring->txcmplq))
11807 			txcmplq_cnt++;
11808 		if (!list_empty(&phba->sli.ring[LPFC_FCP_RING].txcmplq))
11809 			fcp_txcmplq_cnt++;
11810 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11811 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
11812 			"fcp_txcmplq_cnt=%d, els_txcmplq_cnt=%d\n",
11813 			txq_cnt, phba->iocb_cnt,
11814 			fcp_txcmplq_cnt,
11815 			txcmplq_cnt);
11816 		return false;
11817 	}
11818 
11819 	/* Save off the slow-path queue event for work thread to process */
11820 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
11821 	spin_lock_irqsave(&phba->hbalock, iflags);
11822 	list_add_tail(&irspiocbq->cq_event.list,
11823 		      &phba->sli4_hba.sp_queue_event);
11824 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
11825 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11826 
11827 	return true;
11828 }
11829 
11830 /**
11831  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
11832  * @phba: Pointer to HBA context object.
11833  * @wcqe: Pointer to work-queue completion queue entry.
11834  *
11835  * This routine handles slow-path WQ entry comsumed event by invoking the
11836  * proper WQ release routine to the slow-path WQ.
11837  **/
11838 static void
11839 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
11840 			     struct lpfc_wcqe_release *wcqe)
11841 {
11842 	/* sanity check on queue memory */
11843 	if (unlikely(!phba->sli4_hba.els_wq))
11844 		return;
11845 	/* Check for the slow-path ELS work queue */
11846 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
11847 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
11848 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
11849 	else
11850 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11851 				"2579 Slow-path wqe consume event carries "
11852 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
11853 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
11854 				phba->sli4_hba.els_wq->queue_id);
11855 }
11856 
11857 /**
11858  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
11859  * @phba: Pointer to HBA context object.
11860  * @cq: Pointer to a WQ completion queue.
11861  * @wcqe: Pointer to work-queue completion queue entry.
11862  *
11863  * This routine handles an XRI abort event.
11864  *
11865  * Return: true if work posted to worker thread, otherwise false.
11866  **/
11867 static bool
11868 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
11869 				   struct lpfc_queue *cq,
11870 				   struct sli4_wcqe_xri_aborted *wcqe)
11871 {
11872 	bool workposted = false;
11873 	struct lpfc_cq_event *cq_event;
11874 	unsigned long iflags;
11875 
11876 	/* Allocate a new internal CQ_EVENT entry */
11877 	cq_event = lpfc_sli4_cq_event_alloc(phba);
11878 	if (!cq_event) {
11879 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11880 				"0602 Failed to allocate CQ_EVENT entry\n");
11881 		return false;
11882 	}
11883 
11884 	/* Move the CQE into the proper xri abort event list */
11885 	memcpy(&cq_event->cqe, wcqe, sizeof(struct sli4_wcqe_xri_aborted));
11886 	switch (cq->subtype) {
11887 	case LPFC_FCP:
11888 		spin_lock_irqsave(&phba->hbalock, iflags);
11889 		list_add_tail(&cq_event->list,
11890 			      &phba->sli4_hba.sp_fcp_xri_aborted_work_queue);
11891 		/* Set the fcp xri abort event flag */
11892 		phba->hba_flag |= FCP_XRI_ABORT_EVENT;
11893 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11894 		workposted = true;
11895 		break;
11896 	case LPFC_ELS:
11897 		spin_lock_irqsave(&phba->hbalock, iflags);
11898 		list_add_tail(&cq_event->list,
11899 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
11900 		/* Set the els xri abort event flag */
11901 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
11902 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11903 		workposted = true;
11904 		break;
11905 	default:
11906 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11907 				"0603 Invalid work queue CQE subtype (x%x)\n",
11908 				cq->subtype);
11909 		workposted = false;
11910 		break;
11911 	}
11912 	return workposted;
11913 }
11914 
11915 /**
11916  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
11917  * @phba: Pointer to HBA context object.
11918  * @rcqe: Pointer to receive-queue completion queue entry.
11919  *
11920  * This routine process a receive-queue completion queue entry.
11921  *
11922  * Return: true if work posted to worker thread, otherwise false.
11923  **/
11924 static bool
11925 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
11926 {
11927 	bool workposted = false;
11928 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
11929 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
11930 	struct hbq_dmabuf *dma_buf;
11931 	uint32_t status, rq_id;
11932 	unsigned long iflags;
11933 
11934 	/* sanity check on queue memory */
11935 	if (unlikely(!hrq) || unlikely(!drq))
11936 		return workposted;
11937 
11938 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
11939 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
11940 	else
11941 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
11942 	if (rq_id != hrq->queue_id)
11943 		goto out;
11944 
11945 	status = bf_get(lpfc_rcqe_status, rcqe);
11946 	switch (status) {
11947 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
11948 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11949 				"2537 Receive Frame Truncated!!\n");
11950 		hrq->RQ_buf_trunc++;
11951 	case FC_STATUS_RQ_SUCCESS:
11952 		lpfc_sli4_rq_release(hrq, drq);
11953 		spin_lock_irqsave(&phba->hbalock, iflags);
11954 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
11955 		if (!dma_buf) {
11956 			hrq->RQ_no_buf_found++;
11957 			spin_unlock_irqrestore(&phba->hbalock, iflags);
11958 			goto out;
11959 		}
11960 		hrq->RQ_rcv_buf++;
11961 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
11962 		/* save off the frame for the word thread to process */
11963 		list_add_tail(&dma_buf->cq_event.list,
11964 			      &phba->sli4_hba.sp_queue_event);
11965 		/* Frame received */
11966 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
11967 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11968 		workposted = true;
11969 		break;
11970 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
11971 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
11972 		hrq->RQ_no_posted_buf++;
11973 		/* Post more buffers if possible */
11974 		spin_lock_irqsave(&phba->hbalock, iflags);
11975 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
11976 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11977 		workposted = true;
11978 		break;
11979 	}
11980 out:
11981 	return workposted;
11982 }
11983 
11984 /**
11985  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
11986  * @phba: Pointer to HBA context object.
11987  * @cq: Pointer to the completion queue.
11988  * @wcqe: Pointer to a completion queue entry.
11989  *
11990  * This routine process a slow-path work-queue or receive queue completion queue
11991  * entry.
11992  *
11993  * Return: true if work posted to worker thread, otherwise false.
11994  **/
11995 static bool
11996 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
11997 			 struct lpfc_cqe *cqe)
11998 {
11999 	struct lpfc_cqe cqevt;
12000 	bool workposted = false;
12001 
12002 	/* Copy the work queue CQE and convert endian order if needed */
12003 	lpfc_sli_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
12004 
12005 	/* Check and process for different type of WCQE and dispatch */
12006 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
12007 	case CQE_CODE_COMPL_WQE:
12008 		/* Process the WQ/RQ complete event */
12009 		phba->last_completion_time = jiffies;
12010 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
12011 				(struct lpfc_wcqe_complete *)&cqevt);
12012 		break;
12013 	case CQE_CODE_RELEASE_WQE:
12014 		/* Process the WQ release event */
12015 		lpfc_sli4_sp_handle_rel_wcqe(phba,
12016 				(struct lpfc_wcqe_release *)&cqevt);
12017 		break;
12018 	case CQE_CODE_XRI_ABORTED:
12019 		/* Process the WQ XRI abort event */
12020 		phba->last_completion_time = jiffies;
12021 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
12022 				(struct sli4_wcqe_xri_aborted *)&cqevt);
12023 		break;
12024 	case CQE_CODE_RECEIVE:
12025 	case CQE_CODE_RECEIVE_V1:
12026 		/* Process the RQ event */
12027 		phba->last_completion_time = jiffies;
12028 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
12029 				(struct lpfc_rcqe *)&cqevt);
12030 		break;
12031 	default:
12032 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12033 				"0388 Not a valid WCQE code: x%x\n",
12034 				bf_get(lpfc_cqe_code, &cqevt));
12035 		break;
12036 	}
12037 	return workposted;
12038 }
12039 
12040 /**
12041  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
12042  * @phba: Pointer to HBA context object.
12043  * @eqe: Pointer to fast-path event queue entry.
12044  *
12045  * This routine process a event queue entry from the slow-path event queue.
12046  * It will check the MajorCode and MinorCode to determine this is for a
12047  * completion event on a completion queue, if not, an error shall be logged
12048  * and just return. Otherwise, it will get to the corresponding completion
12049  * queue and process all the entries on that completion queue, rearm the
12050  * completion queue, and then return.
12051  *
12052  **/
12053 static void
12054 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
12055 	struct lpfc_queue *speq)
12056 {
12057 	struct lpfc_queue *cq = NULL, *childq;
12058 	struct lpfc_cqe *cqe;
12059 	bool workposted = false;
12060 	int ecount = 0;
12061 	uint16_t cqid;
12062 
12063 	/* Get the reference to the corresponding CQ */
12064 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
12065 
12066 	list_for_each_entry(childq, &speq->child_list, list) {
12067 		if (childq->queue_id == cqid) {
12068 			cq = childq;
12069 			break;
12070 		}
12071 	}
12072 	if (unlikely(!cq)) {
12073 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
12074 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12075 					"0365 Slow-path CQ identifier "
12076 					"(%d) does not exist\n", cqid);
12077 		return;
12078 	}
12079 
12080 	/* Process all the entries to the CQ */
12081 	switch (cq->type) {
12082 	case LPFC_MCQ:
12083 		while ((cqe = lpfc_sli4_cq_get(cq))) {
12084 			workposted |= lpfc_sli4_sp_handle_mcqe(phba, cqe);
12085 			if (!(++ecount % cq->entry_repost))
12086 				lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12087 			cq->CQ_mbox++;
12088 		}
12089 		break;
12090 	case LPFC_WCQ:
12091 		while ((cqe = lpfc_sli4_cq_get(cq))) {
12092 			if (cq->subtype == LPFC_FCP)
12093 				workposted |= lpfc_sli4_fp_handle_wcqe(phba, cq,
12094 								       cqe);
12095 			else
12096 				workposted |= lpfc_sli4_sp_handle_cqe(phba, cq,
12097 								      cqe);
12098 			if (!(++ecount % cq->entry_repost))
12099 				lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12100 		}
12101 
12102 		/* Track the max number of CQEs processed in 1 EQ */
12103 		if (ecount > cq->CQ_max_cqe)
12104 			cq->CQ_max_cqe = ecount;
12105 		break;
12106 	default:
12107 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12108 				"0370 Invalid completion queue type (%d)\n",
12109 				cq->type);
12110 		return;
12111 	}
12112 
12113 	/* Catch the no cq entry condition, log an error */
12114 	if (unlikely(ecount == 0))
12115 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12116 				"0371 No entry from the CQ: identifier "
12117 				"(x%x), type (%d)\n", cq->queue_id, cq->type);
12118 
12119 	/* In any case, flash and re-arm the RCQ */
12120 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
12121 
12122 	/* wake up worker thread if there are works to be done */
12123 	if (workposted)
12124 		lpfc_worker_wake_up(phba);
12125 }
12126 
12127 /**
12128  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
12129  * @phba: Pointer to HBA context object.
12130  * @cq: Pointer to associated CQ
12131  * @wcqe: Pointer to work-queue completion queue entry.
12132  *
12133  * This routine process a fast-path work queue completion entry from fast-path
12134  * event queue for FCP command response completion.
12135  **/
12136 static void
12137 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12138 			     struct lpfc_wcqe_complete *wcqe)
12139 {
12140 	struct lpfc_sli_ring *pring = cq->pring;
12141 	struct lpfc_iocbq *cmdiocbq;
12142 	struct lpfc_iocbq irspiocbq;
12143 	unsigned long iflags;
12144 
12145 	/* Check for response status */
12146 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
12147 		/* If resource errors reported from HBA, reduce queue
12148 		 * depth of the SCSI device.
12149 		 */
12150 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
12151 		     IOSTAT_LOCAL_REJECT)) &&
12152 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
12153 		     IOERR_NO_RESOURCES))
12154 			phba->lpfc_rampdown_queue_depth(phba);
12155 
12156 		/* Log the error status */
12157 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12158 				"0373 FCP complete error: status=x%x, "
12159 				"hw_status=x%x, total_data_specified=%d, "
12160 				"parameter=x%x, word3=x%x\n",
12161 				bf_get(lpfc_wcqe_c_status, wcqe),
12162 				bf_get(lpfc_wcqe_c_hw_status, wcqe),
12163 				wcqe->total_data_placed, wcqe->parameter,
12164 				wcqe->word3);
12165 	}
12166 
12167 	/* Look up the FCP command IOCB and create pseudo response IOCB */
12168 	spin_lock_irqsave(&pring->ring_lock, iflags);
12169 	pring->stats.iocb_event++;
12170 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
12171 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12172 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
12173 	if (unlikely(!cmdiocbq)) {
12174 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12175 				"0374 FCP complete with no corresponding "
12176 				"cmdiocb: iotag (%d)\n",
12177 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12178 		return;
12179 	}
12180 	if (unlikely(!cmdiocbq->iocb_cmpl)) {
12181 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12182 				"0375 FCP cmdiocb not callback function "
12183 				"iotag: (%d)\n",
12184 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12185 		return;
12186 	}
12187 
12188 	/* Fake the irspiocb and copy necessary response information */
12189 	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
12190 
12191 	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
12192 		spin_lock_irqsave(&phba->hbalock, iflags);
12193 		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
12194 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12195 	}
12196 
12197 	/* Pass the cmd_iocb and the rsp state to the upper layer */
12198 	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
12199 }
12200 
12201 /**
12202  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
12203  * @phba: Pointer to HBA context object.
12204  * @cq: Pointer to completion queue.
12205  * @wcqe: Pointer to work-queue completion queue entry.
12206  *
12207  * This routine handles an fast-path WQ entry comsumed event by invoking the
12208  * proper WQ release routine to the slow-path WQ.
12209  **/
12210 static void
12211 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12212 			     struct lpfc_wcqe_release *wcqe)
12213 {
12214 	struct lpfc_queue *childwq;
12215 	bool wqid_matched = false;
12216 	uint16_t fcp_wqid;
12217 
12218 	/* Check for fast-path FCP work queue release */
12219 	fcp_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
12220 	list_for_each_entry(childwq, &cq->child_list, list) {
12221 		if (childwq->queue_id == fcp_wqid) {
12222 			lpfc_sli4_wq_release(childwq,
12223 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
12224 			wqid_matched = true;
12225 			break;
12226 		}
12227 	}
12228 	/* Report warning log message if no match found */
12229 	if (wqid_matched != true)
12230 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12231 				"2580 Fast-path wqe consume event carries "
12232 				"miss-matched qid: wcqe-qid=x%x\n", fcp_wqid);
12233 }
12234 
12235 /**
12236  * lpfc_sli4_fp_handle_wcqe - Process fast-path work queue completion entry
12237  * @cq: Pointer to the completion queue.
12238  * @eqe: Pointer to fast-path completion queue entry.
12239  *
12240  * This routine process a fast-path work queue completion entry from fast-path
12241  * event queue for FCP command response completion.
12242  **/
12243 static int
12244 lpfc_sli4_fp_handle_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12245 			 struct lpfc_cqe *cqe)
12246 {
12247 	struct lpfc_wcqe_release wcqe;
12248 	bool workposted = false;
12249 
12250 	/* Copy the work queue CQE and convert endian order if needed */
12251 	lpfc_sli_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
12252 
12253 	/* Check and process for different type of WCQE and dispatch */
12254 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
12255 	case CQE_CODE_COMPL_WQE:
12256 		cq->CQ_wq++;
12257 		/* Process the WQ complete event */
12258 		phba->last_completion_time = jiffies;
12259 		lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
12260 				(struct lpfc_wcqe_complete *)&wcqe);
12261 		break;
12262 	case CQE_CODE_RELEASE_WQE:
12263 		cq->CQ_release_wqe++;
12264 		/* Process the WQ release event */
12265 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
12266 				(struct lpfc_wcqe_release *)&wcqe);
12267 		break;
12268 	case CQE_CODE_XRI_ABORTED:
12269 		cq->CQ_xri_aborted++;
12270 		/* Process the WQ XRI abort event */
12271 		phba->last_completion_time = jiffies;
12272 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
12273 				(struct sli4_wcqe_xri_aborted *)&wcqe);
12274 		break;
12275 	default:
12276 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12277 				"0144 Not a valid WCQE code: x%x\n",
12278 				bf_get(lpfc_wcqe_c_code, &wcqe));
12279 		break;
12280 	}
12281 	return workposted;
12282 }
12283 
12284 /**
12285  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
12286  * @phba: Pointer to HBA context object.
12287  * @eqe: Pointer to fast-path event queue entry.
12288  *
12289  * This routine process a event queue entry from the fast-path event queue.
12290  * It will check the MajorCode and MinorCode to determine this is for a
12291  * completion event on a completion queue, if not, an error shall be logged
12292  * and just return. Otherwise, it will get to the corresponding completion
12293  * queue and process all the entries on the completion queue, rearm the
12294  * completion queue, and then return.
12295  **/
12296 static void
12297 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
12298 			uint32_t qidx)
12299 {
12300 	struct lpfc_queue *cq;
12301 	struct lpfc_cqe *cqe;
12302 	bool workposted = false;
12303 	uint16_t cqid;
12304 	int ecount = 0;
12305 
12306 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
12307 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12308 				"0366 Not a valid completion "
12309 				"event: majorcode=x%x, minorcode=x%x\n",
12310 				bf_get_le32(lpfc_eqe_major_code, eqe),
12311 				bf_get_le32(lpfc_eqe_minor_code, eqe));
12312 		return;
12313 	}
12314 
12315 	/* Get the reference to the corresponding CQ */
12316 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
12317 
12318 	/* Check if this is a Slow path event */
12319 	if (unlikely(cqid != phba->sli4_hba.fcp_cq_map[qidx])) {
12320 		lpfc_sli4_sp_handle_eqe(phba, eqe,
12321 			phba->sli4_hba.hba_eq[qidx]);
12322 		return;
12323 	}
12324 
12325 	if (unlikely(!phba->sli4_hba.fcp_cq)) {
12326 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12327 				"3146 Fast-path completion queues "
12328 				"does not exist\n");
12329 		return;
12330 	}
12331 	cq = phba->sli4_hba.fcp_cq[qidx];
12332 	if (unlikely(!cq)) {
12333 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
12334 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12335 					"0367 Fast-path completion queue "
12336 					"(%d) does not exist\n", qidx);
12337 		return;
12338 	}
12339 
12340 	if (unlikely(cqid != cq->queue_id)) {
12341 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12342 				"0368 Miss-matched fast-path completion "
12343 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
12344 				cqid, cq->queue_id);
12345 		return;
12346 	}
12347 
12348 	/* Process all the entries to the CQ */
12349 	while ((cqe = lpfc_sli4_cq_get(cq))) {
12350 		workposted |= lpfc_sli4_fp_handle_wcqe(phba, cq, cqe);
12351 		if (!(++ecount % cq->entry_repost))
12352 			lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12353 	}
12354 
12355 	/* Track the max number of CQEs processed in 1 EQ */
12356 	if (ecount > cq->CQ_max_cqe)
12357 		cq->CQ_max_cqe = ecount;
12358 
12359 	/* Catch the no cq entry condition */
12360 	if (unlikely(ecount == 0))
12361 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12362 				"0369 No entry from fast-path completion "
12363 				"queue fcpcqid=%d\n", cq->queue_id);
12364 
12365 	/* In any case, flash and re-arm the CQ */
12366 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
12367 
12368 	/* wake up worker thread if there are works to be done */
12369 	if (workposted)
12370 		lpfc_worker_wake_up(phba);
12371 }
12372 
12373 static void
12374 lpfc_sli4_eq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
12375 {
12376 	struct lpfc_eqe *eqe;
12377 
12378 	/* walk all the EQ entries and drop on the floor */
12379 	while ((eqe = lpfc_sli4_eq_get(eq)))
12380 		;
12381 
12382 	/* Clear and re-arm the EQ */
12383 	lpfc_sli4_eq_release(eq, LPFC_QUEUE_REARM);
12384 }
12385 
12386 
12387 /**
12388  * lpfc_sli4_fof_handle_eqe - Process a Flash Optimized Fabric event queue
12389  *			     entry
12390  * @phba: Pointer to HBA context object.
12391  * @eqe: Pointer to fast-path event queue entry.
12392  *
12393  * This routine process a event queue entry from the Flash Optimized Fabric
12394  * event queue.  It will check the MajorCode and MinorCode to determine this
12395  * is for a completion event on a completion queue, if not, an error shall be
12396  * logged and just return. Otherwise, it will get to the corresponding
12397  * completion queue and process all the entries on the completion queue, rearm
12398  * the completion queue, and then return.
12399  **/
12400 static void
12401 lpfc_sli4_fof_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe)
12402 {
12403 	struct lpfc_queue *cq;
12404 	struct lpfc_cqe *cqe;
12405 	bool workposted = false;
12406 	uint16_t cqid;
12407 	int ecount = 0;
12408 
12409 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
12410 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12411 				"9147 Not a valid completion "
12412 				"event: majorcode=x%x, minorcode=x%x\n",
12413 				bf_get_le32(lpfc_eqe_major_code, eqe),
12414 				bf_get_le32(lpfc_eqe_minor_code, eqe));
12415 		return;
12416 	}
12417 
12418 	/* Get the reference to the corresponding CQ */
12419 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
12420 
12421 	/* Next check for OAS */
12422 	cq = phba->sli4_hba.oas_cq;
12423 	if (unlikely(!cq)) {
12424 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
12425 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12426 					"9148 OAS completion queue "
12427 					"does not exist\n");
12428 		return;
12429 	}
12430 
12431 	if (unlikely(cqid != cq->queue_id)) {
12432 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12433 				"9149 Miss-matched fast-path compl "
12434 				"queue id: eqcqid=%d, fcpcqid=%d\n",
12435 				cqid, cq->queue_id);
12436 		return;
12437 	}
12438 
12439 	/* Process all the entries to the OAS CQ */
12440 	while ((cqe = lpfc_sli4_cq_get(cq))) {
12441 		workposted |= lpfc_sli4_fp_handle_wcqe(phba, cq, cqe);
12442 		if (!(++ecount % cq->entry_repost))
12443 			lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12444 	}
12445 
12446 	/* Track the max number of CQEs processed in 1 EQ */
12447 	if (ecount > cq->CQ_max_cqe)
12448 		cq->CQ_max_cqe = ecount;
12449 
12450 	/* Catch the no cq entry condition */
12451 	if (unlikely(ecount == 0))
12452 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12453 				"9153 No entry from fast-path completion "
12454 				"queue fcpcqid=%d\n", cq->queue_id);
12455 
12456 	/* In any case, flash and re-arm the CQ */
12457 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
12458 
12459 	/* wake up worker thread if there are works to be done */
12460 	if (workposted)
12461 		lpfc_worker_wake_up(phba);
12462 }
12463 
12464 /**
12465  * lpfc_sli4_fof_intr_handler - HBA interrupt handler to SLI-4 device
12466  * @irq: Interrupt number.
12467  * @dev_id: The device context pointer.
12468  *
12469  * This function is directly called from the PCI layer as an interrupt
12470  * service routine when device with SLI-4 interface spec is enabled with
12471  * MSI-X multi-message interrupt mode and there is a Flash Optimized Fabric
12472  * IOCB ring event in the HBA. However, when the device is enabled with either
12473  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
12474  * device-level interrupt handler. When the PCI slot is in error recovery
12475  * or the HBA is undergoing initialization, the interrupt handler will not
12476  * process the interrupt. The Flash Optimized Fabric ring event are handled in
12477  * the intrrupt context. This function is called without any lock held.
12478  * It gets the hbalock to access and update SLI data structures. Note that,
12479  * the EQ to CQ are one-to-one map such that the EQ index is
12480  * equal to that of CQ index.
12481  *
12482  * This function returns IRQ_HANDLED when interrupt is handled else it
12483  * returns IRQ_NONE.
12484  **/
12485 irqreturn_t
12486 lpfc_sli4_fof_intr_handler(int irq, void *dev_id)
12487 {
12488 	struct lpfc_hba *phba;
12489 	struct lpfc_fcp_eq_hdl *fcp_eq_hdl;
12490 	struct lpfc_queue *eq;
12491 	struct lpfc_eqe *eqe;
12492 	unsigned long iflag;
12493 	int ecount = 0;
12494 	uint32_t eqidx;
12495 
12496 	/* Get the driver's phba structure from the dev_id */
12497 	fcp_eq_hdl = (struct lpfc_fcp_eq_hdl *)dev_id;
12498 	phba = fcp_eq_hdl->phba;
12499 	eqidx = fcp_eq_hdl->idx;
12500 
12501 	if (unlikely(!phba))
12502 		return IRQ_NONE;
12503 
12504 	/* Get to the EQ struct associated with this vector */
12505 	eq = phba->sli4_hba.fof_eq;
12506 	if (unlikely(!eq))
12507 		return IRQ_NONE;
12508 
12509 	/* Check device state for handling interrupt */
12510 	if (unlikely(lpfc_intr_state_check(phba))) {
12511 		eq->EQ_badstate++;
12512 		/* Check again for link_state with lock held */
12513 		spin_lock_irqsave(&phba->hbalock, iflag);
12514 		if (phba->link_state < LPFC_LINK_DOWN)
12515 			/* Flush, clear interrupt, and rearm the EQ */
12516 			lpfc_sli4_eq_flush(phba, eq);
12517 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12518 		return IRQ_NONE;
12519 	}
12520 
12521 	/*
12522 	 * Process all the event on FCP fast-path EQ
12523 	 */
12524 	while ((eqe = lpfc_sli4_eq_get(eq))) {
12525 		lpfc_sli4_fof_handle_eqe(phba, eqe);
12526 		if (!(++ecount % eq->entry_repost))
12527 			lpfc_sli4_eq_release(eq, LPFC_QUEUE_NOARM);
12528 		eq->EQ_processed++;
12529 	}
12530 
12531 	/* Track the max number of EQEs processed in 1 intr */
12532 	if (ecount > eq->EQ_max_eqe)
12533 		eq->EQ_max_eqe = ecount;
12534 
12535 
12536 	if (unlikely(ecount == 0)) {
12537 		eq->EQ_no_entry++;
12538 
12539 		if (phba->intr_type == MSIX)
12540 			/* MSI-X treated interrupt served as no EQ share INT */
12541 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12542 					"9145 MSI-X interrupt with no EQE\n");
12543 		else {
12544 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12545 					"9146 ISR interrupt with no EQE\n");
12546 			/* Non MSI-X treated on interrupt as EQ share INT */
12547 			return IRQ_NONE;
12548 		}
12549 	}
12550 	/* Always clear and re-arm the fast-path EQ */
12551 	lpfc_sli4_eq_release(eq, LPFC_QUEUE_REARM);
12552 	return IRQ_HANDLED;
12553 }
12554 
12555 /**
12556  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
12557  * @irq: Interrupt number.
12558  * @dev_id: The device context pointer.
12559  *
12560  * This function is directly called from the PCI layer as an interrupt
12561  * service routine when device with SLI-4 interface spec is enabled with
12562  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
12563  * ring event in the HBA. However, when the device is enabled with either
12564  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
12565  * device-level interrupt handler. When the PCI slot is in error recovery
12566  * or the HBA is undergoing initialization, the interrupt handler will not
12567  * process the interrupt. The SCSI FCP fast-path ring event are handled in
12568  * the intrrupt context. This function is called without any lock held.
12569  * It gets the hbalock to access and update SLI data structures. Note that,
12570  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
12571  * equal to that of FCP CQ index.
12572  *
12573  * The link attention and ELS ring attention events are handled
12574  * by the worker thread. The interrupt handler signals the worker thread
12575  * and returns for these events. This function is called without any lock
12576  * held. It gets the hbalock to access and update SLI data structures.
12577  *
12578  * This function returns IRQ_HANDLED when interrupt is handled else it
12579  * returns IRQ_NONE.
12580  **/
12581 irqreturn_t
12582 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
12583 {
12584 	struct lpfc_hba *phba;
12585 	struct lpfc_fcp_eq_hdl *fcp_eq_hdl;
12586 	struct lpfc_queue *fpeq;
12587 	struct lpfc_eqe *eqe;
12588 	unsigned long iflag;
12589 	int ecount = 0;
12590 	int fcp_eqidx;
12591 
12592 	/* Get the driver's phba structure from the dev_id */
12593 	fcp_eq_hdl = (struct lpfc_fcp_eq_hdl *)dev_id;
12594 	phba = fcp_eq_hdl->phba;
12595 	fcp_eqidx = fcp_eq_hdl->idx;
12596 
12597 	if (unlikely(!phba))
12598 		return IRQ_NONE;
12599 	if (unlikely(!phba->sli4_hba.hba_eq))
12600 		return IRQ_NONE;
12601 
12602 	/* Get to the EQ struct associated with this vector */
12603 	fpeq = phba->sli4_hba.hba_eq[fcp_eqidx];
12604 	if (unlikely(!fpeq))
12605 		return IRQ_NONE;
12606 
12607 	if (lpfc_fcp_look_ahead) {
12608 		if (atomic_dec_and_test(&fcp_eq_hdl->fcp_eq_in_use))
12609 			lpfc_sli4_eq_clr_intr(fpeq);
12610 		else {
12611 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12612 			return IRQ_NONE;
12613 		}
12614 	}
12615 
12616 	/* Check device state for handling interrupt */
12617 	if (unlikely(lpfc_intr_state_check(phba))) {
12618 		fpeq->EQ_badstate++;
12619 		/* Check again for link_state with lock held */
12620 		spin_lock_irqsave(&phba->hbalock, iflag);
12621 		if (phba->link_state < LPFC_LINK_DOWN)
12622 			/* Flush, clear interrupt, and rearm the EQ */
12623 			lpfc_sli4_eq_flush(phba, fpeq);
12624 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12625 		if (lpfc_fcp_look_ahead)
12626 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12627 		return IRQ_NONE;
12628 	}
12629 
12630 	/*
12631 	 * Process all the event on FCP fast-path EQ
12632 	 */
12633 	while ((eqe = lpfc_sli4_eq_get(fpeq))) {
12634 		if (eqe == NULL)
12635 			break;
12636 
12637 		lpfc_sli4_hba_handle_eqe(phba, eqe, fcp_eqidx);
12638 		if (!(++ecount % fpeq->entry_repost))
12639 			lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_NOARM);
12640 		fpeq->EQ_processed++;
12641 	}
12642 
12643 	/* Track the max number of EQEs processed in 1 intr */
12644 	if (ecount > fpeq->EQ_max_eqe)
12645 		fpeq->EQ_max_eqe = ecount;
12646 
12647 	/* Always clear and re-arm the fast-path EQ */
12648 	lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_REARM);
12649 
12650 	if (unlikely(ecount == 0)) {
12651 		fpeq->EQ_no_entry++;
12652 
12653 		if (lpfc_fcp_look_ahead) {
12654 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12655 			return IRQ_NONE;
12656 		}
12657 
12658 		if (phba->intr_type == MSIX)
12659 			/* MSI-X treated interrupt served as no EQ share INT */
12660 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12661 					"0358 MSI-X interrupt with no EQE\n");
12662 		else
12663 			/* Non MSI-X treated on interrupt as EQ share INT */
12664 			return IRQ_NONE;
12665 	}
12666 
12667 	if (lpfc_fcp_look_ahead)
12668 		atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12669 	return IRQ_HANDLED;
12670 } /* lpfc_sli4_fp_intr_handler */
12671 
12672 /**
12673  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
12674  * @irq: Interrupt number.
12675  * @dev_id: The device context pointer.
12676  *
12677  * This function is the device-level interrupt handler to device with SLI-4
12678  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
12679  * interrupt mode is enabled and there is an event in the HBA which requires
12680  * driver attention. This function invokes the slow-path interrupt attention
12681  * handling function and fast-path interrupt attention handling function in
12682  * turn to process the relevant HBA attention events. This function is called
12683  * without any lock held. It gets the hbalock to access and update SLI data
12684  * structures.
12685  *
12686  * This function returns IRQ_HANDLED when interrupt is handled, else it
12687  * returns IRQ_NONE.
12688  **/
12689 irqreturn_t
12690 lpfc_sli4_intr_handler(int irq, void *dev_id)
12691 {
12692 	struct lpfc_hba  *phba;
12693 	irqreturn_t hba_irq_rc;
12694 	bool hba_handled = false;
12695 	int fcp_eqidx;
12696 
12697 	/* Get the driver's phba structure from the dev_id */
12698 	phba = (struct lpfc_hba *)dev_id;
12699 
12700 	if (unlikely(!phba))
12701 		return IRQ_NONE;
12702 
12703 	/*
12704 	 * Invoke fast-path host attention interrupt handling as appropriate.
12705 	 */
12706 	for (fcp_eqidx = 0; fcp_eqidx < phba->cfg_fcp_io_channel; fcp_eqidx++) {
12707 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
12708 					&phba->sli4_hba.fcp_eq_hdl[fcp_eqidx]);
12709 		if (hba_irq_rc == IRQ_HANDLED)
12710 			hba_handled |= true;
12711 	}
12712 
12713 	if (phba->cfg_fof) {
12714 		hba_irq_rc = lpfc_sli4_fof_intr_handler(irq,
12715 					&phba->sli4_hba.fcp_eq_hdl[0]);
12716 		if (hba_irq_rc == IRQ_HANDLED)
12717 			hba_handled |= true;
12718 	}
12719 
12720 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
12721 } /* lpfc_sli4_intr_handler */
12722 
12723 /**
12724  * lpfc_sli4_queue_free - free a queue structure and associated memory
12725  * @queue: The queue structure to free.
12726  *
12727  * This function frees a queue structure and the DMAable memory used for
12728  * the host resident queue. This function must be called after destroying the
12729  * queue on the HBA.
12730  **/
12731 void
12732 lpfc_sli4_queue_free(struct lpfc_queue *queue)
12733 {
12734 	struct lpfc_dmabuf *dmabuf;
12735 
12736 	if (!queue)
12737 		return;
12738 
12739 	while (!list_empty(&queue->page_list)) {
12740 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
12741 				 list);
12742 		dma_free_coherent(&queue->phba->pcidev->dev, SLI4_PAGE_SIZE,
12743 				  dmabuf->virt, dmabuf->phys);
12744 		kfree(dmabuf);
12745 	}
12746 	kfree(queue);
12747 	return;
12748 }
12749 
12750 /**
12751  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
12752  * @phba: The HBA that this queue is being created on.
12753  * @entry_size: The size of each queue entry for this queue.
12754  * @entry count: The number of entries that this queue will handle.
12755  *
12756  * This function allocates a queue structure and the DMAable memory used for
12757  * the host resident queue. This function must be called before creating the
12758  * queue on the HBA.
12759  **/
12760 struct lpfc_queue *
12761 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t entry_size,
12762 		      uint32_t entry_count)
12763 {
12764 	struct lpfc_queue *queue;
12765 	struct lpfc_dmabuf *dmabuf;
12766 	int x, total_qe_count;
12767 	void *dma_pointer;
12768 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
12769 
12770 	if (!phba->sli4_hba.pc_sli4_params.supported)
12771 		hw_page_size = SLI4_PAGE_SIZE;
12772 
12773 	queue = kzalloc(sizeof(struct lpfc_queue) +
12774 			(sizeof(union sli4_qe) * entry_count), GFP_KERNEL);
12775 	if (!queue)
12776 		return NULL;
12777 	queue->page_count = (ALIGN(entry_size * entry_count,
12778 			hw_page_size))/hw_page_size;
12779 	INIT_LIST_HEAD(&queue->list);
12780 	INIT_LIST_HEAD(&queue->page_list);
12781 	INIT_LIST_HEAD(&queue->child_list);
12782 	for (x = 0, total_qe_count = 0; x < queue->page_count; x++) {
12783 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
12784 		if (!dmabuf)
12785 			goto out_fail;
12786 		dmabuf->virt = dma_zalloc_coherent(&phba->pcidev->dev,
12787 						   hw_page_size, &dmabuf->phys,
12788 						   GFP_KERNEL);
12789 		if (!dmabuf->virt) {
12790 			kfree(dmabuf);
12791 			goto out_fail;
12792 		}
12793 		dmabuf->buffer_tag = x;
12794 		list_add_tail(&dmabuf->list, &queue->page_list);
12795 		/* initialize queue's entry array */
12796 		dma_pointer = dmabuf->virt;
12797 		for (; total_qe_count < entry_count &&
12798 		     dma_pointer < (hw_page_size + dmabuf->virt);
12799 		     total_qe_count++, dma_pointer += entry_size) {
12800 			queue->qe[total_qe_count].address = dma_pointer;
12801 		}
12802 	}
12803 	queue->entry_size = entry_size;
12804 	queue->entry_count = entry_count;
12805 
12806 	/*
12807 	 * entry_repost is calculated based on the number of entries in the
12808 	 * queue. This works out except for RQs. If buffers are NOT initially
12809 	 * posted for every RQE, entry_repost should be adjusted accordingly.
12810 	 */
12811 	queue->entry_repost = (entry_count >> 3);
12812 	if (queue->entry_repost < LPFC_QUEUE_MIN_REPOST)
12813 		queue->entry_repost = LPFC_QUEUE_MIN_REPOST;
12814 	queue->phba = phba;
12815 
12816 	return queue;
12817 out_fail:
12818 	lpfc_sli4_queue_free(queue);
12819 	return NULL;
12820 }
12821 
12822 /**
12823  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
12824  * @phba: HBA structure that indicates port to create a queue on.
12825  * @pci_barset: PCI BAR set flag.
12826  *
12827  * This function shall perform iomap of the specified PCI BAR address to host
12828  * memory address if not already done so and return it. The returned host
12829  * memory address can be NULL.
12830  */
12831 static void __iomem *
12832 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
12833 {
12834 	struct pci_dev *pdev;
12835 
12836 	if (!phba->pcidev)
12837 		return NULL;
12838 	else
12839 		pdev = phba->pcidev;
12840 
12841 	switch (pci_barset) {
12842 	case WQ_PCI_BAR_0_AND_1:
12843 		return phba->pci_bar0_memmap_p;
12844 	case WQ_PCI_BAR_2_AND_3:
12845 		return phba->pci_bar2_memmap_p;
12846 	case WQ_PCI_BAR_4_AND_5:
12847 		return phba->pci_bar4_memmap_p;
12848 	default:
12849 		break;
12850 	}
12851 	return NULL;
12852 }
12853 
12854 /**
12855  * lpfc_modify_fcp_eq_delay - Modify Delay Multiplier on FCP EQs
12856  * @phba: HBA structure that indicates port to create a queue on.
12857  * @startq: The starting FCP EQ to modify
12858  *
12859  * This function sends an MODIFY_EQ_DELAY mailbox command to the HBA.
12860  *
12861  * The @phba struct is used to send mailbox command to HBA. The @startq
12862  * is used to get the starting FCP EQ to change.
12863  * This function is asynchronous and will wait for the mailbox
12864  * command to finish before continuing.
12865  *
12866  * On success this function will return a zero. If unable to allocate enough
12867  * memory this function will return -ENOMEM. If the queue create mailbox command
12868  * fails this function will return -ENXIO.
12869  **/
12870 int
12871 lpfc_modify_fcp_eq_delay(struct lpfc_hba *phba, uint32_t startq)
12872 {
12873 	struct lpfc_mbx_modify_eq_delay *eq_delay;
12874 	LPFC_MBOXQ_t *mbox;
12875 	struct lpfc_queue *eq;
12876 	int cnt, rc, length, status = 0;
12877 	uint32_t shdr_status, shdr_add_status;
12878 	uint32_t result;
12879 	int fcp_eqidx;
12880 	union lpfc_sli4_cfg_shdr *shdr;
12881 	uint16_t dmult;
12882 
12883 	if (startq >= phba->cfg_fcp_io_channel)
12884 		return 0;
12885 
12886 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12887 	if (!mbox)
12888 		return -ENOMEM;
12889 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
12890 		  sizeof(struct lpfc_sli4_cfg_mhdr));
12891 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
12892 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
12893 			 length, LPFC_SLI4_MBX_EMBED);
12894 	eq_delay = &mbox->u.mqe.un.eq_delay;
12895 
12896 	/* Calculate delay multiper from maximum interrupt per second */
12897 	result = phba->cfg_fcp_imax / phba->cfg_fcp_io_channel;
12898 	if (result > LPFC_DMULT_CONST)
12899 		dmult = 0;
12900 	else
12901 		dmult = LPFC_DMULT_CONST/result - 1;
12902 
12903 	cnt = 0;
12904 	for (fcp_eqidx = startq; fcp_eqidx < phba->cfg_fcp_io_channel;
12905 	    fcp_eqidx++) {
12906 		eq = phba->sli4_hba.hba_eq[fcp_eqidx];
12907 		if (!eq)
12908 			continue;
12909 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
12910 		eq_delay->u.request.eq[cnt].phase = 0;
12911 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
12912 		cnt++;
12913 		if (cnt >= LPFC_MAX_EQ_DELAY)
12914 			break;
12915 	}
12916 	eq_delay->u.request.num_eq = cnt;
12917 
12918 	mbox->vport = phba->pport;
12919 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
12920 	mbox->context1 = NULL;
12921 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
12922 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
12923 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
12924 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
12925 	if (shdr_status || shdr_add_status || rc) {
12926 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12927 				"2512 MODIFY_EQ_DELAY mailbox failed with "
12928 				"status x%x add_status x%x, mbx status x%x\n",
12929 				shdr_status, shdr_add_status, rc);
12930 		status = -ENXIO;
12931 	}
12932 	mempool_free(mbox, phba->mbox_mem_pool);
12933 	return status;
12934 }
12935 
12936 /**
12937  * lpfc_eq_create - Create an Event Queue on the HBA
12938  * @phba: HBA structure that indicates port to create a queue on.
12939  * @eq: The queue structure to use to create the event queue.
12940  * @imax: The maximum interrupt per second limit.
12941  *
12942  * This function creates an event queue, as detailed in @eq, on a port,
12943  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
12944  *
12945  * The @phba struct is used to send mailbox command to HBA. The @eq struct
12946  * is used to get the entry count and entry size that are necessary to
12947  * determine the number of pages to allocate and use for this queue. This
12948  * function will send the EQ_CREATE mailbox command to the HBA to setup the
12949  * event queue. This function is asynchronous and will wait for the mailbox
12950  * command to finish before continuing.
12951  *
12952  * On success this function will return a zero. If unable to allocate enough
12953  * memory this function will return -ENOMEM. If the queue create mailbox command
12954  * fails this function will return -ENXIO.
12955  **/
12956 int
12957 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
12958 {
12959 	struct lpfc_mbx_eq_create *eq_create;
12960 	LPFC_MBOXQ_t *mbox;
12961 	int rc, length, status = 0;
12962 	struct lpfc_dmabuf *dmabuf;
12963 	uint32_t shdr_status, shdr_add_status;
12964 	union lpfc_sli4_cfg_shdr *shdr;
12965 	uint16_t dmult;
12966 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
12967 
12968 	/* sanity check on queue memory */
12969 	if (!eq)
12970 		return -ENODEV;
12971 	if (!phba->sli4_hba.pc_sli4_params.supported)
12972 		hw_page_size = SLI4_PAGE_SIZE;
12973 
12974 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12975 	if (!mbox)
12976 		return -ENOMEM;
12977 	length = (sizeof(struct lpfc_mbx_eq_create) -
12978 		  sizeof(struct lpfc_sli4_cfg_mhdr));
12979 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
12980 			 LPFC_MBOX_OPCODE_EQ_CREATE,
12981 			 length, LPFC_SLI4_MBX_EMBED);
12982 	eq_create = &mbox->u.mqe.un.eq_create;
12983 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
12984 	       eq->page_count);
12985 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
12986 	       LPFC_EQE_SIZE);
12987 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
12988 	/* don't setup delay multiplier using EQ_CREATE */
12989 	dmult = 0;
12990 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
12991 	       dmult);
12992 	switch (eq->entry_count) {
12993 	default:
12994 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12995 				"0360 Unsupported EQ count. (%d)\n",
12996 				eq->entry_count);
12997 		if (eq->entry_count < 256)
12998 			return -EINVAL;
12999 		/* otherwise default to smallest count (drop through) */
13000 	case 256:
13001 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13002 		       LPFC_EQ_CNT_256);
13003 		break;
13004 	case 512:
13005 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13006 		       LPFC_EQ_CNT_512);
13007 		break;
13008 	case 1024:
13009 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13010 		       LPFC_EQ_CNT_1024);
13011 		break;
13012 	case 2048:
13013 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13014 		       LPFC_EQ_CNT_2048);
13015 		break;
13016 	case 4096:
13017 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13018 		       LPFC_EQ_CNT_4096);
13019 		break;
13020 	}
13021 	list_for_each_entry(dmabuf, &eq->page_list, list) {
13022 		memset(dmabuf->virt, 0, hw_page_size);
13023 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13024 					putPaddrLow(dmabuf->phys);
13025 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13026 					putPaddrHigh(dmabuf->phys);
13027 	}
13028 	mbox->vport = phba->pport;
13029 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13030 	mbox->context1 = NULL;
13031 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13032 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
13033 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13034 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13035 	if (shdr_status || shdr_add_status || rc) {
13036 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13037 				"2500 EQ_CREATE mailbox failed with "
13038 				"status x%x add_status x%x, mbx status x%x\n",
13039 				shdr_status, shdr_add_status, rc);
13040 		status = -ENXIO;
13041 	}
13042 	eq->type = LPFC_EQ;
13043 	eq->subtype = LPFC_NONE;
13044 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
13045 	if (eq->queue_id == 0xFFFF)
13046 		status = -ENXIO;
13047 	eq->host_index = 0;
13048 	eq->hba_index = 0;
13049 
13050 	mempool_free(mbox, phba->mbox_mem_pool);
13051 	return status;
13052 }
13053 
13054 /**
13055  * lpfc_cq_create - Create a Completion Queue on the HBA
13056  * @phba: HBA structure that indicates port to create a queue on.
13057  * @cq: The queue structure to use to create the completion queue.
13058  * @eq: The event queue to bind this completion queue to.
13059  *
13060  * This function creates a completion queue, as detailed in @wq, on a port,
13061  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
13062  *
13063  * The @phba struct is used to send mailbox command to HBA. The @cq struct
13064  * is used to get the entry count and entry size that are necessary to
13065  * determine the number of pages to allocate and use for this queue. The @eq
13066  * is used to indicate which event queue to bind this completion queue to. This
13067  * function will send the CQ_CREATE mailbox command to the HBA to setup the
13068  * completion queue. This function is asynchronous and will wait for the mailbox
13069  * command to finish before continuing.
13070  *
13071  * On success this function will return a zero. If unable to allocate enough
13072  * memory this function will return -ENOMEM. If the queue create mailbox command
13073  * fails this function will return -ENXIO.
13074  **/
13075 int
13076 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
13077 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
13078 {
13079 	struct lpfc_mbx_cq_create *cq_create;
13080 	struct lpfc_dmabuf *dmabuf;
13081 	LPFC_MBOXQ_t *mbox;
13082 	int rc, length, status = 0;
13083 	uint32_t shdr_status, shdr_add_status;
13084 	union lpfc_sli4_cfg_shdr *shdr;
13085 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13086 
13087 	/* sanity check on queue memory */
13088 	if (!cq || !eq)
13089 		return -ENODEV;
13090 	if (!phba->sli4_hba.pc_sli4_params.supported)
13091 		hw_page_size = SLI4_PAGE_SIZE;
13092 
13093 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13094 	if (!mbox)
13095 		return -ENOMEM;
13096 	length = (sizeof(struct lpfc_mbx_cq_create) -
13097 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13098 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13099 			 LPFC_MBOX_OPCODE_CQ_CREATE,
13100 			 length, LPFC_SLI4_MBX_EMBED);
13101 	cq_create = &mbox->u.mqe.un.cq_create;
13102 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
13103 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
13104 		    cq->page_count);
13105 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
13106 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
13107 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13108 	       phba->sli4_hba.pc_sli4_params.cqv);
13109 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
13110 		/* FW only supports 1. Should be PAGE_SIZE/SLI4_PAGE_SIZE */
13111 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request, 1);
13112 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
13113 		       eq->queue_id);
13114 	} else {
13115 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
13116 		       eq->queue_id);
13117 	}
13118 	switch (cq->entry_count) {
13119 	default:
13120 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13121 				"0361 Unsupported CQ count. (%d)\n",
13122 				cq->entry_count);
13123 		if (cq->entry_count < 256) {
13124 			status = -EINVAL;
13125 			goto out;
13126 		}
13127 		/* otherwise default to smallest count (drop through) */
13128 	case 256:
13129 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
13130 		       LPFC_CQ_CNT_256);
13131 		break;
13132 	case 512:
13133 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
13134 		       LPFC_CQ_CNT_512);
13135 		break;
13136 	case 1024:
13137 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
13138 		       LPFC_CQ_CNT_1024);
13139 		break;
13140 	}
13141 	list_for_each_entry(dmabuf, &cq->page_list, list) {
13142 		memset(dmabuf->virt, 0, hw_page_size);
13143 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13144 					putPaddrLow(dmabuf->phys);
13145 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13146 					putPaddrHigh(dmabuf->phys);
13147 	}
13148 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13149 
13150 	/* The IOCTL status is embedded in the mailbox subheader. */
13151 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13152 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13153 	if (shdr_status || shdr_add_status || rc) {
13154 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13155 				"2501 CQ_CREATE mailbox failed with "
13156 				"status x%x add_status x%x, mbx status x%x\n",
13157 				shdr_status, shdr_add_status, rc);
13158 		status = -ENXIO;
13159 		goto out;
13160 	}
13161 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
13162 	if (cq->queue_id == 0xFFFF) {
13163 		status = -ENXIO;
13164 		goto out;
13165 	}
13166 	/* link the cq onto the parent eq child list */
13167 	list_add_tail(&cq->list, &eq->child_list);
13168 	/* Set up completion queue's type and subtype */
13169 	cq->type = type;
13170 	cq->subtype = subtype;
13171 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
13172 	cq->assoc_qid = eq->queue_id;
13173 	cq->host_index = 0;
13174 	cq->hba_index = 0;
13175 
13176 out:
13177 	mempool_free(mbox, phba->mbox_mem_pool);
13178 	return status;
13179 }
13180 
13181 /**
13182  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
13183  * @phba: HBA structure that indicates port to create a queue on.
13184  * @mq: The queue structure to use to create the mailbox queue.
13185  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
13186  * @cq: The completion queue to associate with this cq.
13187  *
13188  * This function provides failback (fb) functionality when the
13189  * mq_create_ext fails on older FW generations.  It's purpose is identical
13190  * to mq_create_ext otherwise.
13191  *
13192  * This routine cannot fail as all attributes were previously accessed and
13193  * initialized in mq_create_ext.
13194  **/
13195 static void
13196 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
13197 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
13198 {
13199 	struct lpfc_mbx_mq_create *mq_create;
13200 	struct lpfc_dmabuf *dmabuf;
13201 	int length;
13202 
13203 	length = (sizeof(struct lpfc_mbx_mq_create) -
13204 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13205 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13206 			 LPFC_MBOX_OPCODE_MQ_CREATE,
13207 			 length, LPFC_SLI4_MBX_EMBED);
13208 	mq_create = &mbox->u.mqe.un.mq_create;
13209 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
13210 	       mq->page_count);
13211 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
13212 	       cq->queue_id);
13213 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
13214 	switch (mq->entry_count) {
13215 	case 16:
13216 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13217 		       LPFC_MQ_RING_SIZE_16);
13218 		break;
13219 	case 32:
13220 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13221 		       LPFC_MQ_RING_SIZE_32);
13222 		break;
13223 	case 64:
13224 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13225 		       LPFC_MQ_RING_SIZE_64);
13226 		break;
13227 	case 128:
13228 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13229 		       LPFC_MQ_RING_SIZE_128);
13230 		break;
13231 	}
13232 	list_for_each_entry(dmabuf, &mq->page_list, list) {
13233 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13234 			putPaddrLow(dmabuf->phys);
13235 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13236 			putPaddrHigh(dmabuf->phys);
13237 	}
13238 }
13239 
13240 /**
13241  * lpfc_mq_create - Create a mailbox Queue on the HBA
13242  * @phba: HBA structure that indicates port to create a queue on.
13243  * @mq: The queue structure to use to create the mailbox queue.
13244  * @cq: The completion queue to associate with this cq.
13245  * @subtype: The queue's subtype.
13246  *
13247  * This function creates a mailbox queue, as detailed in @mq, on a port,
13248  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
13249  *
13250  * The @phba struct is used to send mailbox command to HBA. The @cq struct
13251  * is used to get the entry count and entry size that are necessary to
13252  * determine the number of pages to allocate and use for this queue. This
13253  * function will send the MQ_CREATE mailbox command to the HBA to setup the
13254  * mailbox queue. This function is asynchronous and will wait for the mailbox
13255  * command to finish before continuing.
13256  *
13257  * On success this function will return a zero. If unable to allocate enough
13258  * memory this function will return -ENOMEM. If the queue create mailbox command
13259  * fails this function will return -ENXIO.
13260  **/
13261 int32_t
13262 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
13263 	       struct lpfc_queue *cq, uint32_t subtype)
13264 {
13265 	struct lpfc_mbx_mq_create *mq_create;
13266 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
13267 	struct lpfc_dmabuf *dmabuf;
13268 	LPFC_MBOXQ_t *mbox;
13269 	int rc, length, status = 0;
13270 	uint32_t shdr_status, shdr_add_status;
13271 	union lpfc_sli4_cfg_shdr *shdr;
13272 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13273 
13274 	/* sanity check on queue memory */
13275 	if (!mq || !cq)
13276 		return -ENODEV;
13277 	if (!phba->sli4_hba.pc_sli4_params.supported)
13278 		hw_page_size = SLI4_PAGE_SIZE;
13279 
13280 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13281 	if (!mbox)
13282 		return -ENOMEM;
13283 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
13284 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13285 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13286 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
13287 			 length, LPFC_SLI4_MBX_EMBED);
13288 
13289 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
13290 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
13291 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
13292 	       &mq_create_ext->u.request, mq->page_count);
13293 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
13294 	       &mq_create_ext->u.request, 1);
13295 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
13296 	       &mq_create_ext->u.request, 1);
13297 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
13298 	       &mq_create_ext->u.request, 1);
13299 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
13300 	       &mq_create_ext->u.request, 1);
13301 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
13302 	       &mq_create_ext->u.request, 1);
13303 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
13304 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13305 	       phba->sli4_hba.pc_sli4_params.mqv);
13306 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
13307 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
13308 		       cq->queue_id);
13309 	else
13310 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
13311 		       cq->queue_id);
13312 	switch (mq->entry_count) {
13313 	default:
13314 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13315 				"0362 Unsupported MQ count. (%d)\n",
13316 				mq->entry_count);
13317 		if (mq->entry_count < 16) {
13318 			status = -EINVAL;
13319 			goto out;
13320 		}
13321 		/* otherwise default to smallest count (drop through) */
13322 	case 16:
13323 		bf_set(lpfc_mq_context_ring_size,
13324 		       &mq_create_ext->u.request.context,
13325 		       LPFC_MQ_RING_SIZE_16);
13326 		break;
13327 	case 32:
13328 		bf_set(lpfc_mq_context_ring_size,
13329 		       &mq_create_ext->u.request.context,
13330 		       LPFC_MQ_RING_SIZE_32);
13331 		break;
13332 	case 64:
13333 		bf_set(lpfc_mq_context_ring_size,
13334 		       &mq_create_ext->u.request.context,
13335 		       LPFC_MQ_RING_SIZE_64);
13336 		break;
13337 	case 128:
13338 		bf_set(lpfc_mq_context_ring_size,
13339 		       &mq_create_ext->u.request.context,
13340 		       LPFC_MQ_RING_SIZE_128);
13341 		break;
13342 	}
13343 	list_for_each_entry(dmabuf, &mq->page_list, list) {
13344 		memset(dmabuf->virt, 0, hw_page_size);
13345 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
13346 					putPaddrLow(dmabuf->phys);
13347 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
13348 					putPaddrHigh(dmabuf->phys);
13349 	}
13350 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13351 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
13352 			      &mq_create_ext->u.response);
13353 	if (rc != MBX_SUCCESS) {
13354 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13355 				"2795 MQ_CREATE_EXT failed with "
13356 				"status x%x. Failback to MQ_CREATE.\n",
13357 				rc);
13358 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
13359 		mq_create = &mbox->u.mqe.un.mq_create;
13360 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13361 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
13362 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
13363 				      &mq_create->u.response);
13364 	}
13365 
13366 	/* The IOCTL status is embedded in the mailbox subheader. */
13367 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13368 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13369 	if (shdr_status || shdr_add_status || rc) {
13370 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13371 				"2502 MQ_CREATE mailbox failed with "
13372 				"status x%x add_status x%x, mbx status x%x\n",
13373 				shdr_status, shdr_add_status, rc);
13374 		status = -ENXIO;
13375 		goto out;
13376 	}
13377 	if (mq->queue_id == 0xFFFF) {
13378 		status = -ENXIO;
13379 		goto out;
13380 	}
13381 	mq->type = LPFC_MQ;
13382 	mq->assoc_qid = cq->queue_id;
13383 	mq->subtype = subtype;
13384 	mq->host_index = 0;
13385 	mq->hba_index = 0;
13386 
13387 	/* link the mq onto the parent cq child list */
13388 	list_add_tail(&mq->list, &cq->child_list);
13389 out:
13390 	mempool_free(mbox, phba->mbox_mem_pool);
13391 	return status;
13392 }
13393 
13394 /**
13395  * lpfc_wq_create - Create a Work Queue on the HBA
13396  * @phba: HBA structure that indicates port to create a queue on.
13397  * @wq: The queue structure to use to create the work queue.
13398  * @cq: The completion queue to bind this work queue to.
13399  * @subtype: The subtype of the work queue indicating its functionality.
13400  *
13401  * This function creates a work queue, as detailed in @wq, on a port, described
13402  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
13403  *
13404  * The @phba struct is used to send mailbox command to HBA. The @wq struct
13405  * is used to get the entry count and entry size that are necessary to
13406  * determine the number of pages to allocate and use for this queue. The @cq
13407  * is used to indicate which completion queue to bind this work queue to. This
13408  * function will send the WQ_CREATE mailbox command to the HBA to setup the
13409  * work queue. This function is asynchronous and will wait for the mailbox
13410  * command to finish before continuing.
13411  *
13412  * On success this function will return a zero. If unable to allocate enough
13413  * memory this function will return -ENOMEM. If the queue create mailbox command
13414  * fails this function will return -ENXIO.
13415  **/
13416 int
13417 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
13418 	       struct lpfc_queue *cq, uint32_t subtype)
13419 {
13420 	struct lpfc_mbx_wq_create *wq_create;
13421 	struct lpfc_dmabuf *dmabuf;
13422 	LPFC_MBOXQ_t *mbox;
13423 	int rc, length, status = 0;
13424 	uint32_t shdr_status, shdr_add_status;
13425 	union lpfc_sli4_cfg_shdr *shdr;
13426 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13427 	struct dma_address *page;
13428 	void __iomem *bar_memmap_p;
13429 	uint32_t db_offset;
13430 	uint16_t pci_barset;
13431 
13432 	/* sanity check on queue memory */
13433 	if (!wq || !cq)
13434 		return -ENODEV;
13435 	if (!phba->sli4_hba.pc_sli4_params.supported)
13436 		hw_page_size = SLI4_PAGE_SIZE;
13437 
13438 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13439 	if (!mbox)
13440 		return -ENOMEM;
13441 	length = (sizeof(struct lpfc_mbx_wq_create) -
13442 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13443 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
13444 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
13445 			 length, LPFC_SLI4_MBX_EMBED);
13446 	wq_create = &mbox->u.mqe.un.wq_create;
13447 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
13448 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
13449 		    wq->page_count);
13450 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
13451 		    cq->queue_id);
13452 
13453 	/* wqv is the earliest version supported, NOT the latest */
13454 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13455 	       phba->sli4_hba.pc_sli4_params.wqv);
13456 
13457 	switch (phba->sli4_hba.pc_sli4_params.wqv) {
13458 	case LPFC_Q_CREATE_VERSION_0:
13459 		switch (wq->entry_size) {
13460 		default:
13461 		case 64:
13462 			/* Nothing to do, version 0 ONLY supports 64 byte */
13463 			page = wq_create->u.request.page;
13464 			break;
13465 		case 128:
13466 			if (!(phba->sli4_hba.pc_sli4_params.wqsize &
13467 			    LPFC_WQ_SZ128_SUPPORT)) {
13468 				status = -ERANGE;
13469 				goto out;
13470 			}
13471 			/* If we get here the HBA MUST also support V1 and
13472 			 * we MUST use it
13473 			 */
13474 			bf_set(lpfc_mbox_hdr_version, &shdr->request,
13475 			       LPFC_Q_CREATE_VERSION_1);
13476 
13477 			bf_set(lpfc_mbx_wq_create_wqe_count,
13478 			       &wq_create->u.request_1, wq->entry_count);
13479 			bf_set(lpfc_mbx_wq_create_wqe_size,
13480 			       &wq_create->u.request_1,
13481 			       LPFC_WQ_WQE_SIZE_128);
13482 			bf_set(lpfc_mbx_wq_create_page_size,
13483 			       &wq_create->u.request_1,
13484 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
13485 			page = wq_create->u.request_1.page;
13486 			break;
13487 		}
13488 		break;
13489 	case LPFC_Q_CREATE_VERSION_1:
13490 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
13491 		       wq->entry_count);
13492 		switch (wq->entry_size) {
13493 		default:
13494 		case 64:
13495 			bf_set(lpfc_mbx_wq_create_wqe_size,
13496 			       &wq_create->u.request_1,
13497 			       LPFC_WQ_WQE_SIZE_64);
13498 			break;
13499 		case 128:
13500 			if (!(phba->sli4_hba.pc_sli4_params.wqsize &
13501 				LPFC_WQ_SZ128_SUPPORT)) {
13502 				status = -ERANGE;
13503 				goto out;
13504 			}
13505 			bf_set(lpfc_mbx_wq_create_wqe_size,
13506 			       &wq_create->u.request_1,
13507 			       LPFC_WQ_WQE_SIZE_128);
13508 			break;
13509 		}
13510 		bf_set(lpfc_mbx_wq_create_page_size, &wq_create->u.request_1,
13511 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
13512 		page = wq_create->u.request_1.page;
13513 		break;
13514 	default:
13515 		status = -ERANGE;
13516 		goto out;
13517 	}
13518 
13519 	list_for_each_entry(dmabuf, &wq->page_list, list) {
13520 		memset(dmabuf->virt, 0, hw_page_size);
13521 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
13522 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
13523 	}
13524 
13525 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
13526 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
13527 
13528 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13529 	/* The IOCTL status is embedded in the mailbox subheader. */
13530 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13531 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13532 	if (shdr_status || shdr_add_status || rc) {
13533 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13534 				"2503 WQ_CREATE mailbox failed with "
13535 				"status x%x add_status x%x, mbx status x%x\n",
13536 				shdr_status, shdr_add_status, rc);
13537 		status = -ENXIO;
13538 		goto out;
13539 	}
13540 	wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id, &wq_create->u.response);
13541 	if (wq->queue_id == 0xFFFF) {
13542 		status = -ENXIO;
13543 		goto out;
13544 	}
13545 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
13546 		wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
13547 				       &wq_create->u.response);
13548 		if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
13549 		    (wq->db_format != LPFC_DB_RING_FORMAT)) {
13550 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13551 					"3265 WQ[%d] doorbell format not "
13552 					"supported: x%x\n", wq->queue_id,
13553 					wq->db_format);
13554 			status = -EINVAL;
13555 			goto out;
13556 		}
13557 		pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
13558 				    &wq_create->u.response);
13559 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
13560 		if (!bar_memmap_p) {
13561 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13562 					"3263 WQ[%d] failed to memmap pci "
13563 					"barset:x%x\n", wq->queue_id,
13564 					pci_barset);
13565 			status = -ENOMEM;
13566 			goto out;
13567 		}
13568 		db_offset = wq_create->u.response.doorbell_offset;
13569 		if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
13570 		    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
13571 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13572 					"3252 WQ[%d] doorbell offset not "
13573 					"supported: x%x\n", wq->queue_id,
13574 					db_offset);
13575 			status = -EINVAL;
13576 			goto out;
13577 		}
13578 		wq->db_regaddr = bar_memmap_p + db_offset;
13579 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13580 				"3264 WQ[%d]: barset:x%x, offset:x%x, "
13581 				"format:x%x\n", wq->queue_id, pci_barset,
13582 				db_offset, wq->db_format);
13583 	} else {
13584 		wq->db_format = LPFC_DB_LIST_FORMAT;
13585 		wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
13586 	}
13587 	wq->type = LPFC_WQ;
13588 	wq->assoc_qid = cq->queue_id;
13589 	wq->subtype = subtype;
13590 	wq->host_index = 0;
13591 	wq->hba_index = 0;
13592 	wq->entry_repost = LPFC_RELEASE_NOTIFICATION_INTERVAL;
13593 
13594 	/* link the wq onto the parent cq child list */
13595 	list_add_tail(&wq->list, &cq->child_list);
13596 out:
13597 	mempool_free(mbox, phba->mbox_mem_pool);
13598 	return status;
13599 }
13600 
13601 /**
13602  * lpfc_rq_adjust_repost - Adjust entry_repost for an RQ
13603  * @phba: HBA structure that indicates port to create a queue on.
13604  * @rq:   The queue structure to use for the receive queue.
13605  * @qno:  The associated HBQ number
13606  *
13607  *
13608  * For SLI4 we need to adjust the RQ repost value based on
13609  * the number of buffers that are initially posted to the RQ.
13610  */
13611 void
13612 lpfc_rq_adjust_repost(struct lpfc_hba *phba, struct lpfc_queue *rq, int qno)
13613 {
13614 	uint32_t cnt;
13615 
13616 	/* sanity check on queue memory */
13617 	if (!rq)
13618 		return;
13619 	cnt = lpfc_hbq_defs[qno]->entry_count;
13620 
13621 	/* Recalc repost for RQs based on buffers initially posted */
13622 	cnt = (cnt >> 3);
13623 	if (cnt < LPFC_QUEUE_MIN_REPOST)
13624 		cnt = LPFC_QUEUE_MIN_REPOST;
13625 
13626 	rq->entry_repost = cnt;
13627 }
13628 
13629 /**
13630  * lpfc_rq_create - Create a Receive Queue on the HBA
13631  * @phba: HBA structure that indicates port to create a queue on.
13632  * @hrq: The queue structure to use to create the header receive queue.
13633  * @drq: The queue structure to use to create the data receive queue.
13634  * @cq: The completion queue to bind this work queue to.
13635  *
13636  * This function creates a receive buffer queue pair , as detailed in @hrq and
13637  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
13638  * to the HBA.
13639  *
13640  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
13641  * struct is used to get the entry count that is necessary to determine the
13642  * number of pages to use for this queue. The @cq is used to indicate which
13643  * completion queue to bind received buffers that are posted to these queues to.
13644  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
13645  * receive queue pair. This function is asynchronous and will wait for the
13646  * mailbox command to finish before continuing.
13647  *
13648  * On success this function will return a zero. If unable to allocate enough
13649  * memory this function will return -ENOMEM. If the queue create mailbox command
13650  * fails this function will return -ENXIO.
13651  **/
13652 int
13653 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
13654 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
13655 {
13656 	struct lpfc_mbx_rq_create *rq_create;
13657 	struct lpfc_dmabuf *dmabuf;
13658 	LPFC_MBOXQ_t *mbox;
13659 	int rc, length, status = 0;
13660 	uint32_t shdr_status, shdr_add_status;
13661 	union lpfc_sli4_cfg_shdr *shdr;
13662 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13663 	void __iomem *bar_memmap_p;
13664 	uint32_t db_offset;
13665 	uint16_t pci_barset;
13666 
13667 	/* sanity check on queue memory */
13668 	if (!hrq || !drq || !cq)
13669 		return -ENODEV;
13670 	if (!phba->sli4_hba.pc_sli4_params.supported)
13671 		hw_page_size = SLI4_PAGE_SIZE;
13672 
13673 	if (hrq->entry_count != drq->entry_count)
13674 		return -EINVAL;
13675 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13676 	if (!mbox)
13677 		return -ENOMEM;
13678 	length = (sizeof(struct lpfc_mbx_rq_create) -
13679 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13680 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
13681 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
13682 			 length, LPFC_SLI4_MBX_EMBED);
13683 	rq_create = &mbox->u.mqe.un.rq_create;
13684 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
13685 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13686 	       phba->sli4_hba.pc_sli4_params.rqv);
13687 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
13688 		bf_set(lpfc_rq_context_rqe_count_1,
13689 		       &rq_create->u.request.context,
13690 		       hrq->entry_count);
13691 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
13692 		bf_set(lpfc_rq_context_rqe_size,
13693 		       &rq_create->u.request.context,
13694 		       LPFC_RQE_SIZE_8);
13695 		bf_set(lpfc_rq_context_page_size,
13696 		       &rq_create->u.request.context,
13697 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
13698 	} else {
13699 		switch (hrq->entry_count) {
13700 		default:
13701 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13702 					"2535 Unsupported RQ count. (%d)\n",
13703 					hrq->entry_count);
13704 			if (hrq->entry_count < 512) {
13705 				status = -EINVAL;
13706 				goto out;
13707 			}
13708 			/* otherwise default to smallest count (drop through) */
13709 		case 512:
13710 			bf_set(lpfc_rq_context_rqe_count,
13711 			       &rq_create->u.request.context,
13712 			       LPFC_RQ_RING_SIZE_512);
13713 			break;
13714 		case 1024:
13715 			bf_set(lpfc_rq_context_rqe_count,
13716 			       &rq_create->u.request.context,
13717 			       LPFC_RQ_RING_SIZE_1024);
13718 			break;
13719 		case 2048:
13720 			bf_set(lpfc_rq_context_rqe_count,
13721 			       &rq_create->u.request.context,
13722 			       LPFC_RQ_RING_SIZE_2048);
13723 			break;
13724 		case 4096:
13725 			bf_set(lpfc_rq_context_rqe_count,
13726 			       &rq_create->u.request.context,
13727 			       LPFC_RQ_RING_SIZE_4096);
13728 			break;
13729 		}
13730 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
13731 		       LPFC_HDR_BUF_SIZE);
13732 	}
13733 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
13734 	       cq->queue_id);
13735 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
13736 	       hrq->page_count);
13737 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
13738 		memset(dmabuf->virt, 0, hw_page_size);
13739 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13740 					putPaddrLow(dmabuf->phys);
13741 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13742 					putPaddrHigh(dmabuf->phys);
13743 	}
13744 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
13745 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
13746 
13747 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13748 	/* The IOCTL status is embedded in the mailbox subheader. */
13749 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13750 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13751 	if (shdr_status || shdr_add_status || rc) {
13752 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13753 				"2504 RQ_CREATE mailbox failed with "
13754 				"status x%x add_status x%x, mbx status x%x\n",
13755 				shdr_status, shdr_add_status, rc);
13756 		status = -ENXIO;
13757 		goto out;
13758 	}
13759 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
13760 	if (hrq->queue_id == 0xFFFF) {
13761 		status = -ENXIO;
13762 		goto out;
13763 	}
13764 
13765 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
13766 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
13767 					&rq_create->u.response);
13768 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
13769 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
13770 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13771 					"3262 RQ [%d] doorbell format not "
13772 					"supported: x%x\n", hrq->queue_id,
13773 					hrq->db_format);
13774 			status = -EINVAL;
13775 			goto out;
13776 		}
13777 
13778 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
13779 				    &rq_create->u.response);
13780 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
13781 		if (!bar_memmap_p) {
13782 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13783 					"3269 RQ[%d] failed to memmap pci "
13784 					"barset:x%x\n", hrq->queue_id,
13785 					pci_barset);
13786 			status = -ENOMEM;
13787 			goto out;
13788 		}
13789 
13790 		db_offset = rq_create->u.response.doorbell_offset;
13791 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
13792 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
13793 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13794 					"3270 RQ[%d] doorbell offset not "
13795 					"supported: x%x\n", hrq->queue_id,
13796 					db_offset);
13797 			status = -EINVAL;
13798 			goto out;
13799 		}
13800 		hrq->db_regaddr = bar_memmap_p + db_offset;
13801 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13802 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
13803 				"format:x%x\n", hrq->queue_id, pci_barset,
13804 				db_offset, hrq->db_format);
13805 	} else {
13806 		hrq->db_format = LPFC_DB_RING_FORMAT;
13807 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
13808 	}
13809 	hrq->type = LPFC_HRQ;
13810 	hrq->assoc_qid = cq->queue_id;
13811 	hrq->subtype = subtype;
13812 	hrq->host_index = 0;
13813 	hrq->hba_index = 0;
13814 
13815 	/* now create the data queue */
13816 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
13817 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
13818 			 length, LPFC_SLI4_MBX_EMBED);
13819 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13820 	       phba->sli4_hba.pc_sli4_params.rqv);
13821 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
13822 		bf_set(lpfc_rq_context_rqe_count_1,
13823 		       &rq_create->u.request.context, hrq->entry_count);
13824 		rq_create->u.request.context.buffer_size = LPFC_DATA_BUF_SIZE;
13825 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
13826 		       LPFC_RQE_SIZE_8);
13827 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
13828 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
13829 	} else {
13830 		switch (drq->entry_count) {
13831 		default:
13832 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13833 					"2536 Unsupported RQ count. (%d)\n",
13834 					drq->entry_count);
13835 			if (drq->entry_count < 512) {
13836 				status = -EINVAL;
13837 				goto out;
13838 			}
13839 			/* otherwise default to smallest count (drop through) */
13840 		case 512:
13841 			bf_set(lpfc_rq_context_rqe_count,
13842 			       &rq_create->u.request.context,
13843 			       LPFC_RQ_RING_SIZE_512);
13844 			break;
13845 		case 1024:
13846 			bf_set(lpfc_rq_context_rqe_count,
13847 			       &rq_create->u.request.context,
13848 			       LPFC_RQ_RING_SIZE_1024);
13849 			break;
13850 		case 2048:
13851 			bf_set(lpfc_rq_context_rqe_count,
13852 			       &rq_create->u.request.context,
13853 			       LPFC_RQ_RING_SIZE_2048);
13854 			break;
13855 		case 4096:
13856 			bf_set(lpfc_rq_context_rqe_count,
13857 			       &rq_create->u.request.context,
13858 			       LPFC_RQ_RING_SIZE_4096);
13859 			break;
13860 		}
13861 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
13862 		       LPFC_DATA_BUF_SIZE);
13863 	}
13864 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
13865 	       cq->queue_id);
13866 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
13867 	       drq->page_count);
13868 	list_for_each_entry(dmabuf, &drq->page_list, list) {
13869 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13870 					putPaddrLow(dmabuf->phys);
13871 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13872 					putPaddrHigh(dmabuf->phys);
13873 	}
13874 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
13875 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
13876 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13877 	/* The IOCTL status is embedded in the mailbox subheader. */
13878 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
13879 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13880 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13881 	if (shdr_status || shdr_add_status || rc) {
13882 		status = -ENXIO;
13883 		goto out;
13884 	}
13885 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
13886 	if (drq->queue_id == 0xFFFF) {
13887 		status = -ENXIO;
13888 		goto out;
13889 	}
13890 	drq->type = LPFC_DRQ;
13891 	drq->assoc_qid = cq->queue_id;
13892 	drq->subtype = subtype;
13893 	drq->host_index = 0;
13894 	drq->hba_index = 0;
13895 
13896 	/* link the header and data RQs onto the parent cq child list */
13897 	list_add_tail(&hrq->list, &cq->child_list);
13898 	list_add_tail(&drq->list, &cq->child_list);
13899 
13900 out:
13901 	mempool_free(mbox, phba->mbox_mem_pool);
13902 	return status;
13903 }
13904 
13905 /**
13906  * lpfc_eq_destroy - Destroy an event Queue on the HBA
13907  * @eq: The queue structure associated with the queue to destroy.
13908  *
13909  * This function destroys a queue, as detailed in @eq by sending an mailbox
13910  * command, specific to the type of queue, to the HBA.
13911  *
13912  * The @eq struct is used to get the queue ID of the queue to destroy.
13913  *
13914  * On success this function will return a zero. If the queue destroy mailbox
13915  * command fails this function will return -ENXIO.
13916  **/
13917 int
13918 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
13919 {
13920 	LPFC_MBOXQ_t *mbox;
13921 	int rc, length, status = 0;
13922 	uint32_t shdr_status, shdr_add_status;
13923 	union lpfc_sli4_cfg_shdr *shdr;
13924 
13925 	/* sanity check on queue memory */
13926 	if (!eq)
13927 		return -ENODEV;
13928 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
13929 	if (!mbox)
13930 		return -ENOMEM;
13931 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
13932 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13933 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13934 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
13935 			 length, LPFC_SLI4_MBX_EMBED);
13936 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
13937 	       eq->queue_id);
13938 	mbox->vport = eq->phba->pport;
13939 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13940 
13941 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
13942 	/* The IOCTL status is embedded in the mailbox subheader. */
13943 	shdr = (union lpfc_sli4_cfg_shdr *)
13944 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
13945 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13946 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13947 	if (shdr_status || shdr_add_status || rc) {
13948 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13949 				"2505 EQ_DESTROY mailbox failed with "
13950 				"status x%x add_status x%x, mbx status x%x\n",
13951 				shdr_status, shdr_add_status, rc);
13952 		status = -ENXIO;
13953 	}
13954 
13955 	/* Remove eq from any list */
13956 	list_del_init(&eq->list);
13957 	mempool_free(mbox, eq->phba->mbox_mem_pool);
13958 	return status;
13959 }
13960 
13961 /**
13962  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
13963  * @cq: The queue structure associated with the queue to destroy.
13964  *
13965  * This function destroys a queue, as detailed in @cq by sending an mailbox
13966  * command, specific to the type of queue, to the HBA.
13967  *
13968  * The @cq struct is used to get the queue ID of the queue to destroy.
13969  *
13970  * On success this function will return a zero. If the queue destroy mailbox
13971  * command fails this function will return -ENXIO.
13972  **/
13973 int
13974 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
13975 {
13976 	LPFC_MBOXQ_t *mbox;
13977 	int rc, length, status = 0;
13978 	uint32_t shdr_status, shdr_add_status;
13979 	union lpfc_sli4_cfg_shdr *shdr;
13980 
13981 	/* sanity check on queue memory */
13982 	if (!cq)
13983 		return -ENODEV;
13984 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
13985 	if (!mbox)
13986 		return -ENOMEM;
13987 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
13988 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13989 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13990 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
13991 			 length, LPFC_SLI4_MBX_EMBED);
13992 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
13993 	       cq->queue_id);
13994 	mbox->vport = cq->phba->pport;
13995 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13996 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
13997 	/* The IOCTL status is embedded in the mailbox subheader. */
13998 	shdr = (union lpfc_sli4_cfg_shdr *)
13999 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
14000 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14001 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14002 	if (shdr_status || shdr_add_status || rc) {
14003 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14004 				"2506 CQ_DESTROY mailbox failed with "
14005 				"status x%x add_status x%x, mbx status x%x\n",
14006 				shdr_status, shdr_add_status, rc);
14007 		status = -ENXIO;
14008 	}
14009 	/* Remove cq from any list */
14010 	list_del_init(&cq->list);
14011 	mempool_free(mbox, cq->phba->mbox_mem_pool);
14012 	return status;
14013 }
14014 
14015 /**
14016  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
14017  * @qm: The queue structure associated with the queue to destroy.
14018  *
14019  * This function destroys a queue, as detailed in @mq by sending an mailbox
14020  * command, specific to the type of queue, to the HBA.
14021  *
14022  * The @mq struct is used to get the queue ID of the queue to destroy.
14023  *
14024  * On success this function will return a zero. If the queue destroy mailbox
14025  * command fails this function will return -ENXIO.
14026  **/
14027 int
14028 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
14029 {
14030 	LPFC_MBOXQ_t *mbox;
14031 	int rc, length, status = 0;
14032 	uint32_t shdr_status, shdr_add_status;
14033 	union lpfc_sli4_cfg_shdr *shdr;
14034 
14035 	/* sanity check on queue memory */
14036 	if (!mq)
14037 		return -ENODEV;
14038 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
14039 	if (!mbox)
14040 		return -ENOMEM;
14041 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
14042 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14043 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14044 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
14045 			 length, LPFC_SLI4_MBX_EMBED);
14046 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
14047 	       mq->queue_id);
14048 	mbox->vport = mq->phba->pport;
14049 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14050 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
14051 	/* The IOCTL status is embedded in the mailbox subheader. */
14052 	shdr = (union lpfc_sli4_cfg_shdr *)
14053 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
14054 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14055 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14056 	if (shdr_status || shdr_add_status || rc) {
14057 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14058 				"2507 MQ_DESTROY mailbox failed with "
14059 				"status x%x add_status x%x, mbx status x%x\n",
14060 				shdr_status, shdr_add_status, rc);
14061 		status = -ENXIO;
14062 	}
14063 	/* Remove mq from any list */
14064 	list_del_init(&mq->list);
14065 	mempool_free(mbox, mq->phba->mbox_mem_pool);
14066 	return status;
14067 }
14068 
14069 /**
14070  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
14071  * @wq: The queue structure associated with the queue to destroy.
14072  *
14073  * This function destroys a queue, as detailed in @wq by sending an mailbox
14074  * command, specific to the type of queue, to the HBA.
14075  *
14076  * The @wq struct is used to get the queue ID of the queue to destroy.
14077  *
14078  * On success this function will return a zero. If the queue destroy mailbox
14079  * command fails this function will return -ENXIO.
14080  **/
14081 int
14082 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
14083 {
14084 	LPFC_MBOXQ_t *mbox;
14085 	int rc, length, status = 0;
14086 	uint32_t shdr_status, shdr_add_status;
14087 	union lpfc_sli4_cfg_shdr *shdr;
14088 
14089 	/* sanity check on queue memory */
14090 	if (!wq)
14091 		return -ENODEV;
14092 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
14093 	if (!mbox)
14094 		return -ENOMEM;
14095 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
14096 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14097 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14098 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
14099 			 length, LPFC_SLI4_MBX_EMBED);
14100 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
14101 	       wq->queue_id);
14102 	mbox->vport = wq->phba->pport;
14103 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14104 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
14105 	shdr = (union lpfc_sli4_cfg_shdr *)
14106 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
14107 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14108 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14109 	if (shdr_status || shdr_add_status || rc) {
14110 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14111 				"2508 WQ_DESTROY mailbox failed with "
14112 				"status x%x add_status x%x, mbx status x%x\n",
14113 				shdr_status, shdr_add_status, rc);
14114 		status = -ENXIO;
14115 	}
14116 	/* Remove wq from any list */
14117 	list_del_init(&wq->list);
14118 	mempool_free(mbox, wq->phba->mbox_mem_pool);
14119 	return status;
14120 }
14121 
14122 /**
14123  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
14124  * @rq: The queue structure associated with the queue to destroy.
14125  *
14126  * This function destroys a queue, as detailed in @rq by sending an mailbox
14127  * command, specific to the type of queue, to the HBA.
14128  *
14129  * The @rq struct is used to get the queue ID of the queue to destroy.
14130  *
14131  * On success this function will return a zero. If the queue destroy mailbox
14132  * command fails this function will return -ENXIO.
14133  **/
14134 int
14135 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
14136 		struct lpfc_queue *drq)
14137 {
14138 	LPFC_MBOXQ_t *mbox;
14139 	int rc, length, status = 0;
14140 	uint32_t shdr_status, shdr_add_status;
14141 	union lpfc_sli4_cfg_shdr *shdr;
14142 
14143 	/* sanity check on queue memory */
14144 	if (!hrq || !drq)
14145 		return -ENODEV;
14146 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
14147 	if (!mbox)
14148 		return -ENOMEM;
14149 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
14150 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14151 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14152 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
14153 			 length, LPFC_SLI4_MBX_EMBED);
14154 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
14155 	       hrq->queue_id);
14156 	mbox->vport = hrq->phba->pport;
14157 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14158 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
14159 	/* The IOCTL status is embedded in the mailbox subheader. */
14160 	shdr = (union lpfc_sli4_cfg_shdr *)
14161 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
14162 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14163 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14164 	if (shdr_status || shdr_add_status || rc) {
14165 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14166 				"2509 RQ_DESTROY mailbox failed with "
14167 				"status x%x add_status x%x, mbx status x%x\n",
14168 				shdr_status, shdr_add_status, rc);
14169 		if (rc != MBX_TIMEOUT)
14170 			mempool_free(mbox, hrq->phba->mbox_mem_pool);
14171 		return -ENXIO;
14172 	}
14173 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
14174 	       drq->queue_id);
14175 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
14176 	shdr = (union lpfc_sli4_cfg_shdr *)
14177 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
14178 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14179 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14180 	if (shdr_status || shdr_add_status || rc) {
14181 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14182 				"2510 RQ_DESTROY mailbox failed with "
14183 				"status x%x add_status x%x, mbx status x%x\n",
14184 				shdr_status, shdr_add_status, rc);
14185 		status = -ENXIO;
14186 	}
14187 	list_del_init(&hrq->list);
14188 	list_del_init(&drq->list);
14189 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
14190 	return status;
14191 }
14192 
14193 /**
14194  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
14195  * @phba: The virtual port for which this call being executed.
14196  * @pdma_phys_addr0: Physical address of the 1st SGL page.
14197  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
14198  * @xritag: the xritag that ties this io to the SGL pages.
14199  *
14200  * This routine will post the sgl pages for the IO that has the xritag
14201  * that is in the iocbq structure. The xritag is assigned during iocbq
14202  * creation and persists for as long as the driver is loaded.
14203  * if the caller has fewer than 256 scatter gather segments to map then
14204  * pdma_phys_addr1 should be 0.
14205  * If the caller needs to map more than 256 scatter gather segment then
14206  * pdma_phys_addr1 should be a valid physical address.
14207  * physical address for SGLs must be 64 byte aligned.
14208  * If you are going to map 2 SGL's then the first one must have 256 entries
14209  * the second sgl can have between 1 and 256 entries.
14210  *
14211  * Return codes:
14212  * 	0 - Success
14213  * 	-ENXIO, -ENOMEM - Failure
14214  **/
14215 int
14216 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
14217 		dma_addr_t pdma_phys_addr0,
14218 		dma_addr_t pdma_phys_addr1,
14219 		uint16_t xritag)
14220 {
14221 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
14222 	LPFC_MBOXQ_t *mbox;
14223 	int rc;
14224 	uint32_t shdr_status, shdr_add_status;
14225 	uint32_t mbox_tmo;
14226 	union lpfc_sli4_cfg_shdr *shdr;
14227 
14228 	if (xritag == NO_XRI) {
14229 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14230 				"0364 Invalid param:\n");
14231 		return -EINVAL;
14232 	}
14233 
14234 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14235 	if (!mbox)
14236 		return -ENOMEM;
14237 
14238 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14239 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
14240 			sizeof(struct lpfc_mbx_post_sgl_pages) -
14241 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
14242 
14243 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
14244 				&mbox->u.mqe.un.post_sgl_pages;
14245 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
14246 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
14247 
14248 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
14249 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
14250 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
14251 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
14252 
14253 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
14254 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
14255 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
14256 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
14257 	if (!phba->sli4_hba.intr_enable)
14258 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14259 	else {
14260 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
14261 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
14262 	}
14263 	/* The IOCTL status is embedded in the mailbox subheader. */
14264 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
14265 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14266 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14267 	if (rc != MBX_TIMEOUT)
14268 		mempool_free(mbox, phba->mbox_mem_pool);
14269 	if (shdr_status || shdr_add_status || rc) {
14270 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14271 				"2511 POST_SGL mailbox failed with "
14272 				"status x%x add_status x%x, mbx status x%x\n",
14273 				shdr_status, shdr_add_status, rc);
14274 	}
14275 	return 0;
14276 }
14277 
14278 /**
14279  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
14280  * @phba: pointer to lpfc hba data structure.
14281  *
14282  * This routine is invoked to post rpi header templates to the
14283  * HBA consistent with the SLI-4 interface spec.  This routine
14284  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
14285  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
14286  *
14287  * Returns
14288  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
14289  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
14290  **/
14291 static uint16_t
14292 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
14293 {
14294 	unsigned long xri;
14295 
14296 	/*
14297 	 * Fetch the next logical xri.  Because this index is logical,
14298 	 * the driver starts at 0 each time.
14299 	 */
14300 	spin_lock_irq(&phba->hbalock);
14301 	xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
14302 				 phba->sli4_hba.max_cfg_param.max_xri, 0);
14303 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
14304 		spin_unlock_irq(&phba->hbalock);
14305 		return NO_XRI;
14306 	} else {
14307 		set_bit(xri, phba->sli4_hba.xri_bmask);
14308 		phba->sli4_hba.max_cfg_param.xri_used++;
14309 	}
14310 	spin_unlock_irq(&phba->hbalock);
14311 	return xri;
14312 }
14313 
14314 /**
14315  * lpfc_sli4_free_xri - Release an xri for reuse.
14316  * @phba: pointer to lpfc hba data structure.
14317  *
14318  * This routine is invoked to release an xri to the pool of
14319  * available rpis maintained by the driver.
14320  **/
14321 static void
14322 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
14323 {
14324 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
14325 		phba->sli4_hba.max_cfg_param.xri_used--;
14326 	}
14327 }
14328 
14329 /**
14330  * lpfc_sli4_free_xri - Release an xri for reuse.
14331  * @phba: pointer to lpfc hba data structure.
14332  *
14333  * This routine is invoked to release an xri to the pool of
14334  * available rpis maintained by the driver.
14335  **/
14336 void
14337 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
14338 {
14339 	spin_lock_irq(&phba->hbalock);
14340 	__lpfc_sli4_free_xri(phba, xri);
14341 	spin_unlock_irq(&phba->hbalock);
14342 }
14343 
14344 /**
14345  * lpfc_sli4_next_xritag - Get an xritag for the io
14346  * @phba: Pointer to HBA context object.
14347  *
14348  * This function gets an xritag for the iocb. If there is no unused xritag
14349  * it will return 0xffff.
14350  * The function returns the allocated xritag if successful, else returns zero.
14351  * Zero is not a valid xritag.
14352  * The caller is not required to hold any lock.
14353  **/
14354 uint16_t
14355 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
14356 {
14357 	uint16_t xri_index;
14358 
14359 	xri_index = lpfc_sli4_alloc_xri(phba);
14360 	if (xri_index == NO_XRI)
14361 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14362 				"2004 Failed to allocate XRI.last XRITAG is %d"
14363 				" Max XRI is %d, Used XRI is %d\n",
14364 				xri_index,
14365 				phba->sli4_hba.max_cfg_param.max_xri,
14366 				phba->sli4_hba.max_cfg_param.xri_used);
14367 	return xri_index;
14368 }
14369 
14370 /**
14371  * lpfc_sli4_post_els_sgl_list - post a block of ELS sgls to the port.
14372  * @phba: pointer to lpfc hba data structure.
14373  * @post_sgl_list: pointer to els sgl entry list.
14374  * @count: number of els sgl entries on the list.
14375  *
14376  * This routine is invoked to post a block of driver's sgl pages to the
14377  * HBA using non-embedded mailbox command. No Lock is held. This routine
14378  * is only called when the driver is loading and after all IO has been
14379  * stopped.
14380  **/
14381 static int
14382 lpfc_sli4_post_els_sgl_list(struct lpfc_hba *phba,
14383 			    struct list_head *post_sgl_list,
14384 			    int post_cnt)
14385 {
14386 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
14387 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
14388 	struct sgl_page_pairs *sgl_pg_pairs;
14389 	void *viraddr;
14390 	LPFC_MBOXQ_t *mbox;
14391 	uint32_t reqlen, alloclen, pg_pairs;
14392 	uint32_t mbox_tmo;
14393 	uint16_t xritag_start = 0;
14394 	int rc = 0;
14395 	uint32_t shdr_status, shdr_add_status;
14396 	union lpfc_sli4_cfg_shdr *shdr;
14397 
14398 	reqlen = phba->sli4_hba.els_xri_cnt * sizeof(struct sgl_page_pairs) +
14399 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
14400 	if (reqlen > SLI4_PAGE_SIZE) {
14401 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
14402 				"2559 Block sgl registration required DMA "
14403 				"size (%d) great than a page\n", reqlen);
14404 		return -ENOMEM;
14405 	}
14406 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14407 	if (!mbox)
14408 		return -ENOMEM;
14409 
14410 	/* Allocate DMA memory and set up the non-embedded mailbox command */
14411 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14412 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
14413 			 LPFC_SLI4_MBX_NEMBED);
14414 
14415 	if (alloclen < reqlen) {
14416 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14417 				"0285 Allocated DMA memory size (%d) is "
14418 				"less than the requested DMA memory "
14419 				"size (%d)\n", alloclen, reqlen);
14420 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14421 		return -ENOMEM;
14422 	}
14423 	/* Set up the SGL pages in the non-embedded DMA pages */
14424 	viraddr = mbox->sge_array->addr[0];
14425 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
14426 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
14427 
14428 	pg_pairs = 0;
14429 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
14430 		/* Set up the sge entry */
14431 		sgl_pg_pairs->sgl_pg0_addr_lo =
14432 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
14433 		sgl_pg_pairs->sgl_pg0_addr_hi =
14434 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
14435 		sgl_pg_pairs->sgl_pg1_addr_lo =
14436 				cpu_to_le32(putPaddrLow(0));
14437 		sgl_pg_pairs->sgl_pg1_addr_hi =
14438 				cpu_to_le32(putPaddrHigh(0));
14439 
14440 		/* Keep the first xritag on the list */
14441 		if (pg_pairs == 0)
14442 			xritag_start = sglq_entry->sli4_xritag;
14443 		sgl_pg_pairs++;
14444 		pg_pairs++;
14445 	}
14446 
14447 	/* Complete initialization and perform endian conversion. */
14448 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
14449 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, phba->sli4_hba.els_xri_cnt);
14450 	sgl->word0 = cpu_to_le32(sgl->word0);
14451 	if (!phba->sli4_hba.intr_enable)
14452 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14453 	else {
14454 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
14455 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
14456 	}
14457 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
14458 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14459 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14460 	if (rc != MBX_TIMEOUT)
14461 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14462 	if (shdr_status || shdr_add_status || rc) {
14463 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14464 				"2513 POST_SGL_BLOCK mailbox command failed "
14465 				"status x%x add_status x%x mbx status x%x\n",
14466 				shdr_status, shdr_add_status, rc);
14467 		rc = -ENXIO;
14468 	}
14469 	return rc;
14470 }
14471 
14472 /**
14473  * lpfc_sli4_post_scsi_sgl_block - post a block of scsi sgl list to firmware
14474  * @phba: pointer to lpfc hba data structure.
14475  * @sblist: pointer to scsi buffer list.
14476  * @count: number of scsi buffers on the list.
14477  *
14478  * This routine is invoked to post a block of @count scsi sgl pages from a
14479  * SCSI buffer list @sblist to the HBA using non-embedded mailbox command.
14480  * No Lock is held.
14481  *
14482  **/
14483 int
14484 lpfc_sli4_post_scsi_sgl_block(struct lpfc_hba *phba,
14485 			      struct list_head *sblist,
14486 			      int count)
14487 {
14488 	struct lpfc_scsi_buf *psb;
14489 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
14490 	struct sgl_page_pairs *sgl_pg_pairs;
14491 	void *viraddr;
14492 	LPFC_MBOXQ_t *mbox;
14493 	uint32_t reqlen, alloclen, pg_pairs;
14494 	uint32_t mbox_tmo;
14495 	uint16_t xritag_start = 0;
14496 	int rc = 0;
14497 	uint32_t shdr_status, shdr_add_status;
14498 	dma_addr_t pdma_phys_bpl1;
14499 	union lpfc_sli4_cfg_shdr *shdr;
14500 
14501 	/* Calculate the requested length of the dma memory */
14502 	reqlen = count * sizeof(struct sgl_page_pairs) +
14503 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
14504 	if (reqlen > SLI4_PAGE_SIZE) {
14505 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
14506 				"0217 Block sgl registration required DMA "
14507 				"size (%d) great than a page\n", reqlen);
14508 		return -ENOMEM;
14509 	}
14510 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14511 	if (!mbox) {
14512 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14513 				"0283 Failed to allocate mbox cmd memory\n");
14514 		return -ENOMEM;
14515 	}
14516 
14517 	/* Allocate DMA memory and set up the non-embedded mailbox command */
14518 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14519 				LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
14520 				LPFC_SLI4_MBX_NEMBED);
14521 
14522 	if (alloclen < reqlen) {
14523 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14524 				"2561 Allocated DMA memory size (%d) is "
14525 				"less than the requested DMA memory "
14526 				"size (%d)\n", alloclen, reqlen);
14527 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14528 		return -ENOMEM;
14529 	}
14530 
14531 	/* Get the first SGE entry from the non-embedded DMA memory */
14532 	viraddr = mbox->sge_array->addr[0];
14533 
14534 	/* Set up the SGL pages in the non-embedded DMA pages */
14535 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
14536 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
14537 
14538 	pg_pairs = 0;
14539 	list_for_each_entry(psb, sblist, list) {
14540 		/* Set up the sge entry */
14541 		sgl_pg_pairs->sgl_pg0_addr_lo =
14542 			cpu_to_le32(putPaddrLow(psb->dma_phys_bpl));
14543 		sgl_pg_pairs->sgl_pg0_addr_hi =
14544 			cpu_to_le32(putPaddrHigh(psb->dma_phys_bpl));
14545 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
14546 			pdma_phys_bpl1 = psb->dma_phys_bpl + SGL_PAGE_SIZE;
14547 		else
14548 			pdma_phys_bpl1 = 0;
14549 		sgl_pg_pairs->sgl_pg1_addr_lo =
14550 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
14551 		sgl_pg_pairs->sgl_pg1_addr_hi =
14552 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
14553 		/* Keep the first xritag on the list */
14554 		if (pg_pairs == 0)
14555 			xritag_start = psb->cur_iocbq.sli4_xritag;
14556 		sgl_pg_pairs++;
14557 		pg_pairs++;
14558 	}
14559 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
14560 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
14561 	/* Perform endian conversion if necessary */
14562 	sgl->word0 = cpu_to_le32(sgl->word0);
14563 
14564 	if (!phba->sli4_hba.intr_enable)
14565 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14566 	else {
14567 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
14568 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
14569 	}
14570 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
14571 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14572 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14573 	if (rc != MBX_TIMEOUT)
14574 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14575 	if (shdr_status || shdr_add_status || rc) {
14576 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14577 				"2564 POST_SGL_BLOCK mailbox command failed "
14578 				"status x%x add_status x%x mbx status x%x\n",
14579 				shdr_status, shdr_add_status, rc);
14580 		rc = -ENXIO;
14581 	}
14582 	return rc;
14583 }
14584 
14585 /**
14586  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
14587  * @phba: pointer to lpfc_hba struct that the frame was received on
14588  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
14589  *
14590  * This function checks the fields in the @fc_hdr to see if the FC frame is a
14591  * valid type of frame that the LPFC driver will handle. This function will
14592  * return a zero if the frame is a valid frame or a non zero value when the
14593  * frame does not pass the check.
14594  **/
14595 static int
14596 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
14597 {
14598 	/*  make rctl_names static to save stack space */
14599 	static char *rctl_names[] = FC_RCTL_NAMES_INIT;
14600 	char *type_names[] = FC_TYPE_NAMES_INIT;
14601 	struct fc_vft_header *fc_vft_hdr;
14602 	uint32_t *header = (uint32_t *) fc_hdr;
14603 
14604 	switch (fc_hdr->fh_r_ctl) {
14605 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
14606 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
14607 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
14608 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
14609 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
14610 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
14611 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
14612 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
14613 	case FC_RCTL_ELS_REQ:	/* extended link services request */
14614 	case FC_RCTL_ELS_REP:	/* extended link services reply */
14615 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
14616 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
14617 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
14618 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
14619 	case FC_RCTL_BA_RMC: 	/* remove connection */
14620 	case FC_RCTL_BA_ACC:	/* basic accept */
14621 	case FC_RCTL_BA_RJT:	/* basic reject */
14622 	case FC_RCTL_BA_PRMT:
14623 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
14624 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
14625 	case FC_RCTL_P_RJT:	/* port reject */
14626 	case FC_RCTL_F_RJT:	/* fabric reject */
14627 	case FC_RCTL_P_BSY:	/* port busy */
14628 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
14629 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
14630 	case FC_RCTL_LCR:	/* link credit reset */
14631 	case FC_RCTL_END:	/* end */
14632 		break;
14633 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
14634 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
14635 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
14636 		return lpfc_fc_frame_check(phba, fc_hdr);
14637 	default:
14638 		goto drop;
14639 	}
14640 	switch (fc_hdr->fh_type) {
14641 	case FC_TYPE_BLS:
14642 	case FC_TYPE_ELS:
14643 	case FC_TYPE_FCP:
14644 	case FC_TYPE_CT:
14645 		break;
14646 	case FC_TYPE_IP:
14647 	case FC_TYPE_ILS:
14648 	default:
14649 		goto drop;
14650 	}
14651 
14652 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
14653 			"2538 Received frame rctl:%s (x%x), type:%s (x%x), "
14654 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
14655 			rctl_names[fc_hdr->fh_r_ctl], fc_hdr->fh_r_ctl,
14656 			type_names[fc_hdr->fh_type], fc_hdr->fh_type,
14657 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
14658 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
14659 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
14660 			be32_to_cpu(header[6]));
14661 	return 0;
14662 drop:
14663 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
14664 			"2539 Dropped frame rctl:%s type:%s\n",
14665 			rctl_names[fc_hdr->fh_r_ctl],
14666 			type_names[fc_hdr->fh_type]);
14667 	return 1;
14668 }
14669 
14670 /**
14671  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
14672  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
14673  *
14674  * This function processes the FC header to retrieve the VFI from the VF
14675  * header, if one exists. This function will return the VFI if one exists
14676  * or 0 if no VSAN Header exists.
14677  **/
14678 static uint32_t
14679 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
14680 {
14681 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
14682 
14683 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
14684 		return 0;
14685 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
14686 }
14687 
14688 /**
14689  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
14690  * @phba: Pointer to the HBA structure to search for the vport on
14691  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
14692  * @fcfi: The FC Fabric ID that the frame came from
14693  *
14694  * This function searches the @phba for a vport that matches the content of the
14695  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
14696  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
14697  * returns the matching vport pointer or NULL if unable to match frame to a
14698  * vport.
14699  **/
14700 static struct lpfc_vport *
14701 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
14702 		       uint16_t fcfi)
14703 {
14704 	struct lpfc_vport **vports;
14705 	struct lpfc_vport *vport = NULL;
14706 	int i;
14707 	uint32_t did = (fc_hdr->fh_d_id[0] << 16 |
14708 			fc_hdr->fh_d_id[1] << 8 |
14709 			fc_hdr->fh_d_id[2]);
14710 
14711 	if (did == Fabric_DID)
14712 		return phba->pport;
14713 	if ((phba->pport->fc_flag & FC_PT2PT) &&
14714 		!(phba->link_state == LPFC_HBA_READY))
14715 		return phba->pport;
14716 
14717 	vports = lpfc_create_vport_work_array(phba);
14718 	if (vports != NULL)
14719 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
14720 			if (phba->fcf.fcfi == fcfi &&
14721 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
14722 			    vports[i]->fc_myDID == did) {
14723 				vport = vports[i];
14724 				break;
14725 			}
14726 		}
14727 	lpfc_destroy_vport_work_array(phba, vports);
14728 	return vport;
14729 }
14730 
14731 /**
14732  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
14733  * @vport: The vport to work on.
14734  *
14735  * This function updates the receive sequence time stamp for this vport. The
14736  * receive sequence time stamp indicates the time that the last frame of the
14737  * the sequence that has been idle for the longest amount of time was received.
14738  * the driver uses this time stamp to indicate if any received sequences have
14739  * timed out.
14740  **/
14741 static void
14742 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
14743 {
14744 	struct lpfc_dmabuf *h_buf;
14745 	struct hbq_dmabuf *dmabuf = NULL;
14746 
14747 	/* get the oldest sequence on the rcv list */
14748 	h_buf = list_get_first(&vport->rcv_buffer_list,
14749 			       struct lpfc_dmabuf, list);
14750 	if (!h_buf)
14751 		return;
14752 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
14753 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
14754 }
14755 
14756 /**
14757  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
14758  * @vport: The vport that the received sequences were sent to.
14759  *
14760  * This function cleans up all outstanding received sequences. This is called
14761  * by the driver when a link event or user action invalidates all the received
14762  * sequences.
14763  **/
14764 void
14765 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
14766 {
14767 	struct lpfc_dmabuf *h_buf, *hnext;
14768 	struct lpfc_dmabuf *d_buf, *dnext;
14769 	struct hbq_dmabuf *dmabuf = NULL;
14770 
14771 	/* start with the oldest sequence on the rcv list */
14772 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
14773 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
14774 		list_del_init(&dmabuf->hbuf.list);
14775 		list_for_each_entry_safe(d_buf, dnext,
14776 					 &dmabuf->dbuf.list, list) {
14777 			list_del_init(&d_buf->list);
14778 			lpfc_in_buf_free(vport->phba, d_buf);
14779 		}
14780 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
14781 	}
14782 }
14783 
14784 /**
14785  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
14786  * @vport: The vport that the received sequences were sent to.
14787  *
14788  * This function determines whether any received sequences have timed out by
14789  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
14790  * indicates that there is at least one timed out sequence this routine will
14791  * go through the received sequences one at a time from most inactive to most
14792  * active to determine which ones need to be cleaned up. Once it has determined
14793  * that a sequence needs to be cleaned up it will simply free up the resources
14794  * without sending an abort.
14795  **/
14796 void
14797 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
14798 {
14799 	struct lpfc_dmabuf *h_buf, *hnext;
14800 	struct lpfc_dmabuf *d_buf, *dnext;
14801 	struct hbq_dmabuf *dmabuf = NULL;
14802 	unsigned long timeout;
14803 	int abort_count = 0;
14804 
14805 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
14806 		   vport->rcv_buffer_time_stamp);
14807 	if (list_empty(&vport->rcv_buffer_list) ||
14808 	    time_before(jiffies, timeout))
14809 		return;
14810 	/* start with the oldest sequence on the rcv list */
14811 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
14812 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
14813 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
14814 			   dmabuf->time_stamp);
14815 		if (time_before(jiffies, timeout))
14816 			break;
14817 		abort_count++;
14818 		list_del_init(&dmabuf->hbuf.list);
14819 		list_for_each_entry_safe(d_buf, dnext,
14820 					 &dmabuf->dbuf.list, list) {
14821 			list_del_init(&d_buf->list);
14822 			lpfc_in_buf_free(vport->phba, d_buf);
14823 		}
14824 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
14825 	}
14826 	if (abort_count)
14827 		lpfc_update_rcv_time_stamp(vport);
14828 }
14829 
14830 /**
14831  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
14832  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
14833  *
14834  * This function searches through the existing incomplete sequences that have
14835  * been sent to this @vport. If the frame matches one of the incomplete
14836  * sequences then the dbuf in the @dmabuf is added to the list of frames that
14837  * make up that sequence. If no sequence is found that matches this frame then
14838  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
14839  * This function returns a pointer to the first dmabuf in the sequence list that
14840  * the frame was linked to.
14841  **/
14842 static struct hbq_dmabuf *
14843 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
14844 {
14845 	struct fc_frame_header *new_hdr;
14846 	struct fc_frame_header *temp_hdr;
14847 	struct lpfc_dmabuf *d_buf;
14848 	struct lpfc_dmabuf *h_buf;
14849 	struct hbq_dmabuf *seq_dmabuf = NULL;
14850 	struct hbq_dmabuf *temp_dmabuf = NULL;
14851 
14852 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
14853 	dmabuf->time_stamp = jiffies;
14854 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
14855 	/* Use the hdr_buf to find the sequence that this frame belongs to */
14856 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
14857 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
14858 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
14859 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
14860 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
14861 			continue;
14862 		/* found a pending sequence that matches this frame */
14863 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
14864 		break;
14865 	}
14866 	if (!seq_dmabuf) {
14867 		/*
14868 		 * This indicates first frame received for this sequence.
14869 		 * Queue the buffer on the vport's rcv_buffer_list.
14870 		 */
14871 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
14872 		lpfc_update_rcv_time_stamp(vport);
14873 		return dmabuf;
14874 	}
14875 	temp_hdr = seq_dmabuf->hbuf.virt;
14876 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
14877 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
14878 		list_del_init(&seq_dmabuf->hbuf.list);
14879 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
14880 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
14881 		lpfc_update_rcv_time_stamp(vport);
14882 		return dmabuf;
14883 	}
14884 	/* move this sequence to the tail to indicate a young sequence */
14885 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
14886 	seq_dmabuf->time_stamp = jiffies;
14887 	lpfc_update_rcv_time_stamp(vport);
14888 	if (list_empty(&seq_dmabuf->dbuf.list)) {
14889 		temp_hdr = dmabuf->hbuf.virt;
14890 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
14891 		return seq_dmabuf;
14892 	}
14893 	/* find the correct place in the sequence to insert this frame */
14894 	list_for_each_entry_reverse(d_buf, &seq_dmabuf->dbuf.list, list) {
14895 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
14896 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
14897 		/*
14898 		 * If the frame's sequence count is greater than the frame on
14899 		 * the list then insert the frame right after this frame
14900 		 */
14901 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
14902 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
14903 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
14904 			return seq_dmabuf;
14905 		}
14906 	}
14907 	return NULL;
14908 }
14909 
14910 /**
14911  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
14912  * @vport: pointer to a vitural port
14913  * @dmabuf: pointer to a dmabuf that describes the FC sequence
14914  *
14915  * This function tries to abort from the partially assembed sequence, described
14916  * by the information from basic abbort @dmabuf. It checks to see whether such
14917  * partially assembled sequence held by the driver. If so, it shall free up all
14918  * the frames from the partially assembled sequence.
14919  *
14920  * Return
14921  * true  -- if there is matching partially assembled sequence present and all
14922  *          the frames freed with the sequence;
14923  * false -- if there is no matching partially assembled sequence present so
14924  *          nothing got aborted in the lower layer driver
14925  **/
14926 static bool
14927 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
14928 			    struct hbq_dmabuf *dmabuf)
14929 {
14930 	struct fc_frame_header *new_hdr;
14931 	struct fc_frame_header *temp_hdr;
14932 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
14933 	struct hbq_dmabuf *seq_dmabuf = NULL;
14934 
14935 	/* Use the hdr_buf to find the sequence that matches this frame */
14936 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
14937 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
14938 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
14939 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
14940 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
14941 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
14942 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
14943 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
14944 			continue;
14945 		/* found a pending sequence that matches this frame */
14946 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
14947 		break;
14948 	}
14949 
14950 	/* Free up all the frames from the partially assembled sequence */
14951 	if (seq_dmabuf) {
14952 		list_for_each_entry_safe(d_buf, n_buf,
14953 					 &seq_dmabuf->dbuf.list, list) {
14954 			list_del_init(&d_buf->list);
14955 			lpfc_in_buf_free(vport->phba, d_buf);
14956 		}
14957 		return true;
14958 	}
14959 	return false;
14960 }
14961 
14962 /**
14963  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
14964  * @vport: pointer to a vitural port
14965  * @dmabuf: pointer to a dmabuf that describes the FC sequence
14966  *
14967  * This function tries to abort from the assembed sequence from upper level
14968  * protocol, described by the information from basic abbort @dmabuf. It
14969  * checks to see whether such pending context exists at upper level protocol.
14970  * If so, it shall clean up the pending context.
14971  *
14972  * Return
14973  * true  -- if there is matching pending context of the sequence cleaned
14974  *          at ulp;
14975  * false -- if there is no matching pending context of the sequence present
14976  *          at ulp.
14977  **/
14978 static bool
14979 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
14980 {
14981 	struct lpfc_hba *phba = vport->phba;
14982 	int handled;
14983 
14984 	/* Accepting abort at ulp with SLI4 only */
14985 	if (phba->sli_rev < LPFC_SLI_REV4)
14986 		return false;
14987 
14988 	/* Register all caring upper level protocols to attend abort */
14989 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
14990 	if (handled)
14991 		return true;
14992 
14993 	return false;
14994 }
14995 
14996 /**
14997  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
14998  * @phba: Pointer to HBA context object.
14999  * @cmd_iocbq: pointer to the command iocbq structure.
15000  * @rsp_iocbq: pointer to the response iocbq structure.
15001  *
15002  * This function handles the sequence abort response iocb command complete
15003  * event. It properly releases the memory allocated to the sequence abort
15004  * accept iocb.
15005  **/
15006 static void
15007 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
15008 			     struct lpfc_iocbq *cmd_iocbq,
15009 			     struct lpfc_iocbq *rsp_iocbq)
15010 {
15011 	struct lpfc_nodelist *ndlp;
15012 
15013 	if (cmd_iocbq) {
15014 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
15015 		lpfc_nlp_put(ndlp);
15016 		lpfc_nlp_not_used(ndlp);
15017 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
15018 	}
15019 
15020 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
15021 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
15022 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15023 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
15024 			rsp_iocbq->iocb.ulpStatus,
15025 			rsp_iocbq->iocb.un.ulpWord[4]);
15026 }
15027 
15028 /**
15029  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
15030  * @phba: Pointer to HBA context object.
15031  * @xri: xri id in transaction.
15032  *
15033  * This function validates the xri maps to the known range of XRIs allocated an
15034  * used by the driver.
15035  **/
15036 uint16_t
15037 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
15038 		      uint16_t xri)
15039 {
15040 	uint16_t i;
15041 
15042 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
15043 		if (xri == phba->sli4_hba.xri_ids[i])
15044 			return i;
15045 	}
15046 	return NO_XRI;
15047 }
15048 
15049 /**
15050  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
15051  * @phba: Pointer to HBA context object.
15052  * @fc_hdr: pointer to a FC frame header.
15053  *
15054  * This function sends a basic response to a previous unsol sequence abort
15055  * event after aborting the sequence handling.
15056  **/
15057 static void
15058 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
15059 			struct fc_frame_header *fc_hdr, bool aborted)
15060 {
15061 	struct lpfc_hba *phba = vport->phba;
15062 	struct lpfc_iocbq *ctiocb = NULL;
15063 	struct lpfc_nodelist *ndlp;
15064 	uint16_t oxid, rxid, xri, lxri;
15065 	uint32_t sid, fctl;
15066 	IOCB_t *icmd;
15067 	int rc;
15068 
15069 	if (!lpfc_is_link_up(phba))
15070 		return;
15071 
15072 	sid = sli4_sid_from_fc_hdr(fc_hdr);
15073 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
15074 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
15075 
15076 	ndlp = lpfc_findnode_did(vport, sid);
15077 	if (!ndlp) {
15078 		ndlp = mempool_alloc(phba->nlp_mem_pool, GFP_KERNEL);
15079 		if (!ndlp) {
15080 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
15081 					 "1268 Failed to allocate ndlp for "
15082 					 "oxid:x%x SID:x%x\n", oxid, sid);
15083 			return;
15084 		}
15085 		lpfc_nlp_init(vport, ndlp, sid);
15086 		/* Put ndlp onto pport node list */
15087 		lpfc_enqueue_node(vport, ndlp);
15088 	} else if (!NLP_CHK_NODE_ACT(ndlp)) {
15089 		/* re-setup ndlp without removing from node list */
15090 		ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
15091 		if (!ndlp) {
15092 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
15093 					 "3275 Failed to active ndlp found "
15094 					 "for oxid:x%x SID:x%x\n", oxid, sid);
15095 			return;
15096 		}
15097 	}
15098 
15099 	/* Allocate buffer for rsp iocb */
15100 	ctiocb = lpfc_sli_get_iocbq(phba);
15101 	if (!ctiocb)
15102 		return;
15103 
15104 	/* Extract the F_CTL field from FC_HDR */
15105 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
15106 
15107 	icmd = &ctiocb->iocb;
15108 	icmd->un.xseq64.bdl.bdeSize = 0;
15109 	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
15110 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
15111 	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
15112 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
15113 
15114 	/* Fill in the rest of iocb fields */
15115 	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
15116 	icmd->ulpBdeCount = 0;
15117 	icmd->ulpLe = 1;
15118 	icmd->ulpClass = CLASS3;
15119 	icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
15120 	ctiocb->context1 = lpfc_nlp_get(ndlp);
15121 
15122 	ctiocb->iocb_cmpl = NULL;
15123 	ctiocb->vport = phba->pport;
15124 	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
15125 	ctiocb->sli4_lxritag = NO_XRI;
15126 	ctiocb->sli4_xritag = NO_XRI;
15127 
15128 	if (fctl & FC_FC_EX_CTX)
15129 		/* Exchange responder sent the abort so we
15130 		 * own the oxid.
15131 		 */
15132 		xri = oxid;
15133 	else
15134 		xri = rxid;
15135 	lxri = lpfc_sli4_xri_inrange(phba, xri);
15136 	if (lxri != NO_XRI)
15137 		lpfc_set_rrq_active(phba, ndlp, lxri,
15138 			(xri == oxid) ? rxid : oxid, 0);
15139 	/* For BA_ABTS from exchange responder, if the logical xri with
15140 	 * the oxid maps to the FCP XRI range, the port no longer has
15141 	 * that exchange context, send a BLS_RJT. Override the IOCB for
15142 	 * a BA_RJT.
15143 	 */
15144 	if ((fctl & FC_FC_EX_CTX) &&
15145 	    (lxri > lpfc_sli4_get_els_iocb_cnt(phba))) {
15146 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
15147 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
15148 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
15149 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
15150 	}
15151 
15152 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
15153 	 * the driver no longer has that exchange, send a BLS_RJT. Override
15154 	 * the IOCB for a BA_RJT.
15155 	 */
15156 	if (aborted == false) {
15157 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
15158 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
15159 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
15160 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
15161 	}
15162 
15163 	if (fctl & FC_FC_EX_CTX) {
15164 		/* ABTS sent by responder to CT exchange, construction
15165 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
15166 		 * field and RX_ID from ABTS for RX_ID field.
15167 		 */
15168 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
15169 	} else {
15170 		/* ABTS sent by initiator to CT exchange, construction
15171 		 * of BA_ACC will need to allocate a new XRI as for the
15172 		 * XRI_TAG field.
15173 		 */
15174 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
15175 	}
15176 	bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
15177 	bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
15178 
15179 	/* Xmit CT abts response on exchange <xid> */
15180 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
15181 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
15182 			 icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
15183 
15184 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
15185 	if (rc == IOCB_ERROR) {
15186 		lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
15187 				 "2925 Failed to issue CT ABTS RSP x%x on "
15188 				 "xri x%x, Data x%x\n",
15189 				 icmd->un.xseq64.w5.hcsw.Rctl, oxid,
15190 				 phba->link_state);
15191 		lpfc_nlp_put(ndlp);
15192 		ctiocb->context1 = NULL;
15193 		lpfc_sli_release_iocbq(phba, ctiocb);
15194 	}
15195 }
15196 
15197 /**
15198  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
15199  * @vport: Pointer to the vport on which this sequence was received
15200  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15201  *
15202  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
15203  * receive sequence is only partially assembed by the driver, it shall abort
15204  * the partially assembled frames for the sequence. Otherwise, if the
15205  * unsolicited receive sequence has been completely assembled and passed to
15206  * the Upper Layer Protocol (UPL), it then mark the per oxid status for the
15207  * unsolicited sequence has been aborted. After that, it will issue a basic
15208  * accept to accept the abort.
15209  **/
15210 static void
15211 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
15212 			     struct hbq_dmabuf *dmabuf)
15213 {
15214 	struct lpfc_hba *phba = vport->phba;
15215 	struct fc_frame_header fc_hdr;
15216 	uint32_t fctl;
15217 	bool aborted;
15218 
15219 	/* Make a copy of fc_hdr before the dmabuf being released */
15220 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
15221 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
15222 
15223 	if (fctl & FC_FC_EX_CTX) {
15224 		/* ABTS by responder to exchange, no cleanup needed */
15225 		aborted = true;
15226 	} else {
15227 		/* ABTS by initiator to exchange, need to do cleanup */
15228 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
15229 		if (aborted == false)
15230 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
15231 	}
15232 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
15233 
15234 	/* Respond with BA_ACC or BA_RJT accordingly */
15235 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
15236 }
15237 
15238 /**
15239  * lpfc_seq_complete - Indicates if a sequence is complete
15240  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15241  *
15242  * This function checks the sequence, starting with the frame described by
15243  * @dmabuf, to see if all the frames associated with this sequence are present.
15244  * the frames associated with this sequence are linked to the @dmabuf using the
15245  * dbuf list. This function looks for two major things. 1) That the first frame
15246  * has a sequence count of zero. 2) There is a frame with last frame of sequence
15247  * set. 3) That there are no holes in the sequence count. The function will
15248  * return 1 when the sequence is complete, otherwise it will return 0.
15249  **/
15250 static int
15251 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
15252 {
15253 	struct fc_frame_header *hdr;
15254 	struct lpfc_dmabuf *d_buf;
15255 	struct hbq_dmabuf *seq_dmabuf;
15256 	uint32_t fctl;
15257 	int seq_count = 0;
15258 
15259 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
15260 	/* make sure first fame of sequence has a sequence count of zero */
15261 	if (hdr->fh_seq_cnt != seq_count)
15262 		return 0;
15263 	fctl = (hdr->fh_f_ctl[0] << 16 |
15264 		hdr->fh_f_ctl[1] << 8 |
15265 		hdr->fh_f_ctl[2]);
15266 	/* If last frame of sequence we can return success. */
15267 	if (fctl & FC_FC_END_SEQ)
15268 		return 1;
15269 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
15270 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15271 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
15272 		/* If there is a hole in the sequence count then fail. */
15273 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
15274 			return 0;
15275 		fctl = (hdr->fh_f_ctl[0] << 16 |
15276 			hdr->fh_f_ctl[1] << 8 |
15277 			hdr->fh_f_ctl[2]);
15278 		/* If last frame of sequence we can return success. */
15279 		if (fctl & FC_FC_END_SEQ)
15280 			return 1;
15281 	}
15282 	return 0;
15283 }
15284 
15285 /**
15286  * lpfc_prep_seq - Prep sequence for ULP processing
15287  * @vport: Pointer to the vport on which this sequence was received
15288  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15289  *
15290  * This function takes a sequence, described by a list of frames, and creates
15291  * a list of iocbq structures to describe the sequence. This iocbq list will be
15292  * used to issue to the generic unsolicited sequence handler. This routine
15293  * returns a pointer to the first iocbq in the list. If the function is unable
15294  * to allocate an iocbq then it throw out the received frames that were not
15295  * able to be described and return a pointer to the first iocbq. If unable to
15296  * allocate any iocbqs (including the first) this function will return NULL.
15297  **/
15298 static struct lpfc_iocbq *
15299 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
15300 {
15301 	struct hbq_dmabuf *hbq_buf;
15302 	struct lpfc_dmabuf *d_buf, *n_buf;
15303 	struct lpfc_iocbq *first_iocbq, *iocbq;
15304 	struct fc_frame_header *fc_hdr;
15305 	uint32_t sid;
15306 	uint32_t len, tot_len;
15307 	struct ulp_bde64 *pbde;
15308 
15309 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
15310 	/* remove from receive buffer list */
15311 	list_del_init(&seq_dmabuf->hbuf.list);
15312 	lpfc_update_rcv_time_stamp(vport);
15313 	/* get the Remote Port's SID */
15314 	sid = sli4_sid_from_fc_hdr(fc_hdr);
15315 	tot_len = 0;
15316 	/* Get an iocbq struct to fill in. */
15317 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
15318 	if (first_iocbq) {
15319 		/* Initialize the first IOCB. */
15320 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
15321 		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
15322 
15323 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
15324 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
15325 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
15326 			first_iocbq->iocb.un.rcvels.parmRo =
15327 				sli4_did_from_fc_hdr(fc_hdr);
15328 			first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
15329 		} else
15330 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
15331 		first_iocbq->iocb.ulpContext = NO_XRI;
15332 		first_iocbq->iocb.unsli3.rcvsli3.ox_id =
15333 			be16_to_cpu(fc_hdr->fh_ox_id);
15334 		/* iocbq is prepped for internal consumption.  Physical vpi. */
15335 		first_iocbq->iocb.unsli3.rcvsli3.vpi =
15336 			vport->phba->vpi_ids[vport->vpi];
15337 		/* put the first buffer into the first IOCBq */
15338 		tot_len = bf_get(lpfc_rcqe_length,
15339 				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
15340 
15341 		first_iocbq->context2 = &seq_dmabuf->dbuf;
15342 		first_iocbq->context3 = NULL;
15343 		first_iocbq->iocb.ulpBdeCount = 1;
15344 		if (tot_len > LPFC_DATA_BUF_SIZE)
15345 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
15346 							LPFC_DATA_BUF_SIZE;
15347 		else
15348 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
15349 
15350 		first_iocbq->iocb.un.rcvels.remoteID = sid;
15351 
15352 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
15353 	}
15354 	iocbq = first_iocbq;
15355 	/*
15356 	 * Each IOCBq can have two Buffers assigned, so go through the list
15357 	 * of buffers for this sequence and save two buffers in each IOCBq
15358 	 */
15359 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
15360 		if (!iocbq) {
15361 			lpfc_in_buf_free(vport->phba, d_buf);
15362 			continue;
15363 		}
15364 		if (!iocbq->context3) {
15365 			iocbq->context3 = d_buf;
15366 			iocbq->iocb.ulpBdeCount++;
15367 			/* We need to get the size out of the right CQE */
15368 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15369 			len = bf_get(lpfc_rcqe_length,
15370 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
15371 			pbde = (struct ulp_bde64 *)
15372 					&iocbq->iocb.unsli3.sli3Words[4];
15373 			if (len > LPFC_DATA_BUF_SIZE)
15374 				pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
15375 			else
15376 				pbde->tus.f.bdeSize = len;
15377 
15378 			iocbq->iocb.unsli3.rcvsli3.acc_len += len;
15379 			tot_len += len;
15380 		} else {
15381 			iocbq = lpfc_sli_get_iocbq(vport->phba);
15382 			if (!iocbq) {
15383 				if (first_iocbq) {
15384 					first_iocbq->iocb.ulpStatus =
15385 							IOSTAT_FCP_RSP_ERROR;
15386 					first_iocbq->iocb.un.ulpWord[4] =
15387 							IOERR_NO_RESOURCES;
15388 				}
15389 				lpfc_in_buf_free(vport->phba, d_buf);
15390 				continue;
15391 			}
15392 			/* We need to get the size out of the right CQE */
15393 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15394 			len = bf_get(lpfc_rcqe_length,
15395 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
15396 			iocbq->context2 = d_buf;
15397 			iocbq->context3 = NULL;
15398 			iocbq->iocb.ulpBdeCount = 1;
15399 			if (len > LPFC_DATA_BUF_SIZE)
15400 				iocbq->iocb.un.cont64[0].tus.f.bdeSize =
15401 							LPFC_DATA_BUF_SIZE;
15402 			else
15403 				iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
15404 
15405 			tot_len += len;
15406 			iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
15407 
15408 			iocbq->iocb.un.rcvels.remoteID = sid;
15409 			list_add_tail(&iocbq->list, &first_iocbq->list);
15410 		}
15411 	}
15412 	return first_iocbq;
15413 }
15414 
15415 static void
15416 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
15417 			  struct hbq_dmabuf *seq_dmabuf)
15418 {
15419 	struct fc_frame_header *fc_hdr;
15420 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
15421 	struct lpfc_hba *phba = vport->phba;
15422 
15423 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
15424 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
15425 	if (!iocbq) {
15426 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15427 				"2707 Ring %d handler: Failed to allocate "
15428 				"iocb Rctl x%x Type x%x received\n",
15429 				LPFC_ELS_RING,
15430 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
15431 		return;
15432 	}
15433 	if (!lpfc_complete_unsol_iocb(phba,
15434 				      &phba->sli.ring[LPFC_ELS_RING],
15435 				      iocbq, fc_hdr->fh_r_ctl,
15436 				      fc_hdr->fh_type))
15437 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15438 				"2540 Ring %d handler: unexpected Rctl "
15439 				"x%x Type x%x received\n",
15440 				LPFC_ELS_RING,
15441 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
15442 
15443 	/* Free iocb created in lpfc_prep_seq */
15444 	list_for_each_entry_safe(curr_iocb, next_iocb,
15445 		&iocbq->list, list) {
15446 		list_del_init(&curr_iocb->list);
15447 		lpfc_sli_release_iocbq(phba, curr_iocb);
15448 	}
15449 	lpfc_sli_release_iocbq(phba, iocbq);
15450 }
15451 
15452 /**
15453  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
15454  * @phba: Pointer to HBA context object.
15455  *
15456  * This function is called with no lock held. This function processes all
15457  * the received buffers and gives it to upper layers when a received buffer
15458  * indicates that it is the final frame in the sequence. The interrupt
15459  * service routine processes received buffers at interrupt contexts and adds
15460  * received dma buffers to the rb_pend_list queue and signals the worker thread.
15461  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
15462  * appropriate receive function when the final frame in a sequence is received.
15463  **/
15464 void
15465 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
15466 				 struct hbq_dmabuf *dmabuf)
15467 {
15468 	struct hbq_dmabuf *seq_dmabuf;
15469 	struct fc_frame_header *fc_hdr;
15470 	struct lpfc_vport *vport;
15471 	uint32_t fcfi;
15472 	uint32_t did;
15473 
15474 	/* Process each received buffer */
15475 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
15476 	/* check to see if this a valid type of frame */
15477 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
15478 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
15479 		return;
15480 	}
15481 	if ((bf_get(lpfc_cqe_code,
15482 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
15483 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
15484 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
15485 	else
15486 		fcfi = bf_get(lpfc_rcqe_fcf_id,
15487 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
15488 
15489 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi);
15490 	if (!vport) {
15491 		/* throw out the frame */
15492 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
15493 		return;
15494 	}
15495 
15496 	/* d_id this frame is directed to */
15497 	did = sli4_did_from_fc_hdr(fc_hdr);
15498 
15499 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
15500 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
15501 		(did != Fabric_DID)) {
15502 		/*
15503 		 * Throw out the frame if we are not pt2pt.
15504 		 * The pt2pt protocol allows for discovery frames
15505 		 * to be received without a registered VPI.
15506 		 */
15507 		if (!(vport->fc_flag & FC_PT2PT) ||
15508 			(phba->link_state == LPFC_HBA_READY)) {
15509 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
15510 			return;
15511 		}
15512 	}
15513 
15514 	/* Handle the basic abort sequence (BA_ABTS) event */
15515 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
15516 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
15517 		return;
15518 	}
15519 
15520 	/* Link this frame */
15521 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
15522 	if (!seq_dmabuf) {
15523 		/* unable to add frame to vport - throw it out */
15524 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
15525 		return;
15526 	}
15527 	/* If not last frame in sequence continue processing frames. */
15528 	if (!lpfc_seq_complete(seq_dmabuf))
15529 		return;
15530 
15531 	/* Send the complete sequence to the upper layer protocol */
15532 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
15533 }
15534 
15535 /**
15536  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
15537  * @phba: pointer to lpfc hba data structure.
15538  *
15539  * This routine is invoked to post rpi header templates to the
15540  * HBA consistent with the SLI-4 interface spec.  This routine
15541  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
15542  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
15543  *
15544  * This routine does not require any locks.  It's usage is expected
15545  * to be driver load or reset recovery when the driver is
15546  * sequential.
15547  *
15548  * Return codes
15549  * 	0 - successful
15550  *      -EIO - The mailbox failed to complete successfully.
15551  * 	When this error occurs, the driver is not guaranteed
15552  *	to have any rpi regions posted to the device and
15553  *	must either attempt to repost the regions or take a
15554  *	fatal error.
15555  **/
15556 int
15557 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
15558 {
15559 	struct lpfc_rpi_hdr *rpi_page;
15560 	uint32_t rc = 0;
15561 	uint16_t lrpi = 0;
15562 
15563 	/* SLI4 ports that support extents do not require RPI headers. */
15564 	if (!phba->sli4_hba.rpi_hdrs_in_use)
15565 		goto exit;
15566 	if (phba->sli4_hba.extents_in_use)
15567 		return -EIO;
15568 
15569 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
15570 		/*
15571 		 * Assign the rpi headers a physical rpi only if the driver
15572 		 * has not initialized those resources.  A port reset only
15573 		 * needs the headers posted.
15574 		 */
15575 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
15576 		    LPFC_RPI_RSRC_RDY)
15577 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
15578 
15579 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
15580 		if (rc != MBX_SUCCESS) {
15581 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15582 					"2008 Error %d posting all rpi "
15583 					"headers\n", rc);
15584 			rc = -EIO;
15585 			break;
15586 		}
15587 	}
15588 
15589  exit:
15590 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
15591 	       LPFC_RPI_RSRC_RDY);
15592 	return rc;
15593 }
15594 
15595 /**
15596  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
15597  * @phba: pointer to lpfc hba data structure.
15598  * @rpi_page:  pointer to the rpi memory region.
15599  *
15600  * This routine is invoked to post a single rpi header to the
15601  * HBA consistent with the SLI-4 interface spec.  This memory region
15602  * maps up to 64 rpi context regions.
15603  *
15604  * Return codes
15605  * 	0 - successful
15606  * 	-ENOMEM - No available memory
15607  *      -EIO - The mailbox failed to complete successfully.
15608  **/
15609 int
15610 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
15611 {
15612 	LPFC_MBOXQ_t *mboxq;
15613 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
15614 	uint32_t rc = 0;
15615 	uint32_t shdr_status, shdr_add_status;
15616 	union lpfc_sli4_cfg_shdr *shdr;
15617 
15618 	/* SLI4 ports that support extents do not require RPI headers. */
15619 	if (!phba->sli4_hba.rpi_hdrs_in_use)
15620 		return rc;
15621 	if (phba->sli4_hba.extents_in_use)
15622 		return -EIO;
15623 
15624 	/* The port is notified of the header region via a mailbox command. */
15625 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15626 	if (!mboxq) {
15627 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15628 				"2001 Unable to allocate memory for issuing "
15629 				"SLI_CONFIG_SPECIAL mailbox command\n");
15630 		return -ENOMEM;
15631 	}
15632 
15633 	/* Post all rpi memory regions to the port. */
15634 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
15635 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
15636 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
15637 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
15638 			 sizeof(struct lpfc_sli4_cfg_mhdr),
15639 			 LPFC_SLI4_MBX_EMBED);
15640 
15641 
15642 	/* Post the physical rpi to the port for this rpi header. */
15643 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
15644 	       rpi_page->start_rpi);
15645 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
15646 	       hdr_tmpl, rpi_page->page_count);
15647 
15648 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
15649 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
15650 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
15651 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
15652 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15653 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15654 	if (rc != MBX_TIMEOUT)
15655 		mempool_free(mboxq, phba->mbox_mem_pool);
15656 	if (shdr_status || shdr_add_status || rc) {
15657 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15658 				"2514 POST_RPI_HDR mailbox failed with "
15659 				"status x%x add_status x%x, mbx status x%x\n",
15660 				shdr_status, shdr_add_status, rc);
15661 		rc = -ENXIO;
15662 	}
15663 	return rc;
15664 }
15665 
15666 /**
15667  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
15668  * @phba: pointer to lpfc hba data structure.
15669  *
15670  * This routine is invoked to post rpi header templates to the
15671  * HBA consistent with the SLI-4 interface spec.  This routine
15672  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
15673  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
15674  *
15675  * Returns
15676  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
15677  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
15678  **/
15679 int
15680 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
15681 {
15682 	unsigned long rpi;
15683 	uint16_t max_rpi, rpi_limit;
15684 	uint16_t rpi_remaining, lrpi = 0;
15685 	struct lpfc_rpi_hdr *rpi_hdr;
15686 	unsigned long iflag;
15687 
15688 	/*
15689 	 * Fetch the next logical rpi.  Because this index is logical,
15690 	 * the  driver starts at 0 each time.
15691 	 */
15692 	spin_lock_irqsave(&phba->hbalock, iflag);
15693 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
15694 	rpi_limit = phba->sli4_hba.next_rpi;
15695 
15696 	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
15697 	if (rpi >= rpi_limit)
15698 		rpi = LPFC_RPI_ALLOC_ERROR;
15699 	else {
15700 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
15701 		phba->sli4_hba.max_cfg_param.rpi_used++;
15702 		phba->sli4_hba.rpi_count++;
15703 	}
15704 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15705 			"0001 rpi:%x max:%x lim:%x\n",
15706 			(int) rpi, max_rpi, rpi_limit);
15707 
15708 	/*
15709 	 * Don't try to allocate more rpi header regions if the device limit
15710 	 * has been exhausted.
15711 	 */
15712 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
15713 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
15714 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15715 		return rpi;
15716 	}
15717 
15718 	/*
15719 	 * RPI header postings are not required for SLI4 ports capable of
15720 	 * extents.
15721 	 */
15722 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
15723 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15724 		return rpi;
15725 	}
15726 
15727 	/*
15728 	 * If the driver is running low on rpi resources, allocate another
15729 	 * page now.  Note that the next_rpi value is used because
15730 	 * it represents how many are actually in use whereas max_rpi notes
15731 	 * how many are supported max by the device.
15732 	 */
15733 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
15734 	spin_unlock_irqrestore(&phba->hbalock, iflag);
15735 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
15736 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
15737 		if (!rpi_hdr) {
15738 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15739 					"2002 Error Could not grow rpi "
15740 					"count\n");
15741 		} else {
15742 			lrpi = rpi_hdr->start_rpi;
15743 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
15744 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
15745 		}
15746 	}
15747 
15748 	return rpi;
15749 }
15750 
15751 /**
15752  * lpfc_sli4_free_rpi - Release an rpi for reuse.
15753  * @phba: pointer to lpfc hba data structure.
15754  *
15755  * This routine is invoked to release an rpi to the pool of
15756  * available rpis maintained by the driver.
15757  **/
15758 static void
15759 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
15760 {
15761 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
15762 		phba->sli4_hba.rpi_count--;
15763 		phba->sli4_hba.max_cfg_param.rpi_used--;
15764 	}
15765 }
15766 
15767 /**
15768  * lpfc_sli4_free_rpi - Release an rpi for reuse.
15769  * @phba: pointer to lpfc hba data structure.
15770  *
15771  * This routine is invoked to release an rpi to the pool of
15772  * available rpis maintained by the driver.
15773  **/
15774 void
15775 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
15776 {
15777 	spin_lock_irq(&phba->hbalock);
15778 	__lpfc_sli4_free_rpi(phba, rpi);
15779 	spin_unlock_irq(&phba->hbalock);
15780 }
15781 
15782 /**
15783  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
15784  * @phba: pointer to lpfc hba data structure.
15785  *
15786  * This routine is invoked to remove the memory region that
15787  * provided rpi via a bitmask.
15788  **/
15789 void
15790 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
15791 {
15792 	kfree(phba->sli4_hba.rpi_bmask);
15793 	kfree(phba->sli4_hba.rpi_ids);
15794 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
15795 }
15796 
15797 /**
15798  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
15799  * @phba: pointer to lpfc hba data structure.
15800  *
15801  * This routine is invoked to remove the memory region that
15802  * provided rpi via a bitmask.
15803  **/
15804 int
15805 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
15806 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
15807 {
15808 	LPFC_MBOXQ_t *mboxq;
15809 	struct lpfc_hba *phba = ndlp->phba;
15810 	int rc;
15811 
15812 	/* The port is notified of the header region via a mailbox command. */
15813 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15814 	if (!mboxq)
15815 		return -ENOMEM;
15816 
15817 	/* Post all rpi memory regions to the port. */
15818 	lpfc_resume_rpi(mboxq, ndlp);
15819 	if (cmpl) {
15820 		mboxq->mbox_cmpl = cmpl;
15821 		mboxq->context1 = arg;
15822 		mboxq->context2 = ndlp;
15823 	} else
15824 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15825 	mboxq->vport = ndlp->vport;
15826 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
15827 	if (rc == MBX_NOT_FINISHED) {
15828 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15829 				"2010 Resume RPI Mailbox failed "
15830 				"status %d, mbxStatus x%x\n", rc,
15831 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
15832 		mempool_free(mboxq, phba->mbox_mem_pool);
15833 		return -EIO;
15834 	}
15835 	return 0;
15836 }
15837 
15838 /**
15839  * lpfc_sli4_init_vpi - Initialize a vpi with the port
15840  * @vport: Pointer to the vport for which the vpi is being initialized
15841  *
15842  * This routine is invoked to activate a vpi with the port.
15843  *
15844  * Returns:
15845  *    0 success
15846  *    -Evalue otherwise
15847  **/
15848 int
15849 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
15850 {
15851 	LPFC_MBOXQ_t *mboxq;
15852 	int rc = 0;
15853 	int retval = MBX_SUCCESS;
15854 	uint32_t mbox_tmo;
15855 	struct lpfc_hba *phba = vport->phba;
15856 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15857 	if (!mboxq)
15858 		return -ENOMEM;
15859 	lpfc_init_vpi(phba, mboxq, vport->vpi);
15860 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
15861 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
15862 	if (rc != MBX_SUCCESS) {
15863 		lpfc_printf_vlog(vport, KERN_ERR, LOG_SLI,
15864 				"2022 INIT VPI Mailbox failed "
15865 				"status %d, mbxStatus x%x\n", rc,
15866 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
15867 		retval = -EIO;
15868 	}
15869 	if (rc != MBX_TIMEOUT)
15870 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
15871 
15872 	return retval;
15873 }
15874 
15875 /**
15876  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
15877  * @phba: pointer to lpfc hba data structure.
15878  * @mboxq: Pointer to mailbox object.
15879  *
15880  * This routine is invoked to manually add a single FCF record. The caller
15881  * must pass a completely initialized FCF_Record.  This routine takes
15882  * care of the nonembedded mailbox operations.
15883  **/
15884 static void
15885 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
15886 {
15887 	void *virt_addr;
15888 	union lpfc_sli4_cfg_shdr *shdr;
15889 	uint32_t shdr_status, shdr_add_status;
15890 
15891 	virt_addr = mboxq->sge_array->addr[0];
15892 	/* The IOCTL status is embedded in the mailbox subheader. */
15893 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
15894 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15895 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15896 
15897 	if ((shdr_status || shdr_add_status) &&
15898 		(shdr_status != STATUS_FCF_IN_USE))
15899 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15900 			"2558 ADD_FCF_RECORD mailbox failed with "
15901 			"status x%x add_status x%x\n",
15902 			shdr_status, shdr_add_status);
15903 
15904 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
15905 }
15906 
15907 /**
15908  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
15909  * @phba: pointer to lpfc hba data structure.
15910  * @fcf_record:  pointer to the initialized fcf record to add.
15911  *
15912  * This routine is invoked to manually add a single FCF record. The caller
15913  * must pass a completely initialized FCF_Record.  This routine takes
15914  * care of the nonembedded mailbox operations.
15915  **/
15916 int
15917 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
15918 {
15919 	int rc = 0;
15920 	LPFC_MBOXQ_t *mboxq;
15921 	uint8_t *bytep;
15922 	void *virt_addr;
15923 	dma_addr_t phys_addr;
15924 	struct lpfc_mbx_sge sge;
15925 	uint32_t alloc_len, req_len;
15926 	uint32_t fcfindex;
15927 
15928 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15929 	if (!mboxq) {
15930 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15931 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
15932 		return -ENOMEM;
15933 	}
15934 
15935 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
15936 		  sizeof(uint32_t);
15937 
15938 	/* Allocate DMA memory and set up the non-embedded mailbox command */
15939 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
15940 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
15941 				     req_len, LPFC_SLI4_MBX_NEMBED);
15942 	if (alloc_len < req_len) {
15943 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15944 			"2523 Allocated DMA memory size (x%x) is "
15945 			"less than the requested DMA memory "
15946 			"size (x%x)\n", alloc_len, req_len);
15947 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
15948 		return -ENOMEM;
15949 	}
15950 
15951 	/*
15952 	 * Get the first SGE entry from the non-embedded DMA memory.  This
15953 	 * routine only uses a single SGE.
15954 	 */
15955 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
15956 	phys_addr = getPaddr(sge.pa_hi, sge.pa_lo);
15957 	virt_addr = mboxq->sge_array->addr[0];
15958 	/*
15959 	 * Configure the FCF record for FCFI 0.  This is the driver's
15960 	 * hardcoded default and gets used in nonFIP mode.
15961 	 */
15962 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
15963 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
15964 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
15965 
15966 	/*
15967 	 * Copy the fcf_index and the FCF Record Data. The data starts after
15968 	 * the FCoE header plus word10. The data copy needs to be endian
15969 	 * correct.
15970 	 */
15971 	bytep += sizeof(uint32_t);
15972 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
15973 	mboxq->vport = phba->pport;
15974 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
15975 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
15976 	if (rc == MBX_NOT_FINISHED) {
15977 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15978 			"2515 ADD_FCF_RECORD mailbox failed with "
15979 			"status 0x%x\n", rc);
15980 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
15981 		rc = -EIO;
15982 	} else
15983 		rc = 0;
15984 
15985 	return rc;
15986 }
15987 
15988 /**
15989  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
15990  * @phba: pointer to lpfc hba data structure.
15991  * @fcf_record:  pointer to the fcf record to write the default data.
15992  * @fcf_index: FCF table entry index.
15993  *
15994  * This routine is invoked to build the driver's default FCF record.  The
15995  * values used are hardcoded.  This routine handles memory initialization.
15996  *
15997  **/
15998 void
15999 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
16000 				struct fcf_record *fcf_record,
16001 				uint16_t fcf_index)
16002 {
16003 	memset(fcf_record, 0, sizeof(struct fcf_record));
16004 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
16005 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
16006 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
16007 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
16008 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
16009 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
16010 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
16011 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
16012 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
16013 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
16014 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
16015 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
16016 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
16017 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
16018 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
16019 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
16020 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
16021 	/* Set the VLAN bit map */
16022 	if (phba->valid_vlan) {
16023 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
16024 			= 1 << (phba->vlan_id % 8);
16025 	}
16026 }
16027 
16028 /**
16029  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
16030  * @phba: pointer to lpfc hba data structure.
16031  * @fcf_index: FCF table entry offset.
16032  *
16033  * This routine is invoked to scan the entire FCF table by reading FCF
16034  * record and processing it one at a time starting from the @fcf_index
16035  * for initial FCF discovery or fast FCF failover rediscovery.
16036  *
16037  * Return 0 if the mailbox command is submitted successfully, none 0
16038  * otherwise.
16039  **/
16040 int
16041 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
16042 {
16043 	int rc = 0, error;
16044 	LPFC_MBOXQ_t *mboxq;
16045 
16046 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
16047 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
16048 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16049 	if (!mboxq) {
16050 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16051 				"2000 Failed to allocate mbox for "
16052 				"READ_FCF cmd\n");
16053 		error = -ENOMEM;
16054 		goto fail_fcf_scan;
16055 	}
16056 	/* Construct the read FCF record mailbox command */
16057 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
16058 	if (rc) {
16059 		error = -EINVAL;
16060 		goto fail_fcf_scan;
16061 	}
16062 	/* Issue the mailbox command asynchronously */
16063 	mboxq->vport = phba->pport;
16064 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
16065 
16066 	spin_lock_irq(&phba->hbalock);
16067 	phba->hba_flag |= FCF_TS_INPROG;
16068 	spin_unlock_irq(&phba->hbalock);
16069 
16070 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16071 	if (rc == MBX_NOT_FINISHED)
16072 		error = -EIO;
16073 	else {
16074 		/* Reset eligible FCF count for new scan */
16075 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
16076 			phba->fcf.eligible_fcf_cnt = 0;
16077 		error = 0;
16078 	}
16079 fail_fcf_scan:
16080 	if (error) {
16081 		if (mboxq)
16082 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
16083 		/* FCF scan failed, clear FCF_TS_INPROG flag */
16084 		spin_lock_irq(&phba->hbalock);
16085 		phba->hba_flag &= ~FCF_TS_INPROG;
16086 		spin_unlock_irq(&phba->hbalock);
16087 	}
16088 	return error;
16089 }
16090 
16091 /**
16092  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
16093  * @phba: pointer to lpfc hba data structure.
16094  * @fcf_index: FCF table entry offset.
16095  *
16096  * This routine is invoked to read an FCF record indicated by @fcf_index
16097  * and to use it for FLOGI roundrobin FCF failover.
16098  *
16099  * Return 0 if the mailbox command is submitted successfully, none 0
16100  * otherwise.
16101  **/
16102 int
16103 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
16104 {
16105 	int rc = 0, error;
16106 	LPFC_MBOXQ_t *mboxq;
16107 
16108 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16109 	if (!mboxq) {
16110 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
16111 				"2763 Failed to allocate mbox for "
16112 				"READ_FCF cmd\n");
16113 		error = -ENOMEM;
16114 		goto fail_fcf_read;
16115 	}
16116 	/* Construct the read FCF record mailbox command */
16117 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
16118 	if (rc) {
16119 		error = -EINVAL;
16120 		goto fail_fcf_read;
16121 	}
16122 	/* Issue the mailbox command asynchronously */
16123 	mboxq->vport = phba->pport;
16124 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
16125 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16126 	if (rc == MBX_NOT_FINISHED)
16127 		error = -EIO;
16128 	else
16129 		error = 0;
16130 
16131 fail_fcf_read:
16132 	if (error && mboxq)
16133 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16134 	return error;
16135 }
16136 
16137 /**
16138  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
16139  * @phba: pointer to lpfc hba data structure.
16140  * @fcf_index: FCF table entry offset.
16141  *
16142  * This routine is invoked to read an FCF record indicated by @fcf_index to
16143  * determine whether it's eligible for FLOGI roundrobin failover list.
16144  *
16145  * Return 0 if the mailbox command is submitted successfully, none 0
16146  * otherwise.
16147  **/
16148 int
16149 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
16150 {
16151 	int rc = 0, error;
16152 	LPFC_MBOXQ_t *mboxq;
16153 
16154 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16155 	if (!mboxq) {
16156 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
16157 				"2758 Failed to allocate mbox for "
16158 				"READ_FCF cmd\n");
16159 				error = -ENOMEM;
16160 				goto fail_fcf_read;
16161 	}
16162 	/* Construct the read FCF record mailbox command */
16163 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
16164 	if (rc) {
16165 		error = -EINVAL;
16166 		goto fail_fcf_read;
16167 	}
16168 	/* Issue the mailbox command asynchronously */
16169 	mboxq->vport = phba->pport;
16170 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
16171 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16172 	if (rc == MBX_NOT_FINISHED)
16173 		error = -EIO;
16174 	else
16175 		error = 0;
16176 
16177 fail_fcf_read:
16178 	if (error && mboxq)
16179 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16180 	return error;
16181 }
16182 
16183 /**
16184  * lpfc_check_next_fcf_pri
16185  * phba pointer to the lpfc_hba struct for this port.
16186  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
16187  * routine when the rr_bmask is empty. The FCF indecies are put into the
16188  * rr_bmask based on their priority level. Starting from the highest priority
16189  * to the lowest. The most likely FCF candidate will be in the highest
16190  * priority group. When this routine is called it searches the fcf_pri list for
16191  * next lowest priority group and repopulates the rr_bmask with only those
16192  * fcf_indexes.
16193  * returns:
16194  * 1=success 0=failure
16195  **/
16196 static int
16197 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
16198 {
16199 	uint16_t next_fcf_pri;
16200 	uint16_t last_index;
16201 	struct lpfc_fcf_pri *fcf_pri;
16202 	int rc;
16203 	int ret = 0;
16204 
16205 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
16206 			LPFC_SLI4_FCF_TBL_INDX_MAX);
16207 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16208 			"3060 Last IDX %d\n", last_index);
16209 
16210 	/* Verify the priority list has 2 or more entries */
16211 	spin_lock_irq(&phba->hbalock);
16212 	if (list_empty(&phba->fcf.fcf_pri_list) ||
16213 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
16214 		spin_unlock_irq(&phba->hbalock);
16215 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16216 			"3061 Last IDX %d\n", last_index);
16217 		return 0; /* Empty rr list */
16218 	}
16219 	spin_unlock_irq(&phba->hbalock);
16220 
16221 	next_fcf_pri = 0;
16222 	/*
16223 	 * Clear the rr_bmask and set all of the bits that are at this
16224 	 * priority.
16225 	 */
16226 	memset(phba->fcf.fcf_rr_bmask, 0,
16227 			sizeof(*phba->fcf.fcf_rr_bmask));
16228 	spin_lock_irq(&phba->hbalock);
16229 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
16230 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
16231 			continue;
16232 		/*
16233 		 * the 1st priority that has not FLOGI failed
16234 		 * will be the highest.
16235 		 */
16236 		if (!next_fcf_pri)
16237 			next_fcf_pri = fcf_pri->fcf_rec.priority;
16238 		spin_unlock_irq(&phba->hbalock);
16239 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
16240 			rc = lpfc_sli4_fcf_rr_index_set(phba,
16241 						fcf_pri->fcf_rec.fcf_index);
16242 			if (rc)
16243 				return 0;
16244 		}
16245 		spin_lock_irq(&phba->hbalock);
16246 	}
16247 	/*
16248 	 * if next_fcf_pri was not set above and the list is not empty then
16249 	 * we have failed flogis on all of them. So reset flogi failed
16250 	 * and start at the beginning.
16251 	 */
16252 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
16253 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
16254 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
16255 			/*
16256 			 * the 1st priority that has not FLOGI failed
16257 			 * will be the highest.
16258 			 */
16259 			if (!next_fcf_pri)
16260 				next_fcf_pri = fcf_pri->fcf_rec.priority;
16261 			spin_unlock_irq(&phba->hbalock);
16262 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
16263 				rc = lpfc_sli4_fcf_rr_index_set(phba,
16264 						fcf_pri->fcf_rec.fcf_index);
16265 				if (rc)
16266 					return 0;
16267 			}
16268 			spin_lock_irq(&phba->hbalock);
16269 		}
16270 	} else
16271 		ret = 1;
16272 	spin_unlock_irq(&phba->hbalock);
16273 
16274 	return ret;
16275 }
16276 /**
16277  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
16278  * @phba: pointer to lpfc hba data structure.
16279  *
16280  * This routine is to get the next eligible FCF record index in a round
16281  * robin fashion. If the next eligible FCF record index equals to the
16282  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
16283  * shall be returned, otherwise, the next eligible FCF record's index
16284  * shall be returned.
16285  **/
16286 uint16_t
16287 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
16288 {
16289 	uint16_t next_fcf_index;
16290 
16291 initial_priority:
16292 	/* Search start from next bit of currently registered FCF index */
16293 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
16294 
16295 next_priority:
16296 	/* Determine the next fcf index to check */
16297 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
16298 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
16299 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
16300 				       next_fcf_index);
16301 
16302 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
16303 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
16304 		/*
16305 		 * If we have wrapped then we need to clear the bits that
16306 		 * have been tested so that we can detect when we should
16307 		 * change the priority level.
16308 		 */
16309 		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
16310 					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
16311 	}
16312 
16313 
16314 	/* Check roundrobin failover list empty condition */
16315 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
16316 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
16317 		/*
16318 		 * If next fcf index is not found check if there are lower
16319 		 * Priority level fcf's in the fcf_priority list.
16320 		 * Set up the rr_bmask with all of the avaiable fcf bits
16321 		 * at that level and continue the selection process.
16322 		 */
16323 		if (lpfc_check_next_fcf_pri_level(phba))
16324 			goto initial_priority;
16325 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
16326 				"2844 No roundrobin failover FCF available\n");
16327 		if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX)
16328 			return LPFC_FCOE_FCF_NEXT_NONE;
16329 		else {
16330 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
16331 				"3063 Only FCF available idx %d, flag %x\n",
16332 				next_fcf_index,
16333 			phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag);
16334 			return next_fcf_index;
16335 		}
16336 	}
16337 
16338 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
16339 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
16340 		LPFC_FCF_FLOGI_FAILED)
16341 		goto next_priority;
16342 
16343 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16344 			"2845 Get next roundrobin failover FCF (x%x)\n",
16345 			next_fcf_index);
16346 
16347 	return next_fcf_index;
16348 }
16349 
16350 /**
16351  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
16352  * @phba: pointer to lpfc hba data structure.
16353  *
16354  * This routine sets the FCF record index in to the eligible bmask for
16355  * roundrobin failover search. It checks to make sure that the index
16356  * does not go beyond the range of the driver allocated bmask dimension
16357  * before setting the bit.
16358  *
16359  * Returns 0 if the index bit successfully set, otherwise, it returns
16360  * -EINVAL.
16361  **/
16362 int
16363 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
16364 {
16365 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
16366 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16367 				"2610 FCF (x%x) reached driver's book "
16368 				"keeping dimension:x%x\n",
16369 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
16370 		return -EINVAL;
16371 	}
16372 	/* Set the eligible FCF record index bmask */
16373 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
16374 
16375 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16376 			"2790 Set FCF (x%x) to roundrobin FCF failover "
16377 			"bmask\n", fcf_index);
16378 
16379 	return 0;
16380 }
16381 
16382 /**
16383  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
16384  * @phba: pointer to lpfc hba data structure.
16385  *
16386  * This routine clears the FCF record index from the eligible bmask for
16387  * roundrobin failover search. It checks to make sure that the index
16388  * does not go beyond the range of the driver allocated bmask dimension
16389  * before clearing the bit.
16390  **/
16391 void
16392 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
16393 {
16394 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
16395 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
16396 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16397 				"2762 FCF (x%x) reached driver's book "
16398 				"keeping dimension:x%x\n",
16399 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
16400 		return;
16401 	}
16402 	/* Clear the eligible FCF record index bmask */
16403 	spin_lock_irq(&phba->hbalock);
16404 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
16405 				 list) {
16406 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
16407 			list_del_init(&fcf_pri->list);
16408 			break;
16409 		}
16410 	}
16411 	spin_unlock_irq(&phba->hbalock);
16412 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
16413 
16414 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16415 			"2791 Clear FCF (x%x) from roundrobin failover "
16416 			"bmask\n", fcf_index);
16417 }
16418 
16419 /**
16420  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
16421  * @phba: pointer to lpfc hba data structure.
16422  *
16423  * This routine is the completion routine for the rediscover FCF table mailbox
16424  * command. If the mailbox command returned failure, it will try to stop the
16425  * FCF rediscover wait timer.
16426  **/
16427 static void
16428 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
16429 {
16430 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
16431 	uint32_t shdr_status, shdr_add_status;
16432 
16433 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
16434 
16435 	shdr_status = bf_get(lpfc_mbox_hdr_status,
16436 			     &redisc_fcf->header.cfg_shdr.response);
16437 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
16438 			     &redisc_fcf->header.cfg_shdr.response);
16439 	if (shdr_status || shdr_add_status) {
16440 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16441 				"2746 Requesting for FCF rediscovery failed "
16442 				"status x%x add_status x%x\n",
16443 				shdr_status, shdr_add_status);
16444 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
16445 			spin_lock_irq(&phba->hbalock);
16446 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
16447 			spin_unlock_irq(&phba->hbalock);
16448 			/*
16449 			 * CVL event triggered FCF rediscover request failed,
16450 			 * last resort to re-try current registered FCF entry.
16451 			 */
16452 			lpfc_retry_pport_discovery(phba);
16453 		} else {
16454 			spin_lock_irq(&phba->hbalock);
16455 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
16456 			spin_unlock_irq(&phba->hbalock);
16457 			/*
16458 			 * DEAD FCF event triggered FCF rediscover request
16459 			 * failed, last resort to fail over as a link down
16460 			 * to FCF registration.
16461 			 */
16462 			lpfc_sli4_fcf_dead_failthrough(phba);
16463 		}
16464 	} else {
16465 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16466 				"2775 Start FCF rediscover quiescent timer\n");
16467 		/*
16468 		 * Start FCF rediscovery wait timer for pending FCF
16469 		 * before rescan FCF record table.
16470 		 */
16471 		lpfc_fcf_redisc_wait_start_timer(phba);
16472 	}
16473 
16474 	mempool_free(mbox, phba->mbox_mem_pool);
16475 }
16476 
16477 /**
16478  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
16479  * @phba: pointer to lpfc hba data structure.
16480  *
16481  * This routine is invoked to request for rediscovery of the entire FCF table
16482  * by the port.
16483  **/
16484 int
16485 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
16486 {
16487 	LPFC_MBOXQ_t *mbox;
16488 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
16489 	int rc, length;
16490 
16491 	/* Cancel retry delay timers to all vports before FCF rediscover */
16492 	lpfc_cancel_all_vport_retry_delay_timer(phba);
16493 
16494 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16495 	if (!mbox) {
16496 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16497 				"2745 Failed to allocate mbox for "
16498 				"requesting FCF rediscover.\n");
16499 		return -ENOMEM;
16500 	}
16501 
16502 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
16503 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16504 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16505 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
16506 			 length, LPFC_SLI4_MBX_EMBED);
16507 
16508 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
16509 	/* Set count to 0 for invalidating the entire FCF database */
16510 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
16511 
16512 	/* Issue the mailbox command asynchronously */
16513 	mbox->vport = phba->pport;
16514 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
16515 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
16516 
16517 	if (rc == MBX_NOT_FINISHED) {
16518 		mempool_free(mbox, phba->mbox_mem_pool);
16519 		return -EIO;
16520 	}
16521 	return 0;
16522 }
16523 
16524 /**
16525  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
16526  * @phba: pointer to lpfc hba data structure.
16527  *
16528  * This function is the failover routine as a last resort to the FCF DEAD
16529  * event when driver failed to perform fast FCF failover.
16530  **/
16531 void
16532 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
16533 {
16534 	uint32_t link_state;
16535 
16536 	/*
16537 	 * Last resort as FCF DEAD event failover will treat this as
16538 	 * a link down, but save the link state because we don't want
16539 	 * it to be changed to Link Down unless it is already down.
16540 	 */
16541 	link_state = phba->link_state;
16542 	lpfc_linkdown(phba);
16543 	phba->link_state = link_state;
16544 
16545 	/* Unregister FCF if no devices connected to it */
16546 	lpfc_unregister_unused_fcf(phba);
16547 }
16548 
16549 /**
16550  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
16551  * @phba: pointer to lpfc hba data structure.
16552  * @rgn23_data: pointer to configure region 23 data.
16553  *
16554  * This function gets SLI3 port configure region 23 data through memory dump
16555  * mailbox command. When it successfully retrieves data, the size of the data
16556  * will be returned, otherwise, 0 will be returned.
16557  **/
16558 static uint32_t
16559 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
16560 {
16561 	LPFC_MBOXQ_t *pmb = NULL;
16562 	MAILBOX_t *mb;
16563 	uint32_t offset = 0;
16564 	int rc;
16565 
16566 	if (!rgn23_data)
16567 		return 0;
16568 
16569 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16570 	if (!pmb) {
16571 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16572 				"2600 failed to allocate mailbox memory\n");
16573 		return 0;
16574 	}
16575 	mb = &pmb->u.mb;
16576 
16577 	do {
16578 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
16579 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
16580 
16581 		if (rc != MBX_SUCCESS) {
16582 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16583 					"2601 failed to read config "
16584 					"region 23, rc 0x%x Status 0x%x\n",
16585 					rc, mb->mbxStatus);
16586 			mb->un.varDmp.word_cnt = 0;
16587 		}
16588 		/*
16589 		 * dump mem may return a zero when finished or we got a
16590 		 * mailbox error, either way we are done.
16591 		 */
16592 		if (mb->un.varDmp.word_cnt == 0)
16593 			break;
16594 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
16595 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
16596 
16597 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
16598 				       rgn23_data + offset,
16599 				       mb->un.varDmp.word_cnt);
16600 		offset += mb->un.varDmp.word_cnt;
16601 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
16602 
16603 	mempool_free(pmb, phba->mbox_mem_pool);
16604 	return offset;
16605 }
16606 
16607 /**
16608  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
16609  * @phba: pointer to lpfc hba data structure.
16610  * @rgn23_data: pointer to configure region 23 data.
16611  *
16612  * This function gets SLI4 port configure region 23 data through memory dump
16613  * mailbox command. When it successfully retrieves data, the size of the data
16614  * will be returned, otherwise, 0 will be returned.
16615  **/
16616 static uint32_t
16617 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
16618 {
16619 	LPFC_MBOXQ_t *mboxq = NULL;
16620 	struct lpfc_dmabuf *mp = NULL;
16621 	struct lpfc_mqe *mqe;
16622 	uint32_t data_length = 0;
16623 	int rc;
16624 
16625 	if (!rgn23_data)
16626 		return 0;
16627 
16628 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16629 	if (!mboxq) {
16630 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16631 				"3105 failed to allocate mailbox memory\n");
16632 		return 0;
16633 	}
16634 
16635 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
16636 		goto out;
16637 	mqe = &mboxq->u.mqe;
16638 	mp = (struct lpfc_dmabuf *) mboxq->context1;
16639 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
16640 	if (rc)
16641 		goto out;
16642 	data_length = mqe->un.mb_words[5];
16643 	if (data_length == 0)
16644 		goto out;
16645 	if (data_length > DMP_RGN23_SIZE) {
16646 		data_length = 0;
16647 		goto out;
16648 	}
16649 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
16650 out:
16651 	mempool_free(mboxq, phba->mbox_mem_pool);
16652 	if (mp) {
16653 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
16654 		kfree(mp);
16655 	}
16656 	return data_length;
16657 }
16658 
16659 /**
16660  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
16661  * @phba: pointer to lpfc hba data structure.
16662  *
16663  * This function read region 23 and parse TLV for port status to
16664  * decide if the user disaled the port. If the TLV indicates the
16665  * port is disabled, the hba_flag is set accordingly.
16666  **/
16667 void
16668 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
16669 {
16670 	uint8_t *rgn23_data = NULL;
16671 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
16672 	uint32_t offset = 0;
16673 
16674 	/* Get adapter Region 23 data */
16675 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
16676 	if (!rgn23_data)
16677 		goto out;
16678 
16679 	if (phba->sli_rev < LPFC_SLI_REV4)
16680 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
16681 	else {
16682 		if_type = bf_get(lpfc_sli_intf_if_type,
16683 				 &phba->sli4_hba.sli_intf);
16684 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
16685 			goto out;
16686 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
16687 	}
16688 
16689 	if (!data_size)
16690 		goto out;
16691 
16692 	/* Check the region signature first */
16693 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
16694 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16695 			"2619 Config region 23 has bad signature\n");
16696 			goto out;
16697 	}
16698 	offset += 4;
16699 
16700 	/* Check the data structure version */
16701 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
16702 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16703 			"2620 Config region 23 has bad version\n");
16704 		goto out;
16705 	}
16706 	offset += 4;
16707 
16708 	/* Parse TLV entries in the region */
16709 	while (offset < data_size) {
16710 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
16711 			break;
16712 		/*
16713 		 * If the TLV is not driver specific TLV or driver id is
16714 		 * not linux driver id, skip the record.
16715 		 */
16716 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
16717 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
16718 		    (rgn23_data[offset + 3] != 0)) {
16719 			offset += rgn23_data[offset + 1] * 4 + 4;
16720 			continue;
16721 		}
16722 
16723 		/* Driver found a driver specific TLV in the config region */
16724 		sub_tlv_len = rgn23_data[offset + 1] * 4;
16725 		offset += 4;
16726 		tlv_offset = 0;
16727 
16728 		/*
16729 		 * Search for configured port state sub-TLV.
16730 		 */
16731 		while ((offset < data_size) &&
16732 			(tlv_offset < sub_tlv_len)) {
16733 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
16734 				offset += 4;
16735 				tlv_offset += 4;
16736 				break;
16737 			}
16738 			if (rgn23_data[offset] != PORT_STE_TYPE) {
16739 				offset += rgn23_data[offset + 1] * 4 + 4;
16740 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
16741 				continue;
16742 			}
16743 
16744 			/* This HBA contains PORT_STE configured */
16745 			if (!rgn23_data[offset + 2])
16746 				phba->hba_flag |= LINK_DISABLED;
16747 
16748 			goto out;
16749 		}
16750 	}
16751 
16752 out:
16753 	kfree(rgn23_data);
16754 	return;
16755 }
16756 
16757 /**
16758  * lpfc_wr_object - write an object to the firmware
16759  * @phba: HBA structure that indicates port to create a queue on.
16760  * @dmabuf_list: list of dmabufs to write to the port.
16761  * @size: the total byte value of the objects to write to the port.
16762  * @offset: the current offset to be used to start the transfer.
16763  *
16764  * This routine will create a wr_object mailbox command to send to the port.
16765  * the mailbox command will be constructed using the dma buffers described in
16766  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
16767  * BDEs that the imbedded mailbox can support. The @offset variable will be
16768  * used to indicate the starting offset of the transfer and will also return
16769  * the offset after the write object mailbox has completed. @size is used to
16770  * determine the end of the object and whether the eof bit should be set.
16771  *
16772  * Return 0 is successful and offset will contain the the new offset to use
16773  * for the next write.
16774  * Return negative value for error cases.
16775  **/
16776 int
16777 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
16778 	       uint32_t size, uint32_t *offset)
16779 {
16780 	struct lpfc_mbx_wr_object *wr_object;
16781 	LPFC_MBOXQ_t *mbox;
16782 	int rc = 0, i = 0;
16783 	uint32_t shdr_status, shdr_add_status;
16784 	uint32_t mbox_tmo;
16785 	union lpfc_sli4_cfg_shdr *shdr;
16786 	struct lpfc_dmabuf *dmabuf;
16787 	uint32_t written = 0;
16788 
16789 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16790 	if (!mbox)
16791 		return -ENOMEM;
16792 
16793 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16794 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
16795 			sizeof(struct lpfc_mbx_wr_object) -
16796 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
16797 
16798 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
16799 	wr_object->u.request.write_offset = *offset;
16800 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
16801 	wr_object->u.request.object_name[0] =
16802 		cpu_to_le32(wr_object->u.request.object_name[0]);
16803 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
16804 	list_for_each_entry(dmabuf, dmabuf_list, list) {
16805 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
16806 			break;
16807 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
16808 		wr_object->u.request.bde[i].addrHigh =
16809 			putPaddrHigh(dmabuf->phys);
16810 		if (written + SLI4_PAGE_SIZE >= size) {
16811 			wr_object->u.request.bde[i].tus.f.bdeSize =
16812 				(size - written);
16813 			written += (size - written);
16814 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
16815 		} else {
16816 			wr_object->u.request.bde[i].tus.f.bdeSize =
16817 				SLI4_PAGE_SIZE;
16818 			written += SLI4_PAGE_SIZE;
16819 		}
16820 		i++;
16821 	}
16822 	wr_object->u.request.bde_count = i;
16823 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
16824 	if (!phba->sli4_hba.intr_enable)
16825 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16826 	else {
16827 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16828 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16829 	}
16830 	/* The IOCTL status is embedded in the mailbox subheader. */
16831 	shdr = (union lpfc_sli4_cfg_shdr *) &wr_object->header.cfg_shdr;
16832 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16833 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16834 	if (rc != MBX_TIMEOUT)
16835 		mempool_free(mbox, phba->mbox_mem_pool);
16836 	if (shdr_status || shdr_add_status || rc) {
16837 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16838 				"3025 Write Object mailbox failed with "
16839 				"status x%x add_status x%x, mbx status x%x\n",
16840 				shdr_status, shdr_add_status, rc);
16841 		rc = -ENXIO;
16842 	} else
16843 		*offset += wr_object->u.response.actual_write_length;
16844 	return rc;
16845 }
16846 
16847 /**
16848  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
16849  * @vport: pointer to vport data structure.
16850  *
16851  * This function iterate through the mailboxq and clean up all REG_LOGIN
16852  * and REG_VPI mailbox commands associated with the vport. This function
16853  * is called when driver want to restart discovery of the vport due to
16854  * a Clear Virtual Link event.
16855  **/
16856 void
16857 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
16858 {
16859 	struct lpfc_hba *phba = vport->phba;
16860 	LPFC_MBOXQ_t *mb, *nextmb;
16861 	struct lpfc_dmabuf *mp;
16862 	struct lpfc_nodelist *ndlp;
16863 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
16864 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
16865 	LIST_HEAD(mbox_cmd_list);
16866 	uint8_t restart_loop;
16867 
16868 	/* Clean up internally queued mailbox commands with the vport */
16869 	spin_lock_irq(&phba->hbalock);
16870 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
16871 		if (mb->vport != vport)
16872 			continue;
16873 
16874 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
16875 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
16876 			continue;
16877 
16878 		list_del(&mb->list);
16879 		list_add_tail(&mb->list, &mbox_cmd_list);
16880 	}
16881 	/* Clean up active mailbox command with the vport */
16882 	mb = phba->sli.mbox_active;
16883 	if (mb && (mb->vport == vport)) {
16884 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
16885 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
16886 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16887 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
16888 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->context2;
16889 			/* Put reference count for delayed processing */
16890 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
16891 			/* Unregister the RPI when mailbox complete */
16892 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
16893 		}
16894 	}
16895 	/* Cleanup any mailbox completions which are not yet processed */
16896 	do {
16897 		restart_loop = 0;
16898 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
16899 			/*
16900 			 * If this mailox is already processed or it is
16901 			 * for another vport ignore it.
16902 			 */
16903 			if ((mb->vport != vport) ||
16904 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
16905 				continue;
16906 
16907 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
16908 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
16909 				continue;
16910 
16911 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16912 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
16913 				ndlp = (struct lpfc_nodelist *)mb->context2;
16914 				/* Unregister the RPI when mailbox complete */
16915 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
16916 				restart_loop = 1;
16917 				spin_unlock_irq(&phba->hbalock);
16918 				spin_lock(shost->host_lock);
16919 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
16920 				spin_unlock(shost->host_lock);
16921 				spin_lock_irq(&phba->hbalock);
16922 				break;
16923 			}
16924 		}
16925 	} while (restart_loop);
16926 
16927 	spin_unlock_irq(&phba->hbalock);
16928 
16929 	/* Release the cleaned-up mailbox commands */
16930 	while (!list_empty(&mbox_cmd_list)) {
16931 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
16932 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
16933 			mp = (struct lpfc_dmabuf *) (mb->context1);
16934 			if (mp) {
16935 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
16936 				kfree(mp);
16937 			}
16938 			ndlp = (struct lpfc_nodelist *) mb->context2;
16939 			mb->context2 = NULL;
16940 			if (ndlp) {
16941 				spin_lock(shost->host_lock);
16942 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
16943 				spin_unlock(shost->host_lock);
16944 				lpfc_nlp_put(ndlp);
16945 			}
16946 		}
16947 		mempool_free(mb, phba->mbox_mem_pool);
16948 	}
16949 
16950 	/* Release the ndlp with the cleaned-up active mailbox command */
16951 	if (act_mbx_ndlp) {
16952 		spin_lock(shost->host_lock);
16953 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
16954 		spin_unlock(shost->host_lock);
16955 		lpfc_nlp_put(act_mbx_ndlp);
16956 	}
16957 }
16958 
16959 /**
16960  * lpfc_drain_txq - Drain the txq
16961  * @phba: Pointer to HBA context object.
16962  *
16963  * This function attempt to submit IOCBs on the txq
16964  * to the adapter.  For SLI4 adapters, the txq contains
16965  * ELS IOCBs that have been deferred because the there
16966  * are no SGLs.  This congestion can occur with large
16967  * vport counts during node discovery.
16968  **/
16969 
16970 uint32_t
16971 lpfc_drain_txq(struct lpfc_hba *phba)
16972 {
16973 	LIST_HEAD(completions);
16974 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
16975 	struct lpfc_iocbq *piocbq = NULL;
16976 	unsigned long iflags = 0;
16977 	char *fail_msg = NULL;
16978 	struct lpfc_sglq *sglq;
16979 	union lpfc_wqe wqe;
16980 	uint32_t txq_cnt = 0;
16981 
16982 	spin_lock_irqsave(&pring->ring_lock, iflags);
16983 	list_for_each_entry(piocbq, &pring->txq, list) {
16984 		txq_cnt++;
16985 	}
16986 
16987 	if (txq_cnt > pring->txq_max)
16988 		pring->txq_max = txq_cnt;
16989 
16990 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
16991 
16992 	while (!list_empty(&pring->txq)) {
16993 		spin_lock_irqsave(&pring->ring_lock, iflags);
16994 
16995 		piocbq = lpfc_sli_ringtx_get(phba, pring);
16996 		if (!piocbq) {
16997 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
16998 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16999 				"2823 txq empty and txq_cnt is %d\n ",
17000 				txq_cnt);
17001 			break;
17002 		}
17003 		sglq = __lpfc_sli_get_sglq(phba, piocbq);
17004 		if (!sglq) {
17005 			__lpfc_sli_ringtx_put(phba, pring, piocbq);
17006 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
17007 			break;
17008 		}
17009 		txq_cnt--;
17010 
17011 		/* The xri and iocb resources secured,
17012 		 * attempt to issue request
17013 		 */
17014 		piocbq->sli4_lxritag = sglq->sli4_lxritag;
17015 		piocbq->sli4_xritag = sglq->sli4_xritag;
17016 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
17017 			fail_msg = "to convert bpl to sgl";
17018 		else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
17019 			fail_msg = "to convert iocb to wqe";
17020 		else if (lpfc_sli4_wq_put(phba->sli4_hba.els_wq, &wqe))
17021 			fail_msg = " - Wq is full";
17022 		else
17023 			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
17024 
17025 		if (fail_msg) {
17026 			/* Failed means we can't issue and need to cancel */
17027 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17028 					"2822 IOCB failed %s iotag 0x%x "
17029 					"xri 0x%x\n",
17030 					fail_msg,
17031 					piocbq->iotag, piocbq->sli4_xritag);
17032 			list_add_tail(&piocbq->list, &completions);
17033 		}
17034 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
17035 	}
17036 
17037 	/* Cancel all the IOCBs that cannot be issued */
17038 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
17039 				IOERR_SLI_ABORTED);
17040 
17041 	return txq_cnt;
17042 }
17043