xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision 0883c2c0)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2004-2016 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 #include <linux/lockdep.h>
28 
29 #include <scsi/scsi.h>
30 #include <scsi/scsi_cmnd.h>
31 #include <scsi/scsi_device.h>
32 #include <scsi/scsi_host.h>
33 #include <scsi/scsi_transport_fc.h>
34 #include <scsi/fc/fc_fs.h>
35 #include <linux/aer.h>
36 
37 #include "lpfc_hw4.h"
38 #include "lpfc_hw.h"
39 #include "lpfc_sli.h"
40 #include "lpfc_sli4.h"
41 #include "lpfc_nl.h"
42 #include "lpfc_disc.h"
43 #include "lpfc_scsi.h"
44 #include "lpfc.h"
45 #include "lpfc_crtn.h"
46 #include "lpfc_logmsg.h"
47 #include "lpfc_compat.h"
48 #include "lpfc_debugfs.h"
49 #include "lpfc_vport.h"
50 
51 /* There are only four IOCB completion types. */
52 typedef enum _lpfc_iocb_type {
53 	LPFC_UNKNOWN_IOCB,
54 	LPFC_UNSOL_IOCB,
55 	LPFC_SOL_IOCB,
56 	LPFC_ABORT_IOCB
57 } lpfc_iocb_type;
58 
59 
60 /* Provide function prototypes local to this module. */
61 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
62 				  uint32_t);
63 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
64 			      uint8_t *, uint32_t *);
65 static struct lpfc_iocbq *lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *,
66 							 struct lpfc_iocbq *);
67 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
68 				      struct hbq_dmabuf *);
69 static int lpfc_sli4_fp_handle_wcqe(struct lpfc_hba *, struct lpfc_queue *,
70 				    struct lpfc_cqe *);
71 static int lpfc_sli4_post_els_sgl_list(struct lpfc_hba *, struct list_head *,
72 				       int);
73 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *, struct lpfc_eqe *,
74 			uint32_t);
75 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
76 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
77 
78 static IOCB_t *
79 lpfc_get_iocb_from_iocbq(struct lpfc_iocbq *iocbq)
80 {
81 	return &iocbq->iocb;
82 }
83 
84 /**
85  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
86  * @q: The Work Queue to operate on.
87  * @wqe: The work Queue Entry to put on the Work queue.
88  *
89  * This routine will copy the contents of @wqe to the next available entry on
90  * the @q. This function will then ring the Work Queue Doorbell to signal the
91  * HBA to start processing the Work Queue Entry. This function returns 0 if
92  * successful. If no entries are available on @q then this function will return
93  * -ENOMEM.
94  * The caller is expected to hold the hbalock when calling this routine.
95  **/
96 static uint32_t
97 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe *wqe)
98 {
99 	union lpfc_wqe *temp_wqe;
100 	struct lpfc_register doorbell;
101 	uint32_t host_index;
102 	uint32_t idx;
103 
104 	/* sanity check on queue memory */
105 	if (unlikely(!q))
106 		return -ENOMEM;
107 	temp_wqe = q->qe[q->host_index].wqe;
108 
109 	/* If the host has not yet processed the next entry then we are done */
110 	idx = ((q->host_index + 1) % q->entry_count);
111 	if (idx == q->hba_index) {
112 		q->WQ_overflow++;
113 		return -ENOMEM;
114 	}
115 	q->WQ_posted++;
116 	/* set consumption flag every once in a while */
117 	if (!((q->host_index + 1) % q->entry_repost))
118 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
119 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
120 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
121 	lpfc_sli_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
122 
123 	/* Update the host index before invoking device */
124 	host_index = q->host_index;
125 
126 	q->host_index = idx;
127 
128 	/* Ring Doorbell */
129 	doorbell.word0 = 0;
130 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
131 		bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
132 		bf_set(lpfc_wq_db_list_fm_index, &doorbell, host_index);
133 		bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
134 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
135 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
136 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
137 	} else {
138 		return -EINVAL;
139 	}
140 	writel(doorbell.word0, q->db_regaddr);
141 
142 	return 0;
143 }
144 
145 /**
146  * lpfc_sli4_wq_release - Updates internal hba index for WQ
147  * @q: The Work Queue to operate on.
148  * @index: The index to advance the hba index to.
149  *
150  * This routine will update the HBA index of a queue to reflect consumption of
151  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
152  * an entry the host calls this function to update the queue's internal
153  * pointers. This routine returns the number of entries that were consumed by
154  * the HBA.
155  **/
156 static uint32_t
157 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
158 {
159 	uint32_t released = 0;
160 
161 	/* sanity check on queue memory */
162 	if (unlikely(!q))
163 		return 0;
164 
165 	if (q->hba_index == index)
166 		return 0;
167 	do {
168 		q->hba_index = ((q->hba_index + 1) % q->entry_count);
169 		released++;
170 	} while (q->hba_index != index);
171 	return released;
172 }
173 
174 /**
175  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
176  * @q: The Mailbox Queue to operate on.
177  * @wqe: The Mailbox Queue Entry to put on the Work queue.
178  *
179  * This routine will copy the contents of @mqe to the next available entry on
180  * the @q. This function will then ring the Work Queue Doorbell to signal the
181  * HBA to start processing the Work Queue Entry. This function returns 0 if
182  * successful. If no entries are available on @q then this function will return
183  * -ENOMEM.
184  * The caller is expected to hold the hbalock when calling this routine.
185  **/
186 static uint32_t
187 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
188 {
189 	struct lpfc_mqe *temp_mqe;
190 	struct lpfc_register doorbell;
191 
192 	/* sanity check on queue memory */
193 	if (unlikely(!q))
194 		return -ENOMEM;
195 	temp_mqe = q->qe[q->host_index].mqe;
196 
197 	/* If the host has not yet processed the next entry then we are done */
198 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
199 		return -ENOMEM;
200 	lpfc_sli_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
201 	/* Save off the mailbox pointer for completion */
202 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
203 
204 	/* Update the host index before invoking device */
205 	q->host_index = ((q->host_index + 1) % q->entry_count);
206 
207 	/* Ring Doorbell */
208 	doorbell.word0 = 0;
209 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
210 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
211 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
212 	return 0;
213 }
214 
215 /**
216  * lpfc_sli4_mq_release - Updates internal hba index for MQ
217  * @q: The Mailbox Queue to operate on.
218  *
219  * This routine will update the HBA index of a queue to reflect consumption of
220  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
221  * an entry the host calls this function to update the queue's internal
222  * pointers. This routine returns the number of entries that were consumed by
223  * the HBA.
224  **/
225 static uint32_t
226 lpfc_sli4_mq_release(struct lpfc_queue *q)
227 {
228 	/* sanity check on queue memory */
229 	if (unlikely(!q))
230 		return 0;
231 
232 	/* Clear the mailbox pointer for completion */
233 	q->phba->mbox = NULL;
234 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
235 	return 1;
236 }
237 
238 /**
239  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
240  * @q: The Event Queue to get the first valid EQE from
241  *
242  * This routine will get the first valid Event Queue Entry from @q, update
243  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
244  * the Queue (no more work to do), or the Queue is full of EQEs that have been
245  * processed, but not popped back to the HBA then this routine will return NULL.
246  **/
247 static struct lpfc_eqe *
248 lpfc_sli4_eq_get(struct lpfc_queue *q)
249 {
250 	struct lpfc_eqe *eqe;
251 	uint32_t idx;
252 
253 	/* sanity check on queue memory */
254 	if (unlikely(!q))
255 		return NULL;
256 	eqe = q->qe[q->hba_index].eqe;
257 
258 	/* If the next EQE is not valid then we are done */
259 	if (!bf_get_le32(lpfc_eqe_valid, eqe))
260 		return NULL;
261 	/* If the host has not yet processed the next entry then we are done */
262 	idx = ((q->hba_index + 1) % q->entry_count);
263 	if (idx == q->host_index)
264 		return NULL;
265 
266 	q->hba_index = idx;
267 
268 	/*
269 	 * insert barrier for instruction interlock : data from the hardware
270 	 * must have the valid bit checked before it can be copied and acted
271 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
272 	 * instructions allowing action on content before valid bit checked,
273 	 * add barrier here as well. May not be needed as "content" is a
274 	 * single 32-bit entity here (vs multi word structure for cq's).
275 	 */
276 	mb();
277 	return eqe;
278 }
279 
280 /**
281  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
282  * @q: The Event Queue to disable interrupts
283  *
284  **/
285 static inline void
286 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
287 {
288 	struct lpfc_register doorbell;
289 
290 	doorbell.word0 = 0;
291 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
292 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
293 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
294 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
295 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
296 	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
297 }
298 
299 /**
300  * lpfc_sli4_eq_release - Indicates the host has finished processing an EQ
301  * @q: The Event Queue that the host has completed processing for.
302  * @arm: Indicates whether the host wants to arms this CQ.
303  *
304  * This routine will mark all Event Queue Entries on @q, from the last
305  * known completed entry to the last entry that was processed, as completed
306  * by clearing the valid bit for each completion queue entry. Then it will
307  * notify the HBA, by ringing the doorbell, that the EQEs have been processed.
308  * The internal host index in the @q will be updated by this routine to indicate
309  * that the host has finished processing the entries. The @arm parameter
310  * indicates that the queue should be rearmed when ringing the doorbell.
311  *
312  * This function will return the number of EQEs that were popped.
313  **/
314 uint32_t
315 lpfc_sli4_eq_release(struct lpfc_queue *q, bool arm)
316 {
317 	uint32_t released = 0;
318 	struct lpfc_eqe *temp_eqe;
319 	struct lpfc_register doorbell;
320 
321 	/* sanity check on queue memory */
322 	if (unlikely(!q))
323 		return 0;
324 
325 	/* while there are valid entries */
326 	while (q->hba_index != q->host_index) {
327 		temp_eqe = q->qe[q->host_index].eqe;
328 		bf_set_le32(lpfc_eqe_valid, temp_eqe, 0);
329 		released++;
330 		q->host_index = ((q->host_index + 1) % q->entry_count);
331 	}
332 	if (unlikely(released == 0 && !arm))
333 		return 0;
334 
335 	/* ring doorbell for number popped */
336 	doorbell.word0 = 0;
337 	if (arm) {
338 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
339 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
340 	}
341 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, released);
342 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
343 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
344 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
345 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
346 	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
347 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
348 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
349 		readl(q->phba->sli4_hba.EQCQDBregaddr);
350 	return released;
351 }
352 
353 /**
354  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
355  * @q: The Completion Queue to get the first valid CQE from
356  *
357  * This routine will get the first valid Completion Queue Entry from @q, update
358  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
359  * the Queue (no more work to do), or the Queue is full of CQEs that have been
360  * processed, but not popped back to the HBA then this routine will return NULL.
361  **/
362 static struct lpfc_cqe *
363 lpfc_sli4_cq_get(struct lpfc_queue *q)
364 {
365 	struct lpfc_cqe *cqe;
366 	uint32_t idx;
367 
368 	/* sanity check on queue memory */
369 	if (unlikely(!q))
370 		return NULL;
371 
372 	/* If the next CQE is not valid then we are done */
373 	if (!bf_get_le32(lpfc_cqe_valid, q->qe[q->hba_index].cqe))
374 		return NULL;
375 	/* If the host has not yet processed the next entry then we are done */
376 	idx = ((q->hba_index + 1) % q->entry_count);
377 	if (idx == q->host_index)
378 		return NULL;
379 
380 	cqe = q->qe[q->hba_index].cqe;
381 	q->hba_index = idx;
382 
383 	/*
384 	 * insert barrier for instruction interlock : data from the hardware
385 	 * must have the valid bit checked before it can be copied and acted
386 	 * upon. Speculative instructions were allowing a bcopy at the start
387 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
388 	 * after our return, to copy data before the valid bit check above
389 	 * was done. As such, some of the copied data was stale. The barrier
390 	 * ensures the check is before any data is copied.
391 	 */
392 	mb();
393 	return cqe;
394 }
395 
396 /**
397  * lpfc_sli4_cq_release - Indicates the host has finished processing a CQ
398  * @q: The Completion Queue that the host has completed processing for.
399  * @arm: Indicates whether the host wants to arms this CQ.
400  *
401  * This routine will mark all Completion queue entries on @q, from the last
402  * known completed entry to the last entry that was processed, as completed
403  * by clearing the valid bit for each completion queue entry. Then it will
404  * notify the HBA, by ringing the doorbell, that the CQEs have been processed.
405  * The internal host index in the @q will be updated by this routine to indicate
406  * that the host has finished processing the entries. The @arm parameter
407  * indicates that the queue should be rearmed when ringing the doorbell.
408  *
409  * This function will return the number of CQEs that were released.
410  **/
411 uint32_t
412 lpfc_sli4_cq_release(struct lpfc_queue *q, bool arm)
413 {
414 	uint32_t released = 0;
415 	struct lpfc_cqe *temp_qe;
416 	struct lpfc_register doorbell;
417 
418 	/* sanity check on queue memory */
419 	if (unlikely(!q))
420 		return 0;
421 	/* while there are valid entries */
422 	while (q->hba_index != q->host_index) {
423 		temp_qe = q->qe[q->host_index].cqe;
424 		bf_set_le32(lpfc_cqe_valid, temp_qe, 0);
425 		released++;
426 		q->host_index = ((q->host_index + 1) % q->entry_count);
427 	}
428 	if (unlikely(released == 0 && !arm))
429 		return 0;
430 
431 	/* ring doorbell for number popped */
432 	doorbell.word0 = 0;
433 	if (arm)
434 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
435 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, released);
436 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
437 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
438 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
439 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
440 	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
441 	return released;
442 }
443 
444 /**
445  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
446  * @q: The Header Receive Queue to operate on.
447  * @wqe: The Receive Queue Entry to put on the Receive queue.
448  *
449  * This routine will copy the contents of @wqe to the next available entry on
450  * the @q. This function will then ring the Receive Queue Doorbell to signal the
451  * HBA to start processing the Receive Queue Entry. This function returns the
452  * index that the rqe was copied to if successful. If no entries are available
453  * on @q then this function will return -ENOMEM.
454  * The caller is expected to hold the hbalock when calling this routine.
455  **/
456 static int
457 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
458 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
459 {
460 	struct lpfc_rqe *temp_hrqe;
461 	struct lpfc_rqe *temp_drqe;
462 	struct lpfc_register doorbell;
463 	int put_index;
464 
465 	/* sanity check on queue memory */
466 	if (unlikely(!hq) || unlikely(!dq))
467 		return -ENOMEM;
468 	put_index = hq->host_index;
469 	temp_hrqe = hq->qe[hq->host_index].rqe;
470 	temp_drqe = dq->qe[dq->host_index].rqe;
471 
472 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
473 		return -EINVAL;
474 	if (hq->host_index != dq->host_index)
475 		return -EINVAL;
476 	/* If the host has not yet processed the next entry then we are done */
477 	if (((hq->host_index + 1) % hq->entry_count) == hq->hba_index)
478 		return -EBUSY;
479 	lpfc_sli_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
480 	lpfc_sli_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
481 
482 	/* Update the host index to point to the next slot */
483 	hq->host_index = ((hq->host_index + 1) % hq->entry_count);
484 	dq->host_index = ((dq->host_index + 1) % dq->entry_count);
485 
486 	/* Ring The Header Receive Queue Doorbell */
487 	if (!(hq->host_index % hq->entry_repost)) {
488 		doorbell.word0 = 0;
489 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
490 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
491 			       hq->entry_repost);
492 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
493 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
494 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
495 			       hq->entry_repost);
496 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
497 			       hq->host_index);
498 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
499 		} else {
500 			return -EINVAL;
501 		}
502 		writel(doorbell.word0, hq->db_regaddr);
503 	}
504 	return put_index;
505 }
506 
507 /**
508  * lpfc_sli4_rq_release - Updates internal hba index for RQ
509  * @q: The Header Receive Queue to operate on.
510  *
511  * This routine will update the HBA index of a queue to reflect consumption of
512  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
513  * consumed an entry the host calls this function to update the queue's
514  * internal pointers. This routine returns the number of entries that were
515  * consumed by the HBA.
516  **/
517 static uint32_t
518 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
519 {
520 	/* sanity check on queue memory */
521 	if (unlikely(!hq) || unlikely(!dq))
522 		return 0;
523 
524 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
525 		return 0;
526 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
527 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
528 	return 1;
529 }
530 
531 /**
532  * lpfc_cmd_iocb - Get next command iocb entry in the ring
533  * @phba: Pointer to HBA context object.
534  * @pring: Pointer to driver SLI ring object.
535  *
536  * This function returns pointer to next command iocb entry
537  * in the command ring. The caller must hold hbalock to prevent
538  * other threads consume the next command iocb.
539  * SLI-2/SLI-3 provide different sized iocbs.
540  **/
541 static inline IOCB_t *
542 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
543 {
544 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
545 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
546 }
547 
548 /**
549  * lpfc_resp_iocb - Get next response iocb entry in the ring
550  * @phba: Pointer to HBA context object.
551  * @pring: Pointer to driver SLI ring object.
552  *
553  * This function returns pointer to next response iocb entry
554  * in the response ring. The caller must hold hbalock to make sure
555  * that no other thread consume the next response iocb.
556  * SLI-2/SLI-3 provide different sized iocbs.
557  **/
558 static inline IOCB_t *
559 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
560 {
561 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
562 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
563 }
564 
565 /**
566  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
567  * @phba: Pointer to HBA context object.
568  *
569  * This function is called with hbalock held. This function
570  * allocates a new driver iocb object from the iocb pool. If the
571  * allocation is successful, it returns pointer to the newly
572  * allocated iocb object else it returns NULL.
573  **/
574 struct lpfc_iocbq *
575 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
576 {
577 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
578 	struct lpfc_iocbq * iocbq = NULL;
579 
580 	lockdep_assert_held(&phba->hbalock);
581 
582 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
583 	if (iocbq)
584 		phba->iocb_cnt++;
585 	if (phba->iocb_cnt > phba->iocb_max)
586 		phba->iocb_max = phba->iocb_cnt;
587 	return iocbq;
588 }
589 
590 /**
591  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
592  * @phba: Pointer to HBA context object.
593  * @xritag: XRI value.
594  *
595  * This function clears the sglq pointer from the array of acive
596  * sglq's. The xritag that is passed in is used to index into the
597  * array. Before the xritag can be used it needs to be adjusted
598  * by subtracting the xribase.
599  *
600  * Returns sglq ponter = success, NULL = Failure.
601  **/
602 static struct lpfc_sglq *
603 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
604 {
605 	struct lpfc_sglq *sglq;
606 
607 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
608 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
609 	return sglq;
610 }
611 
612 /**
613  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
614  * @phba: Pointer to HBA context object.
615  * @xritag: XRI value.
616  *
617  * This function returns the sglq pointer from the array of acive
618  * sglq's. The xritag that is passed in is used to index into the
619  * array. Before the xritag can be used it needs to be adjusted
620  * by subtracting the xribase.
621  *
622  * Returns sglq ponter = success, NULL = Failure.
623  **/
624 struct lpfc_sglq *
625 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
626 {
627 	struct lpfc_sglq *sglq;
628 
629 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
630 	return sglq;
631 }
632 
633 /**
634  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
635  * @phba: Pointer to HBA context object.
636  * @xritag: xri used in this exchange.
637  * @rrq: The RRQ to be cleared.
638  *
639  **/
640 void
641 lpfc_clr_rrq_active(struct lpfc_hba *phba,
642 		    uint16_t xritag,
643 		    struct lpfc_node_rrq *rrq)
644 {
645 	struct lpfc_nodelist *ndlp = NULL;
646 
647 	if ((rrq->vport) && NLP_CHK_NODE_ACT(rrq->ndlp))
648 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
649 
650 	/* The target DID could have been swapped (cable swap)
651 	 * we should use the ndlp from the findnode if it is
652 	 * available.
653 	 */
654 	if ((!ndlp) && rrq->ndlp)
655 		ndlp = rrq->ndlp;
656 
657 	if (!ndlp)
658 		goto out;
659 
660 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
661 		rrq->send_rrq = 0;
662 		rrq->xritag = 0;
663 		rrq->rrq_stop_time = 0;
664 	}
665 out:
666 	mempool_free(rrq, phba->rrq_pool);
667 }
668 
669 /**
670  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
671  * @phba: Pointer to HBA context object.
672  *
673  * This function is called with hbalock held. This function
674  * Checks if stop_time (ratov from setting rrq active) has
675  * been reached, if it has and the send_rrq flag is set then
676  * it will call lpfc_send_rrq. If the send_rrq flag is not set
677  * then it will just call the routine to clear the rrq and
678  * free the rrq resource.
679  * The timer is set to the next rrq that is going to expire before
680  * leaving the routine.
681  *
682  **/
683 void
684 lpfc_handle_rrq_active(struct lpfc_hba *phba)
685 {
686 	struct lpfc_node_rrq *rrq;
687 	struct lpfc_node_rrq *nextrrq;
688 	unsigned long next_time;
689 	unsigned long iflags;
690 	LIST_HEAD(send_rrq);
691 
692 	spin_lock_irqsave(&phba->hbalock, iflags);
693 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
694 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
695 	list_for_each_entry_safe(rrq, nextrrq,
696 				 &phba->active_rrq_list, list) {
697 		if (time_after(jiffies, rrq->rrq_stop_time))
698 			list_move(&rrq->list, &send_rrq);
699 		else if (time_before(rrq->rrq_stop_time, next_time))
700 			next_time = rrq->rrq_stop_time;
701 	}
702 	spin_unlock_irqrestore(&phba->hbalock, iflags);
703 	if ((!list_empty(&phba->active_rrq_list)) &&
704 	    (!(phba->pport->load_flag & FC_UNLOADING)))
705 		mod_timer(&phba->rrq_tmr, next_time);
706 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
707 		list_del(&rrq->list);
708 		if (!rrq->send_rrq)
709 			/* this call will free the rrq */
710 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
711 		else if (lpfc_send_rrq(phba, rrq)) {
712 			/* if we send the rrq then the completion handler
713 			*  will clear the bit in the xribitmap.
714 			*/
715 			lpfc_clr_rrq_active(phba, rrq->xritag,
716 					    rrq);
717 		}
718 	}
719 }
720 
721 /**
722  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
723  * @vport: Pointer to vport context object.
724  * @xri: The xri used in the exchange.
725  * @did: The targets DID for this exchange.
726  *
727  * returns NULL = rrq not found in the phba->active_rrq_list.
728  *         rrq = rrq for this xri and target.
729  **/
730 struct lpfc_node_rrq *
731 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
732 {
733 	struct lpfc_hba *phba = vport->phba;
734 	struct lpfc_node_rrq *rrq;
735 	struct lpfc_node_rrq *nextrrq;
736 	unsigned long iflags;
737 
738 	if (phba->sli_rev != LPFC_SLI_REV4)
739 		return NULL;
740 	spin_lock_irqsave(&phba->hbalock, iflags);
741 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
742 		if (rrq->vport == vport && rrq->xritag == xri &&
743 				rrq->nlp_DID == did){
744 			list_del(&rrq->list);
745 			spin_unlock_irqrestore(&phba->hbalock, iflags);
746 			return rrq;
747 		}
748 	}
749 	spin_unlock_irqrestore(&phba->hbalock, iflags);
750 	return NULL;
751 }
752 
753 /**
754  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
755  * @vport: Pointer to vport context object.
756  * @ndlp: Pointer to the lpfc_node_list structure.
757  * If ndlp is NULL Remove all active RRQs for this vport from the
758  * phba->active_rrq_list and clear the rrq.
759  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
760  **/
761 void
762 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
763 
764 {
765 	struct lpfc_hba *phba = vport->phba;
766 	struct lpfc_node_rrq *rrq;
767 	struct lpfc_node_rrq *nextrrq;
768 	unsigned long iflags;
769 	LIST_HEAD(rrq_list);
770 
771 	if (phba->sli_rev != LPFC_SLI_REV4)
772 		return;
773 	if (!ndlp) {
774 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
775 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
776 	}
777 	spin_lock_irqsave(&phba->hbalock, iflags);
778 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list)
779 		if ((rrq->vport == vport) && (!ndlp  || rrq->ndlp == ndlp))
780 			list_move(&rrq->list, &rrq_list);
781 	spin_unlock_irqrestore(&phba->hbalock, iflags);
782 
783 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
784 		list_del(&rrq->list);
785 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
786 	}
787 }
788 
789 /**
790  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
791  * @phba: Pointer to HBA context object.
792  * @ndlp: Targets nodelist pointer for this exchange.
793  * @xritag the xri in the bitmap to test.
794  *
795  * This function is called with hbalock held. This function
796  * returns 0 = rrq not active for this xri
797  *         1 = rrq is valid for this xri.
798  **/
799 int
800 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
801 			uint16_t  xritag)
802 {
803 	lockdep_assert_held(&phba->hbalock);
804 	if (!ndlp)
805 		return 0;
806 	if (!ndlp->active_rrqs_xri_bitmap)
807 		return 0;
808 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
809 			return 1;
810 	else
811 		return 0;
812 }
813 
814 /**
815  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
816  * @phba: Pointer to HBA context object.
817  * @ndlp: nodelist pointer for this target.
818  * @xritag: xri used in this exchange.
819  * @rxid: Remote Exchange ID.
820  * @send_rrq: Flag used to determine if we should send rrq els cmd.
821  *
822  * This function takes the hbalock.
823  * The active bit is always set in the active rrq xri_bitmap even
824  * if there is no slot avaiable for the other rrq information.
825  *
826  * returns 0 rrq actived for this xri
827  *         < 0 No memory or invalid ndlp.
828  **/
829 int
830 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
831 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
832 {
833 	unsigned long iflags;
834 	struct lpfc_node_rrq *rrq;
835 	int empty;
836 
837 	if (!ndlp)
838 		return -EINVAL;
839 
840 	if (!phba->cfg_enable_rrq)
841 		return -EINVAL;
842 
843 	spin_lock_irqsave(&phba->hbalock, iflags);
844 	if (phba->pport->load_flag & FC_UNLOADING) {
845 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
846 		goto out;
847 	}
848 
849 	/*
850 	 * set the active bit even if there is no mem available.
851 	 */
852 	if (NLP_CHK_FREE_REQ(ndlp))
853 		goto out;
854 
855 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
856 		goto out;
857 
858 	if (!ndlp->active_rrqs_xri_bitmap)
859 		goto out;
860 
861 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
862 		goto out;
863 
864 	spin_unlock_irqrestore(&phba->hbalock, iflags);
865 	rrq = mempool_alloc(phba->rrq_pool, GFP_KERNEL);
866 	if (!rrq) {
867 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
868 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
869 				" DID:0x%x Send:%d\n",
870 				xritag, rxid, ndlp->nlp_DID, send_rrq);
871 		return -EINVAL;
872 	}
873 	if (phba->cfg_enable_rrq == 1)
874 		rrq->send_rrq = send_rrq;
875 	else
876 		rrq->send_rrq = 0;
877 	rrq->xritag = xritag;
878 	rrq->rrq_stop_time = jiffies +
879 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
880 	rrq->ndlp = ndlp;
881 	rrq->nlp_DID = ndlp->nlp_DID;
882 	rrq->vport = ndlp->vport;
883 	rrq->rxid = rxid;
884 	spin_lock_irqsave(&phba->hbalock, iflags);
885 	empty = list_empty(&phba->active_rrq_list);
886 	list_add_tail(&rrq->list, &phba->active_rrq_list);
887 	phba->hba_flag |= HBA_RRQ_ACTIVE;
888 	if (empty)
889 		lpfc_worker_wake_up(phba);
890 	spin_unlock_irqrestore(&phba->hbalock, iflags);
891 	return 0;
892 out:
893 	spin_unlock_irqrestore(&phba->hbalock, iflags);
894 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
895 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
896 			" DID:0x%x Send:%d\n",
897 			xritag, rxid, ndlp->nlp_DID, send_rrq);
898 	return -EINVAL;
899 }
900 
901 /**
902  * __lpfc_sli_get_sglq - Allocates an iocb object from sgl pool
903  * @phba: Pointer to HBA context object.
904  * @piocb: Pointer to the iocbq.
905  *
906  * This function is called with the ring lock held. This function
907  * gets a new driver sglq object from the sglq list. If the
908  * list is not empty then it is successful, it returns pointer to the newly
909  * allocated sglq object else it returns NULL.
910  **/
911 static struct lpfc_sglq *
912 __lpfc_sli_get_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
913 {
914 	struct list_head *lpfc_sgl_list = &phba->sli4_hba.lpfc_sgl_list;
915 	struct lpfc_sglq *sglq = NULL;
916 	struct lpfc_sglq *start_sglq = NULL;
917 	struct lpfc_scsi_buf *lpfc_cmd;
918 	struct lpfc_nodelist *ndlp;
919 	int found = 0;
920 
921 	lockdep_assert_held(&phba->hbalock);
922 
923 	if (piocbq->iocb_flag &  LPFC_IO_FCP) {
924 		lpfc_cmd = (struct lpfc_scsi_buf *) piocbq->context1;
925 		ndlp = lpfc_cmd->rdata->pnode;
926 	} else  if ((piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) &&
927 			!(piocbq->iocb_flag & LPFC_IO_LIBDFC)) {
928 		ndlp = piocbq->context_un.ndlp;
929 	} else  if (piocbq->iocb_flag & LPFC_IO_LIBDFC) {
930 		if (piocbq->iocb_flag & LPFC_IO_LOOPBACK)
931 			ndlp = NULL;
932 		else
933 			ndlp = piocbq->context_un.ndlp;
934 	} else {
935 		ndlp = piocbq->context1;
936 	}
937 
938 	list_remove_head(lpfc_sgl_list, sglq, struct lpfc_sglq, list);
939 	start_sglq = sglq;
940 	while (!found) {
941 		if (!sglq)
942 			return NULL;
943 		if (lpfc_test_rrq_active(phba, ndlp, sglq->sli4_lxritag)) {
944 			/* This xri has an rrq outstanding for this DID.
945 			 * put it back in the list and get another xri.
946 			 */
947 			list_add_tail(&sglq->list, lpfc_sgl_list);
948 			sglq = NULL;
949 			list_remove_head(lpfc_sgl_list, sglq,
950 						struct lpfc_sglq, list);
951 			if (sglq == start_sglq) {
952 				sglq = NULL;
953 				break;
954 			} else
955 				continue;
956 		}
957 		sglq->ndlp = ndlp;
958 		found = 1;
959 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
960 		sglq->state = SGL_ALLOCATED;
961 	}
962 	return sglq;
963 }
964 
965 /**
966  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
967  * @phba: Pointer to HBA context object.
968  *
969  * This function is called with no lock held. This function
970  * allocates a new driver iocb object from the iocb pool. If the
971  * allocation is successful, it returns pointer to the newly
972  * allocated iocb object else it returns NULL.
973  **/
974 struct lpfc_iocbq *
975 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
976 {
977 	struct lpfc_iocbq * iocbq = NULL;
978 	unsigned long iflags;
979 
980 	spin_lock_irqsave(&phba->hbalock, iflags);
981 	iocbq = __lpfc_sli_get_iocbq(phba);
982 	spin_unlock_irqrestore(&phba->hbalock, iflags);
983 	return iocbq;
984 }
985 
986 /**
987  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
988  * @phba: Pointer to HBA context object.
989  * @iocbq: Pointer to driver iocb object.
990  *
991  * This function is called with hbalock held to release driver
992  * iocb object to the iocb pool. The iotag in the iocb object
993  * does not change for each use of the iocb object. This function
994  * clears all other fields of the iocb object when it is freed.
995  * The sqlq structure that holds the xritag and phys and virtual
996  * mappings for the scatter gather list is retrieved from the
997  * active array of sglq. The get of the sglq pointer also clears
998  * the entry in the array. If the status of the IO indiactes that
999  * this IO was aborted then the sglq entry it put on the
1000  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1001  * IO has good status or fails for any other reason then the sglq
1002  * entry is added to the free list (lpfc_sgl_list).
1003  **/
1004 static void
1005 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1006 {
1007 	struct lpfc_sglq *sglq;
1008 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1009 	unsigned long iflag = 0;
1010 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
1011 
1012 	lockdep_assert_held(&phba->hbalock);
1013 
1014 	if (iocbq->sli4_xritag == NO_XRI)
1015 		sglq = NULL;
1016 	else
1017 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1018 
1019 
1020 	if (sglq)  {
1021 		if ((iocbq->iocb_flag & LPFC_EXCHANGE_BUSY) &&
1022 			(sglq->state != SGL_XRI_ABORTED)) {
1023 			spin_lock_irqsave(&phba->sli4_hba.abts_sgl_list_lock,
1024 					iflag);
1025 			list_add(&sglq->list,
1026 				&phba->sli4_hba.lpfc_abts_els_sgl_list);
1027 			spin_unlock_irqrestore(
1028 				&phba->sli4_hba.abts_sgl_list_lock, iflag);
1029 		} else {
1030 			spin_lock_irqsave(&pring->ring_lock, iflag);
1031 			sglq->state = SGL_FREED;
1032 			sglq->ndlp = NULL;
1033 			list_add_tail(&sglq->list,
1034 				&phba->sli4_hba.lpfc_sgl_list);
1035 			spin_unlock_irqrestore(&pring->ring_lock, iflag);
1036 
1037 			/* Check if TXQ queue needs to be serviced */
1038 			if (!list_empty(&pring->txq))
1039 				lpfc_worker_wake_up(phba);
1040 		}
1041 	}
1042 
1043 
1044 	/*
1045 	 * Clean all volatile data fields, preserve iotag and node struct.
1046 	 */
1047 	memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1048 	iocbq->sli4_lxritag = NO_XRI;
1049 	iocbq->sli4_xritag = NO_XRI;
1050 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1051 }
1052 
1053 
1054 /**
1055  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1056  * @phba: Pointer to HBA context object.
1057  * @iocbq: Pointer to driver iocb object.
1058  *
1059  * This function is called with hbalock held to release driver
1060  * iocb object to the iocb pool. The iotag in the iocb object
1061  * does not change for each use of the iocb object. This function
1062  * clears all other fields of the iocb object when it is freed.
1063  **/
1064 static void
1065 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1066 {
1067 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1068 
1069 	lockdep_assert_held(&phba->hbalock);
1070 
1071 	/*
1072 	 * Clean all volatile data fields, preserve iotag and node struct.
1073 	 */
1074 	memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1075 	iocbq->sli4_xritag = NO_XRI;
1076 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1077 }
1078 
1079 /**
1080  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1081  * @phba: Pointer to HBA context object.
1082  * @iocbq: Pointer to driver iocb object.
1083  *
1084  * This function is called with hbalock held to release driver
1085  * iocb object to the iocb pool. The iotag in the iocb object
1086  * does not change for each use of the iocb object. This function
1087  * clears all other fields of the iocb object when it is freed.
1088  **/
1089 static void
1090 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1091 {
1092 	lockdep_assert_held(&phba->hbalock);
1093 
1094 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1095 	phba->iocb_cnt--;
1096 }
1097 
1098 /**
1099  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1100  * @phba: Pointer to HBA context object.
1101  * @iocbq: Pointer to driver iocb object.
1102  *
1103  * This function is called with no lock held to release the iocb to
1104  * iocb pool.
1105  **/
1106 void
1107 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1108 {
1109 	unsigned long iflags;
1110 
1111 	/*
1112 	 * Clean all volatile data fields, preserve iotag and node struct.
1113 	 */
1114 	spin_lock_irqsave(&phba->hbalock, iflags);
1115 	__lpfc_sli_release_iocbq(phba, iocbq);
1116 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1117 }
1118 
1119 /**
1120  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1121  * @phba: Pointer to HBA context object.
1122  * @iocblist: List of IOCBs.
1123  * @ulpstatus: ULP status in IOCB command field.
1124  * @ulpWord4: ULP word-4 in IOCB command field.
1125  *
1126  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1127  * on the list by invoking the complete callback function associated with the
1128  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1129  * fields.
1130  **/
1131 void
1132 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1133 		      uint32_t ulpstatus, uint32_t ulpWord4)
1134 {
1135 	struct lpfc_iocbq *piocb;
1136 
1137 	while (!list_empty(iocblist)) {
1138 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1139 		if (!piocb->iocb_cmpl)
1140 			lpfc_sli_release_iocbq(phba, piocb);
1141 		else {
1142 			piocb->iocb.ulpStatus = ulpstatus;
1143 			piocb->iocb.un.ulpWord[4] = ulpWord4;
1144 			(piocb->iocb_cmpl) (phba, piocb, piocb);
1145 		}
1146 	}
1147 	return;
1148 }
1149 
1150 /**
1151  * lpfc_sli_iocb_cmd_type - Get the iocb type
1152  * @iocb_cmnd: iocb command code.
1153  *
1154  * This function is called by ring event handler function to get the iocb type.
1155  * This function translates the iocb command to an iocb command type used to
1156  * decide the final disposition of each completed IOCB.
1157  * The function returns
1158  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1159  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1160  * LPFC_ABORT_IOCB   if it is an abort iocb
1161  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1162  *
1163  * The caller is not required to hold any lock.
1164  **/
1165 static lpfc_iocb_type
1166 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1167 {
1168 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1169 
1170 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1171 		return 0;
1172 
1173 	switch (iocb_cmnd) {
1174 	case CMD_XMIT_SEQUENCE_CR:
1175 	case CMD_XMIT_SEQUENCE_CX:
1176 	case CMD_XMIT_BCAST_CN:
1177 	case CMD_XMIT_BCAST_CX:
1178 	case CMD_ELS_REQUEST_CR:
1179 	case CMD_ELS_REQUEST_CX:
1180 	case CMD_CREATE_XRI_CR:
1181 	case CMD_CREATE_XRI_CX:
1182 	case CMD_GET_RPI_CN:
1183 	case CMD_XMIT_ELS_RSP_CX:
1184 	case CMD_GET_RPI_CR:
1185 	case CMD_FCP_IWRITE_CR:
1186 	case CMD_FCP_IWRITE_CX:
1187 	case CMD_FCP_IREAD_CR:
1188 	case CMD_FCP_IREAD_CX:
1189 	case CMD_FCP_ICMND_CR:
1190 	case CMD_FCP_ICMND_CX:
1191 	case CMD_FCP_TSEND_CX:
1192 	case CMD_FCP_TRSP_CX:
1193 	case CMD_FCP_TRECEIVE_CX:
1194 	case CMD_FCP_AUTO_TRSP_CX:
1195 	case CMD_ADAPTER_MSG:
1196 	case CMD_ADAPTER_DUMP:
1197 	case CMD_XMIT_SEQUENCE64_CR:
1198 	case CMD_XMIT_SEQUENCE64_CX:
1199 	case CMD_XMIT_BCAST64_CN:
1200 	case CMD_XMIT_BCAST64_CX:
1201 	case CMD_ELS_REQUEST64_CR:
1202 	case CMD_ELS_REQUEST64_CX:
1203 	case CMD_FCP_IWRITE64_CR:
1204 	case CMD_FCP_IWRITE64_CX:
1205 	case CMD_FCP_IREAD64_CR:
1206 	case CMD_FCP_IREAD64_CX:
1207 	case CMD_FCP_ICMND64_CR:
1208 	case CMD_FCP_ICMND64_CX:
1209 	case CMD_FCP_TSEND64_CX:
1210 	case CMD_FCP_TRSP64_CX:
1211 	case CMD_FCP_TRECEIVE64_CX:
1212 	case CMD_GEN_REQUEST64_CR:
1213 	case CMD_GEN_REQUEST64_CX:
1214 	case CMD_XMIT_ELS_RSP64_CX:
1215 	case DSSCMD_IWRITE64_CR:
1216 	case DSSCMD_IWRITE64_CX:
1217 	case DSSCMD_IREAD64_CR:
1218 	case DSSCMD_IREAD64_CX:
1219 		type = LPFC_SOL_IOCB;
1220 		break;
1221 	case CMD_ABORT_XRI_CN:
1222 	case CMD_ABORT_XRI_CX:
1223 	case CMD_CLOSE_XRI_CN:
1224 	case CMD_CLOSE_XRI_CX:
1225 	case CMD_XRI_ABORTED_CX:
1226 	case CMD_ABORT_MXRI64_CN:
1227 	case CMD_XMIT_BLS_RSP64_CX:
1228 		type = LPFC_ABORT_IOCB;
1229 		break;
1230 	case CMD_RCV_SEQUENCE_CX:
1231 	case CMD_RCV_ELS_REQ_CX:
1232 	case CMD_RCV_SEQUENCE64_CX:
1233 	case CMD_RCV_ELS_REQ64_CX:
1234 	case CMD_ASYNC_STATUS:
1235 	case CMD_IOCB_RCV_SEQ64_CX:
1236 	case CMD_IOCB_RCV_ELS64_CX:
1237 	case CMD_IOCB_RCV_CONT64_CX:
1238 	case CMD_IOCB_RET_XRI64_CX:
1239 		type = LPFC_UNSOL_IOCB;
1240 		break;
1241 	case CMD_IOCB_XMIT_MSEQ64_CR:
1242 	case CMD_IOCB_XMIT_MSEQ64_CX:
1243 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1244 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1245 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1246 	case CMD_IOCB_ABORT_EXTENDED_CN:
1247 	case CMD_IOCB_RET_HBQE64_CN:
1248 	case CMD_IOCB_FCP_IBIDIR64_CR:
1249 	case CMD_IOCB_FCP_IBIDIR64_CX:
1250 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1251 	case CMD_IOCB_LOGENTRY_CN:
1252 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1253 		printk("%s - Unhandled SLI-3 Command x%x\n",
1254 				__func__, iocb_cmnd);
1255 		type = LPFC_UNKNOWN_IOCB;
1256 		break;
1257 	default:
1258 		type = LPFC_UNKNOWN_IOCB;
1259 		break;
1260 	}
1261 
1262 	return type;
1263 }
1264 
1265 /**
1266  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1267  * @phba: Pointer to HBA context object.
1268  *
1269  * This function is called from SLI initialization code
1270  * to configure every ring of the HBA's SLI interface. The
1271  * caller is not required to hold any lock. This function issues
1272  * a config_ring mailbox command for each ring.
1273  * This function returns zero if successful else returns a negative
1274  * error code.
1275  **/
1276 static int
1277 lpfc_sli_ring_map(struct lpfc_hba *phba)
1278 {
1279 	struct lpfc_sli *psli = &phba->sli;
1280 	LPFC_MBOXQ_t *pmb;
1281 	MAILBOX_t *pmbox;
1282 	int i, rc, ret = 0;
1283 
1284 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1285 	if (!pmb)
1286 		return -ENOMEM;
1287 	pmbox = &pmb->u.mb;
1288 	phba->link_state = LPFC_INIT_MBX_CMDS;
1289 	for (i = 0; i < psli->num_rings; i++) {
1290 		lpfc_config_ring(phba, i, pmb);
1291 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1292 		if (rc != MBX_SUCCESS) {
1293 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1294 					"0446 Adapter failed to init (%d), "
1295 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1296 					"ring %d\n",
1297 					rc, pmbox->mbxCommand,
1298 					pmbox->mbxStatus, i);
1299 			phba->link_state = LPFC_HBA_ERROR;
1300 			ret = -ENXIO;
1301 			break;
1302 		}
1303 	}
1304 	mempool_free(pmb, phba->mbox_mem_pool);
1305 	return ret;
1306 }
1307 
1308 /**
1309  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1310  * @phba: Pointer to HBA context object.
1311  * @pring: Pointer to driver SLI ring object.
1312  * @piocb: Pointer to the driver iocb object.
1313  *
1314  * This function is called with hbalock held. The function adds the
1315  * new iocb to txcmplq of the given ring. This function always returns
1316  * 0. If this function is called for ELS ring, this function checks if
1317  * there is a vport associated with the ELS command. This function also
1318  * starts els_tmofunc timer if this is an ELS command.
1319  **/
1320 static int
1321 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1322 			struct lpfc_iocbq *piocb)
1323 {
1324 	lockdep_assert_held(&phba->hbalock);
1325 
1326 	list_add_tail(&piocb->list, &pring->txcmplq);
1327 	piocb->iocb_flag |= LPFC_IO_ON_TXCMPLQ;
1328 
1329 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1330 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
1331 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN) &&
1332 	 (!(piocb->vport->load_flag & FC_UNLOADING))) {
1333 		if (!piocb->vport)
1334 			BUG();
1335 		else
1336 			mod_timer(&piocb->vport->els_tmofunc,
1337 				jiffies +
1338 				msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1339 	}
1340 
1341 
1342 	return 0;
1343 }
1344 
1345 /**
1346  * lpfc_sli_ringtx_get - Get first element of the txq
1347  * @phba: Pointer to HBA context object.
1348  * @pring: Pointer to driver SLI ring object.
1349  *
1350  * This function is called with hbalock held to get next
1351  * iocb in txq of the given ring. If there is any iocb in
1352  * the txq, the function returns first iocb in the list after
1353  * removing the iocb from the list, else it returns NULL.
1354  **/
1355 struct lpfc_iocbq *
1356 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1357 {
1358 	struct lpfc_iocbq *cmd_iocb;
1359 
1360 	lockdep_assert_held(&phba->hbalock);
1361 
1362 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1363 	return cmd_iocb;
1364 }
1365 
1366 /**
1367  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
1368  * @phba: Pointer to HBA context object.
1369  * @pring: Pointer to driver SLI ring object.
1370  *
1371  * This function is called with hbalock held and the caller must post the
1372  * iocb without releasing the lock. If the caller releases the lock,
1373  * iocb slot returned by the function is not guaranteed to be available.
1374  * The function returns pointer to the next available iocb slot if there
1375  * is available slot in the ring, else it returns NULL.
1376  * If the get index of the ring is ahead of the put index, the function
1377  * will post an error attention event to the worker thread to take the
1378  * HBA to offline state.
1379  **/
1380 static IOCB_t *
1381 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1382 {
1383 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
1384 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
1385 
1386 	lockdep_assert_held(&phba->hbalock);
1387 
1388 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
1389 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
1390 		pring->sli.sli3.next_cmdidx = 0;
1391 
1392 	if (unlikely(pring->sli.sli3.local_getidx ==
1393 		pring->sli.sli3.next_cmdidx)) {
1394 
1395 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
1396 
1397 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
1398 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1399 					"0315 Ring %d issue: portCmdGet %d "
1400 					"is bigger than cmd ring %d\n",
1401 					pring->ringno,
1402 					pring->sli.sli3.local_getidx,
1403 					max_cmd_idx);
1404 
1405 			phba->link_state = LPFC_HBA_ERROR;
1406 			/*
1407 			 * All error attention handlers are posted to
1408 			 * worker thread
1409 			 */
1410 			phba->work_ha |= HA_ERATT;
1411 			phba->work_hs = HS_FFER3;
1412 
1413 			lpfc_worker_wake_up(phba);
1414 
1415 			return NULL;
1416 		}
1417 
1418 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
1419 			return NULL;
1420 	}
1421 
1422 	return lpfc_cmd_iocb(phba, pring);
1423 }
1424 
1425 /**
1426  * lpfc_sli_next_iotag - Get an iotag for the iocb
1427  * @phba: Pointer to HBA context object.
1428  * @iocbq: Pointer to driver iocb object.
1429  *
1430  * This function gets an iotag for the iocb. If there is no unused iotag and
1431  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
1432  * array and assigns a new iotag.
1433  * The function returns the allocated iotag if successful, else returns zero.
1434  * Zero is not a valid iotag.
1435  * The caller is not required to hold any lock.
1436  **/
1437 uint16_t
1438 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1439 {
1440 	struct lpfc_iocbq **new_arr;
1441 	struct lpfc_iocbq **old_arr;
1442 	size_t new_len;
1443 	struct lpfc_sli *psli = &phba->sli;
1444 	uint16_t iotag;
1445 
1446 	spin_lock_irq(&phba->hbalock);
1447 	iotag = psli->last_iotag;
1448 	if(++iotag < psli->iocbq_lookup_len) {
1449 		psli->last_iotag = iotag;
1450 		psli->iocbq_lookup[iotag] = iocbq;
1451 		spin_unlock_irq(&phba->hbalock);
1452 		iocbq->iotag = iotag;
1453 		return iotag;
1454 	} else if (psli->iocbq_lookup_len < (0xffff
1455 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
1456 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
1457 		spin_unlock_irq(&phba->hbalock);
1458 		new_arr = kzalloc(new_len * sizeof (struct lpfc_iocbq *),
1459 				  GFP_KERNEL);
1460 		if (new_arr) {
1461 			spin_lock_irq(&phba->hbalock);
1462 			old_arr = psli->iocbq_lookup;
1463 			if (new_len <= psli->iocbq_lookup_len) {
1464 				/* highly unprobable case */
1465 				kfree(new_arr);
1466 				iotag = psli->last_iotag;
1467 				if(++iotag < psli->iocbq_lookup_len) {
1468 					psli->last_iotag = iotag;
1469 					psli->iocbq_lookup[iotag] = iocbq;
1470 					spin_unlock_irq(&phba->hbalock);
1471 					iocbq->iotag = iotag;
1472 					return iotag;
1473 				}
1474 				spin_unlock_irq(&phba->hbalock);
1475 				return 0;
1476 			}
1477 			if (psli->iocbq_lookup)
1478 				memcpy(new_arr, old_arr,
1479 				       ((psli->last_iotag  + 1) *
1480 					sizeof (struct lpfc_iocbq *)));
1481 			psli->iocbq_lookup = new_arr;
1482 			psli->iocbq_lookup_len = new_len;
1483 			psli->last_iotag = iotag;
1484 			psli->iocbq_lookup[iotag] = iocbq;
1485 			spin_unlock_irq(&phba->hbalock);
1486 			iocbq->iotag = iotag;
1487 			kfree(old_arr);
1488 			return iotag;
1489 		}
1490 	} else
1491 		spin_unlock_irq(&phba->hbalock);
1492 
1493 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
1494 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
1495 			psli->last_iotag);
1496 
1497 	return 0;
1498 }
1499 
1500 /**
1501  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
1502  * @phba: Pointer to HBA context object.
1503  * @pring: Pointer to driver SLI ring object.
1504  * @iocb: Pointer to iocb slot in the ring.
1505  * @nextiocb: Pointer to driver iocb object which need to be
1506  *            posted to firmware.
1507  *
1508  * This function is called with hbalock held to post a new iocb to
1509  * the firmware. This function copies the new iocb to ring iocb slot and
1510  * updates the ring pointers. It adds the new iocb to txcmplq if there is
1511  * a completion call back for this iocb else the function will free the
1512  * iocb object.
1513  **/
1514 static void
1515 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1516 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
1517 {
1518 	lockdep_assert_held(&phba->hbalock);
1519 	/*
1520 	 * Set up an iotag
1521 	 */
1522 	nextiocb->iocb.ulpIoTag = (nextiocb->iocb_cmpl) ? nextiocb->iotag : 0;
1523 
1524 
1525 	if (pring->ringno == LPFC_ELS_RING) {
1526 		lpfc_debugfs_slow_ring_trc(phba,
1527 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
1528 			*(((uint32_t *) &nextiocb->iocb) + 4),
1529 			*(((uint32_t *) &nextiocb->iocb) + 6),
1530 			*(((uint32_t *) &nextiocb->iocb) + 7));
1531 	}
1532 
1533 	/*
1534 	 * Issue iocb command to adapter
1535 	 */
1536 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
1537 	wmb();
1538 	pring->stats.iocb_cmd++;
1539 
1540 	/*
1541 	 * If there is no completion routine to call, we can release the
1542 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
1543 	 * that have no rsp ring completion, iocb_cmpl MUST be NULL.
1544 	 */
1545 	if (nextiocb->iocb_cmpl)
1546 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
1547 	else
1548 		__lpfc_sli_release_iocbq(phba, nextiocb);
1549 
1550 	/*
1551 	 * Let the HBA know what IOCB slot will be the next one the
1552 	 * driver will put a command into.
1553 	 */
1554 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
1555 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
1556 }
1557 
1558 /**
1559  * lpfc_sli_update_full_ring - Update the chip attention register
1560  * @phba: Pointer to HBA context object.
1561  * @pring: Pointer to driver SLI ring object.
1562  *
1563  * The caller is not required to hold any lock for calling this function.
1564  * This function updates the chip attention bits for the ring to inform firmware
1565  * that there are pending work to be done for this ring and requests an
1566  * interrupt when there is space available in the ring. This function is
1567  * called when the driver is unable to post more iocbs to the ring due
1568  * to unavailability of space in the ring.
1569  **/
1570 static void
1571 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1572 {
1573 	int ringno = pring->ringno;
1574 
1575 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
1576 
1577 	wmb();
1578 
1579 	/*
1580 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
1581 	 * The HBA will tell us when an IOCB entry is available.
1582 	 */
1583 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
1584 	readl(phba->CAregaddr); /* flush */
1585 
1586 	pring->stats.iocb_cmd_full++;
1587 }
1588 
1589 /**
1590  * lpfc_sli_update_ring - Update chip attention register
1591  * @phba: Pointer to HBA context object.
1592  * @pring: Pointer to driver SLI ring object.
1593  *
1594  * This function updates the chip attention register bit for the
1595  * given ring to inform HBA that there is more work to be done
1596  * in this ring. The caller is not required to hold any lock.
1597  **/
1598 static void
1599 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1600 {
1601 	int ringno = pring->ringno;
1602 
1603 	/*
1604 	 * Tell the HBA that there is work to do in this ring.
1605 	 */
1606 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
1607 		wmb();
1608 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
1609 		readl(phba->CAregaddr); /* flush */
1610 	}
1611 }
1612 
1613 /**
1614  * lpfc_sli_resume_iocb - Process iocbs in the txq
1615  * @phba: Pointer to HBA context object.
1616  * @pring: Pointer to driver SLI ring object.
1617  *
1618  * This function is called with hbalock held to post pending iocbs
1619  * in the txq to the firmware. This function is called when driver
1620  * detects space available in the ring.
1621  **/
1622 static void
1623 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1624 {
1625 	IOCB_t *iocb;
1626 	struct lpfc_iocbq *nextiocb;
1627 
1628 	lockdep_assert_held(&phba->hbalock);
1629 
1630 	/*
1631 	 * Check to see if:
1632 	 *  (a) there is anything on the txq to send
1633 	 *  (b) link is up
1634 	 *  (c) link attention events can be processed (fcp ring only)
1635 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
1636 	 */
1637 
1638 	if (lpfc_is_link_up(phba) &&
1639 	    (!list_empty(&pring->txq)) &&
1640 	    (pring->ringno != phba->sli.fcp_ring ||
1641 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
1642 
1643 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
1644 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
1645 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
1646 
1647 		if (iocb)
1648 			lpfc_sli_update_ring(phba, pring);
1649 		else
1650 			lpfc_sli_update_full_ring(phba, pring);
1651 	}
1652 
1653 	return;
1654 }
1655 
1656 /**
1657  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
1658  * @phba: Pointer to HBA context object.
1659  * @hbqno: HBQ number.
1660  *
1661  * This function is called with hbalock held to get the next
1662  * available slot for the given HBQ. If there is free slot
1663  * available for the HBQ it will return pointer to the next available
1664  * HBQ entry else it will return NULL.
1665  **/
1666 static struct lpfc_hbq_entry *
1667 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
1668 {
1669 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
1670 
1671 	lockdep_assert_held(&phba->hbalock);
1672 
1673 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
1674 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
1675 		hbqp->next_hbqPutIdx = 0;
1676 
1677 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
1678 		uint32_t raw_index = phba->hbq_get[hbqno];
1679 		uint32_t getidx = le32_to_cpu(raw_index);
1680 
1681 		hbqp->local_hbqGetIdx = getidx;
1682 
1683 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
1684 			lpfc_printf_log(phba, KERN_ERR,
1685 					LOG_SLI | LOG_VPORT,
1686 					"1802 HBQ %d: local_hbqGetIdx "
1687 					"%u is > than hbqp->entry_count %u\n",
1688 					hbqno, hbqp->local_hbqGetIdx,
1689 					hbqp->entry_count);
1690 
1691 			phba->link_state = LPFC_HBA_ERROR;
1692 			return NULL;
1693 		}
1694 
1695 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
1696 			return NULL;
1697 	}
1698 
1699 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
1700 			hbqp->hbqPutIdx;
1701 }
1702 
1703 /**
1704  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
1705  * @phba: Pointer to HBA context object.
1706  *
1707  * This function is called with no lock held to free all the
1708  * hbq buffers while uninitializing the SLI interface. It also
1709  * frees the HBQ buffers returned by the firmware but not yet
1710  * processed by the upper layers.
1711  **/
1712 void
1713 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
1714 {
1715 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
1716 	struct hbq_dmabuf *hbq_buf;
1717 	unsigned long flags;
1718 	int i, hbq_count;
1719 	uint32_t hbqno;
1720 
1721 	hbq_count = lpfc_sli_hbq_count();
1722 	/* Return all memory used by all HBQs */
1723 	spin_lock_irqsave(&phba->hbalock, flags);
1724 	for (i = 0; i < hbq_count; ++i) {
1725 		list_for_each_entry_safe(dmabuf, next_dmabuf,
1726 				&phba->hbqs[i].hbq_buffer_list, list) {
1727 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
1728 			list_del(&hbq_buf->dbuf.list);
1729 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
1730 		}
1731 		phba->hbqs[i].buffer_count = 0;
1732 	}
1733 	/* Return all HBQ buffer that are in-fly */
1734 	list_for_each_entry_safe(dmabuf, next_dmabuf, &phba->rb_pend_list,
1735 				 list) {
1736 		hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
1737 		list_del(&hbq_buf->dbuf.list);
1738 		if (hbq_buf->tag == -1) {
1739 			(phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer)
1740 				(phba, hbq_buf);
1741 		} else {
1742 			hbqno = hbq_buf->tag >> 16;
1743 			if (hbqno >= LPFC_MAX_HBQS)
1744 				(phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer)
1745 					(phba, hbq_buf);
1746 			else
1747 				(phba->hbqs[hbqno].hbq_free_buffer)(phba,
1748 					hbq_buf);
1749 		}
1750 	}
1751 
1752 	/* Mark the HBQs not in use */
1753 	phba->hbq_in_use = 0;
1754 	spin_unlock_irqrestore(&phba->hbalock, flags);
1755 }
1756 
1757 /**
1758  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
1759  * @phba: Pointer to HBA context object.
1760  * @hbqno: HBQ number.
1761  * @hbq_buf: Pointer to HBQ buffer.
1762  *
1763  * This function is called with the hbalock held to post a
1764  * hbq buffer to the firmware. If the function finds an empty
1765  * slot in the HBQ, it will post the buffer. The function will return
1766  * pointer to the hbq entry if it successfully post the buffer
1767  * else it will return NULL.
1768  **/
1769 static int
1770 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
1771 			 struct hbq_dmabuf *hbq_buf)
1772 {
1773 	lockdep_assert_held(&phba->hbalock);
1774 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
1775 }
1776 
1777 /**
1778  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
1779  * @phba: Pointer to HBA context object.
1780  * @hbqno: HBQ number.
1781  * @hbq_buf: Pointer to HBQ buffer.
1782  *
1783  * This function is called with the hbalock held to post a hbq buffer to the
1784  * firmware. If the function finds an empty slot in the HBQ, it will post the
1785  * buffer and place it on the hbq_buffer_list. The function will return zero if
1786  * it successfully post the buffer else it will return an error.
1787  **/
1788 static int
1789 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
1790 			    struct hbq_dmabuf *hbq_buf)
1791 {
1792 	struct lpfc_hbq_entry *hbqe;
1793 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
1794 
1795 	lockdep_assert_held(&phba->hbalock);
1796 	/* Get next HBQ entry slot to use */
1797 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
1798 	if (hbqe) {
1799 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
1800 
1801 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
1802 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
1803 		hbqe->bde.tus.f.bdeSize = hbq_buf->size;
1804 		hbqe->bde.tus.f.bdeFlags = 0;
1805 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
1806 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
1807 				/* Sync SLIM */
1808 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
1809 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
1810 				/* flush */
1811 		readl(phba->hbq_put + hbqno);
1812 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
1813 		return 0;
1814 	} else
1815 		return -ENOMEM;
1816 }
1817 
1818 /**
1819  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
1820  * @phba: Pointer to HBA context object.
1821  * @hbqno: HBQ number.
1822  * @hbq_buf: Pointer to HBQ buffer.
1823  *
1824  * This function is called with the hbalock held to post an RQE to the SLI4
1825  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
1826  * the hbq_buffer_list and return zero, otherwise it will return an error.
1827  **/
1828 static int
1829 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
1830 			    struct hbq_dmabuf *hbq_buf)
1831 {
1832 	int rc;
1833 	struct lpfc_rqe hrqe;
1834 	struct lpfc_rqe drqe;
1835 
1836 	lockdep_assert_held(&phba->hbalock);
1837 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
1838 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
1839 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
1840 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
1841 	rc = lpfc_sli4_rq_put(phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
1842 			      &hrqe, &drqe);
1843 	if (rc < 0)
1844 		return rc;
1845 	hbq_buf->tag = rc;
1846 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
1847 	return 0;
1848 }
1849 
1850 /* HBQ for ELS and CT traffic. */
1851 static struct lpfc_hbq_init lpfc_els_hbq = {
1852 	.rn = 1,
1853 	.entry_count = 256,
1854 	.mask_count = 0,
1855 	.profile = 0,
1856 	.ring_mask = (1 << LPFC_ELS_RING),
1857 	.buffer_count = 0,
1858 	.init_count = 40,
1859 	.add_count = 40,
1860 };
1861 
1862 /* HBQ for the extra ring if needed */
1863 static struct lpfc_hbq_init lpfc_extra_hbq = {
1864 	.rn = 1,
1865 	.entry_count = 200,
1866 	.mask_count = 0,
1867 	.profile = 0,
1868 	.ring_mask = (1 << LPFC_EXTRA_RING),
1869 	.buffer_count = 0,
1870 	.init_count = 0,
1871 	.add_count = 5,
1872 };
1873 
1874 /* Array of HBQs */
1875 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
1876 	&lpfc_els_hbq,
1877 	&lpfc_extra_hbq,
1878 };
1879 
1880 /**
1881  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
1882  * @phba: Pointer to HBA context object.
1883  * @hbqno: HBQ number.
1884  * @count: Number of HBQ buffers to be posted.
1885  *
1886  * This function is called with no lock held to post more hbq buffers to the
1887  * given HBQ. The function returns the number of HBQ buffers successfully
1888  * posted.
1889  **/
1890 static int
1891 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
1892 {
1893 	uint32_t i, posted = 0;
1894 	unsigned long flags;
1895 	struct hbq_dmabuf *hbq_buffer;
1896 	LIST_HEAD(hbq_buf_list);
1897 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
1898 		return 0;
1899 
1900 	if ((phba->hbqs[hbqno].buffer_count + count) >
1901 	    lpfc_hbq_defs[hbqno]->entry_count)
1902 		count = lpfc_hbq_defs[hbqno]->entry_count -
1903 					phba->hbqs[hbqno].buffer_count;
1904 	if (!count)
1905 		return 0;
1906 	/* Allocate HBQ entries */
1907 	for (i = 0; i < count; i++) {
1908 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
1909 		if (!hbq_buffer)
1910 			break;
1911 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
1912 	}
1913 	/* Check whether HBQ is still in use */
1914 	spin_lock_irqsave(&phba->hbalock, flags);
1915 	if (!phba->hbq_in_use)
1916 		goto err;
1917 	while (!list_empty(&hbq_buf_list)) {
1918 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
1919 				 dbuf.list);
1920 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
1921 				      (hbqno << 16));
1922 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
1923 			phba->hbqs[hbqno].buffer_count++;
1924 			posted++;
1925 		} else
1926 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
1927 	}
1928 	spin_unlock_irqrestore(&phba->hbalock, flags);
1929 	return posted;
1930 err:
1931 	spin_unlock_irqrestore(&phba->hbalock, flags);
1932 	while (!list_empty(&hbq_buf_list)) {
1933 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
1934 				 dbuf.list);
1935 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
1936 	}
1937 	return 0;
1938 }
1939 
1940 /**
1941  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
1942  * @phba: Pointer to HBA context object.
1943  * @qno: HBQ number.
1944  *
1945  * This function posts more buffers to the HBQ. This function
1946  * is called with no lock held. The function returns the number of HBQ entries
1947  * successfully allocated.
1948  **/
1949 int
1950 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
1951 {
1952 	if (phba->sli_rev == LPFC_SLI_REV4)
1953 		return 0;
1954 	else
1955 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
1956 					 lpfc_hbq_defs[qno]->add_count);
1957 }
1958 
1959 /**
1960  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
1961  * @phba: Pointer to HBA context object.
1962  * @qno:  HBQ queue number.
1963  *
1964  * This function is called from SLI initialization code path with
1965  * no lock held to post initial HBQ buffers to firmware. The
1966  * function returns the number of HBQ entries successfully allocated.
1967  **/
1968 static int
1969 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
1970 {
1971 	if (phba->sli_rev == LPFC_SLI_REV4)
1972 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
1973 					lpfc_hbq_defs[qno]->entry_count);
1974 	else
1975 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
1976 					 lpfc_hbq_defs[qno]->init_count);
1977 }
1978 
1979 /**
1980  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
1981  * @phba: Pointer to HBA context object.
1982  * @hbqno: HBQ number.
1983  *
1984  * This function removes the first hbq buffer on an hbq list and returns a
1985  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
1986  **/
1987 static struct hbq_dmabuf *
1988 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
1989 {
1990 	struct lpfc_dmabuf *d_buf;
1991 
1992 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
1993 	if (!d_buf)
1994 		return NULL;
1995 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
1996 }
1997 
1998 /**
1999  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2000  * @phba: Pointer to HBA context object.
2001  * @tag: Tag of the hbq buffer.
2002  *
2003  * This function searches for the hbq buffer associated with the given tag in
2004  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2005  * otherwise it returns NULL.
2006  **/
2007 static struct hbq_dmabuf *
2008 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2009 {
2010 	struct lpfc_dmabuf *d_buf;
2011 	struct hbq_dmabuf *hbq_buf;
2012 	uint32_t hbqno;
2013 
2014 	hbqno = tag >> 16;
2015 	if (hbqno >= LPFC_MAX_HBQS)
2016 		return NULL;
2017 
2018 	spin_lock_irq(&phba->hbalock);
2019 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2020 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2021 		if (hbq_buf->tag == tag) {
2022 			spin_unlock_irq(&phba->hbalock);
2023 			return hbq_buf;
2024 		}
2025 	}
2026 	spin_unlock_irq(&phba->hbalock);
2027 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_VPORT,
2028 			"1803 Bad hbq tag. Data: x%x x%x\n",
2029 			tag, phba->hbqs[tag >> 16].buffer_count);
2030 	return NULL;
2031 }
2032 
2033 /**
2034  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2035  * @phba: Pointer to HBA context object.
2036  * @hbq_buffer: Pointer to HBQ buffer.
2037  *
2038  * This function is called with hbalock. This function gives back
2039  * the hbq buffer to firmware. If the HBQ does not have space to
2040  * post the buffer, it will free the buffer.
2041  **/
2042 void
2043 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2044 {
2045 	uint32_t hbqno;
2046 
2047 	if (hbq_buffer) {
2048 		hbqno = hbq_buffer->tag >> 16;
2049 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2050 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2051 	}
2052 }
2053 
2054 /**
2055  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2056  * @mbxCommand: mailbox command code.
2057  *
2058  * This function is called by the mailbox event handler function to verify
2059  * that the completed mailbox command is a legitimate mailbox command. If the
2060  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2061  * and the mailbox event handler will take the HBA offline.
2062  **/
2063 static int
2064 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2065 {
2066 	uint8_t ret;
2067 
2068 	switch (mbxCommand) {
2069 	case MBX_LOAD_SM:
2070 	case MBX_READ_NV:
2071 	case MBX_WRITE_NV:
2072 	case MBX_WRITE_VPARMS:
2073 	case MBX_RUN_BIU_DIAG:
2074 	case MBX_INIT_LINK:
2075 	case MBX_DOWN_LINK:
2076 	case MBX_CONFIG_LINK:
2077 	case MBX_CONFIG_RING:
2078 	case MBX_RESET_RING:
2079 	case MBX_READ_CONFIG:
2080 	case MBX_READ_RCONFIG:
2081 	case MBX_READ_SPARM:
2082 	case MBX_READ_STATUS:
2083 	case MBX_READ_RPI:
2084 	case MBX_READ_XRI:
2085 	case MBX_READ_REV:
2086 	case MBX_READ_LNK_STAT:
2087 	case MBX_REG_LOGIN:
2088 	case MBX_UNREG_LOGIN:
2089 	case MBX_CLEAR_LA:
2090 	case MBX_DUMP_MEMORY:
2091 	case MBX_DUMP_CONTEXT:
2092 	case MBX_RUN_DIAGS:
2093 	case MBX_RESTART:
2094 	case MBX_UPDATE_CFG:
2095 	case MBX_DOWN_LOAD:
2096 	case MBX_DEL_LD_ENTRY:
2097 	case MBX_RUN_PROGRAM:
2098 	case MBX_SET_MASK:
2099 	case MBX_SET_VARIABLE:
2100 	case MBX_UNREG_D_ID:
2101 	case MBX_KILL_BOARD:
2102 	case MBX_CONFIG_FARP:
2103 	case MBX_BEACON:
2104 	case MBX_LOAD_AREA:
2105 	case MBX_RUN_BIU_DIAG64:
2106 	case MBX_CONFIG_PORT:
2107 	case MBX_READ_SPARM64:
2108 	case MBX_READ_RPI64:
2109 	case MBX_REG_LOGIN64:
2110 	case MBX_READ_TOPOLOGY:
2111 	case MBX_WRITE_WWN:
2112 	case MBX_SET_DEBUG:
2113 	case MBX_LOAD_EXP_ROM:
2114 	case MBX_ASYNCEVT_ENABLE:
2115 	case MBX_REG_VPI:
2116 	case MBX_UNREG_VPI:
2117 	case MBX_HEARTBEAT:
2118 	case MBX_PORT_CAPABILITIES:
2119 	case MBX_PORT_IOV_CONTROL:
2120 	case MBX_SLI4_CONFIG:
2121 	case MBX_SLI4_REQ_FTRS:
2122 	case MBX_REG_FCFI:
2123 	case MBX_UNREG_FCFI:
2124 	case MBX_REG_VFI:
2125 	case MBX_UNREG_VFI:
2126 	case MBX_INIT_VPI:
2127 	case MBX_INIT_VFI:
2128 	case MBX_RESUME_RPI:
2129 	case MBX_READ_EVENT_LOG_STATUS:
2130 	case MBX_READ_EVENT_LOG:
2131 	case MBX_SECURITY_MGMT:
2132 	case MBX_AUTH_PORT:
2133 	case MBX_ACCESS_VDATA:
2134 		ret = mbxCommand;
2135 		break;
2136 	default:
2137 		ret = MBX_SHUTDOWN;
2138 		break;
2139 	}
2140 	return ret;
2141 }
2142 
2143 /**
2144  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2145  * @phba: Pointer to HBA context object.
2146  * @pmboxq: Pointer to mailbox command.
2147  *
2148  * This is completion handler function for mailbox commands issued from
2149  * lpfc_sli_issue_mbox_wait function. This function is called by the
2150  * mailbox event handler function with no lock held. This function
2151  * will wake up thread waiting on the wait queue pointed by context1
2152  * of the mailbox.
2153  **/
2154 void
2155 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2156 {
2157 	wait_queue_head_t *pdone_q;
2158 	unsigned long drvr_flag;
2159 
2160 	/*
2161 	 * If pdone_q is empty, the driver thread gave up waiting and
2162 	 * continued running.
2163 	 */
2164 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2165 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2166 	pdone_q = (wait_queue_head_t *) pmboxq->context1;
2167 	if (pdone_q)
2168 		wake_up_interruptible(pdone_q);
2169 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2170 	return;
2171 }
2172 
2173 
2174 /**
2175  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2176  * @phba: Pointer to HBA context object.
2177  * @pmb: Pointer to mailbox object.
2178  *
2179  * This function is the default mailbox completion handler. It
2180  * frees the memory resources associated with the completed mailbox
2181  * command. If the completed command is a REG_LOGIN mailbox command,
2182  * this function will issue a UREG_LOGIN to re-claim the RPI.
2183  **/
2184 void
2185 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2186 {
2187 	struct lpfc_vport  *vport = pmb->vport;
2188 	struct lpfc_dmabuf *mp;
2189 	struct lpfc_nodelist *ndlp;
2190 	struct Scsi_Host *shost;
2191 	uint16_t rpi, vpi;
2192 	int rc;
2193 
2194 	mp = (struct lpfc_dmabuf *) (pmb->context1);
2195 
2196 	if (mp) {
2197 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
2198 		kfree(mp);
2199 	}
2200 
2201 	/*
2202 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2203 	 * is in re-discovery driver need to cleanup the RPI.
2204 	 */
2205 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2206 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2207 	    !pmb->u.mb.mbxStatus) {
2208 		rpi = pmb->u.mb.un.varWords[0];
2209 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2210 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2211 		pmb->vport = vport;
2212 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2213 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2214 		if (rc != MBX_NOT_FINISHED)
2215 			return;
2216 	}
2217 
2218 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2219 		!(phba->pport->load_flag & FC_UNLOADING) &&
2220 		!pmb->u.mb.mbxStatus) {
2221 		shost = lpfc_shost_from_vport(vport);
2222 		spin_lock_irq(shost->host_lock);
2223 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2224 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2225 		spin_unlock_irq(shost->host_lock);
2226 	}
2227 
2228 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2229 		ndlp = (struct lpfc_nodelist *)pmb->context2;
2230 		lpfc_nlp_put(ndlp);
2231 		pmb->context2 = NULL;
2232 	}
2233 
2234 	/* Check security permission status on INIT_LINK mailbox command */
2235 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2236 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2237 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2238 				"2860 SLI authentication is required "
2239 				"for INIT_LINK but has not done yet\n");
2240 
2241 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2242 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2243 	else
2244 		mempool_free(pmb, phba->mbox_mem_pool);
2245 }
2246  /**
2247  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2248  * @phba: Pointer to HBA context object.
2249  * @pmb: Pointer to mailbox object.
2250  *
2251  * This function is the unreg rpi mailbox completion handler. It
2252  * frees the memory resources associated with the completed mailbox
2253  * command. An additional refrenece is put on the ndlp to prevent
2254  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2255  * the unreg mailbox command completes, this routine puts the
2256  * reference back.
2257  *
2258  **/
2259 void
2260 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2261 {
2262 	struct lpfc_vport  *vport = pmb->vport;
2263 	struct lpfc_nodelist *ndlp;
2264 
2265 	ndlp = pmb->context1;
2266 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2267 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2268 		    (bf_get(lpfc_sli_intf_if_type,
2269 		     &phba->sli4_hba.sli_intf) ==
2270 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2271 			if (ndlp) {
2272 				lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
2273 						 "0010 UNREG_LOGIN vpi:%x "
2274 						 "rpi:%x DID:%x map:%x %p\n",
2275 						 vport->vpi, ndlp->nlp_rpi,
2276 						 ndlp->nlp_DID,
2277 						 ndlp->nlp_usg_map, ndlp);
2278 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2279 				lpfc_nlp_put(ndlp);
2280 			}
2281 		}
2282 	}
2283 
2284 	mempool_free(pmb, phba->mbox_mem_pool);
2285 }
2286 
2287 /**
2288  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
2289  * @phba: Pointer to HBA context object.
2290  *
2291  * This function is called with no lock held. This function processes all
2292  * the completed mailbox commands and gives it to upper layers. The interrupt
2293  * service routine processes mailbox completion interrupt and adds completed
2294  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
2295  * Worker thread call lpfc_sli_handle_mb_event, which will return the
2296  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
2297  * function returns the mailbox commands to the upper layer by calling the
2298  * completion handler function of each mailbox.
2299  **/
2300 int
2301 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
2302 {
2303 	MAILBOX_t *pmbox;
2304 	LPFC_MBOXQ_t *pmb;
2305 	int rc;
2306 	LIST_HEAD(cmplq);
2307 
2308 	phba->sli.slistat.mbox_event++;
2309 
2310 	/* Get all completed mailboxe buffers into the cmplq */
2311 	spin_lock_irq(&phba->hbalock);
2312 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
2313 	spin_unlock_irq(&phba->hbalock);
2314 
2315 	/* Get a Mailbox buffer to setup mailbox commands for callback */
2316 	do {
2317 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
2318 		if (pmb == NULL)
2319 			break;
2320 
2321 		pmbox = &pmb->u.mb;
2322 
2323 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
2324 			if (pmb->vport) {
2325 				lpfc_debugfs_disc_trc(pmb->vport,
2326 					LPFC_DISC_TRC_MBOX_VPORT,
2327 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
2328 					(uint32_t)pmbox->mbxCommand,
2329 					pmbox->un.varWords[0],
2330 					pmbox->un.varWords[1]);
2331 			}
2332 			else {
2333 				lpfc_debugfs_disc_trc(phba->pport,
2334 					LPFC_DISC_TRC_MBOX,
2335 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
2336 					(uint32_t)pmbox->mbxCommand,
2337 					pmbox->un.varWords[0],
2338 					pmbox->un.varWords[1]);
2339 			}
2340 		}
2341 
2342 		/*
2343 		 * It is a fatal error if unknown mbox command completion.
2344 		 */
2345 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
2346 		    MBX_SHUTDOWN) {
2347 			/* Unknown mailbox command compl */
2348 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2349 					"(%d):0323 Unknown Mailbox command "
2350 					"x%x (x%x/x%x) Cmpl\n",
2351 					pmb->vport ? pmb->vport->vpi : 0,
2352 					pmbox->mbxCommand,
2353 					lpfc_sli_config_mbox_subsys_get(phba,
2354 									pmb),
2355 					lpfc_sli_config_mbox_opcode_get(phba,
2356 									pmb));
2357 			phba->link_state = LPFC_HBA_ERROR;
2358 			phba->work_hs = HS_FFER3;
2359 			lpfc_handle_eratt(phba);
2360 			continue;
2361 		}
2362 
2363 		if (pmbox->mbxStatus) {
2364 			phba->sli.slistat.mbox_stat_err++;
2365 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
2366 				/* Mbox cmd cmpl error - RETRYing */
2367 				lpfc_printf_log(phba, KERN_INFO,
2368 					LOG_MBOX | LOG_SLI,
2369 					"(%d):0305 Mbox cmd cmpl "
2370 					"error - RETRYing Data: x%x "
2371 					"(x%x/x%x) x%x x%x x%x\n",
2372 					pmb->vport ? pmb->vport->vpi : 0,
2373 					pmbox->mbxCommand,
2374 					lpfc_sli_config_mbox_subsys_get(phba,
2375 									pmb),
2376 					lpfc_sli_config_mbox_opcode_get(phba,
2377 									pmb),
2378 					pmbox->mbxStatus,
2379 					pmbox->un.varWords[0],
2380 					pmb->vport->port_state);
2381 				pmbox->mbxStatus = 0;
2382 				pmbox->mbxOwner = OWN_HOST;
2383 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2384 				if (rc != MBX_NOT_FINISHED)
2385 					continue;
2386 			}
2387 		}
2388 
2389 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
2390 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
2391 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl x%p "
2392 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
2393 				"x%x x%x x%x\n",
2394 				pmb->vport ? pmb->vport->vpi : 0,
2395 				pmbox->mbxCommand,
2396 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
2397 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
2398 				pmb->mbox_cmpl,
2399 				*((uint32_t *) pmbox),
2400 				pmbox->un.varWords[0],
2401 				pmbox->un.varWords[1],
2402 				pmbox->un.varWords[2],
2403 				pmbox->un.varWords[3],
2404 				pmbox->un.varWords[4],
2405 				pmbox->un.varWords[5],
2406 				pmbox->un.varWords[6],
2407 				pmbox->un.varWords[7],
2408 				pmbox->un.varWords[8],
2409 				pmbox->un.varWords[9],
2410 				pmbox->un.varWords[10]);
2411 
2412 		if (pmb->mbox_cmpl)
2413 			pmb->mbox_cmpl(phba,pmb);
2414 	} while (1);
2415 	return 0;
2416 }
2417 
2418 /**
2419  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
2420  * @phba: Pointer to HBA context object.
2421  * @pring: Pointer to driver SLI ring object.
2422  * @tag: buffer tag.
2423  *
2424  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
2425  * is set in the tag the buffer is posted for a particular exchange,
2426  * the function will return the buffer without replacing the buffer.
2427  * If the buffer is for unsolicited ELS or CT traffic, this function
2428  * returns the buffer and also posts another buffer to the firmware.
2429  **/
2430 static struct lpfc_dmabuf *
2431 lpfc_sli_get_buff(struct lpfc_hba *phba,
2432 		  struct lpfc_sli_ring *pring,
2433 		  uint32_t tag)
2434 {
2435 	struct hbq_dmabuf *hbq_entry;
2436 
2437 	if (tag & QUE_BUFTAG_BIT)
2438 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
2439 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
2440 	if (!hbq_entry)
2441 		return NULL;
2442 	return &hbq_entry->dbuf;
2443 }
2444 
2445 /**
2446  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
2447  * @phba: Pointer to HBA context object.
2448  * @pring: Pointer to driver SLI ring object.
2449  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
2450  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
2451  * @fch_type: the type for the first frame of the sequence.
2452  *
2453  * This function is called with no lock held. This function uses the r_ctl and
2454  * type of the received sequence to find the correct callback function to call
2455  * to process the sequence.
2456  **/
2457 static int
2458 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2459 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
2460 			 uint32_t fch_type)
2461 {
2462 	int i;
2463 
2464 	/* unSolicited Responses */
2465 	if (pring->prt[0].profile) {
2466 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
2467 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
2468 									saveq);
2469 		return 1;
2470 	}
2471 	/* We must search, based on rctl / type
2472 	   for the right routine */
2473 	for (i = 0; i < pring->num_mask; i++) {
2474 		if ((pring->prt[i].rctl == fch_r_ctl) &&
2475 		    (pring->prt[i].type == fch_type)) {
2476 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
2477 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
2478 						(phba, pring, saveq);
2479 			return 1;
2480 		}
2481 	}
2482 	return 0;
2483 }
2484 
2485 /**
2486  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
2487  * @phba: Pointer to HBA context object.
2488  * @pring: Pointer to driver SLI ring object.
2489  * @saveq: Pointer to the unsolicited iocb.
2490  *
2491  * This function is called with no lock held by the ring event handler
2492  * when there is an unsolicited iocb posted to the response ring by the
2493  * firmware. This function gets the buffer associated with the iocbs
2494  * and calls the event handler for the ring. This function handles both
2495  * qring buffers and hbq buffers.
2496  * When the function returns 1 the caller can free the iocb object otherwise
2497  * upper layer functions will free the iocb objects.
2498  **/
2499 static int
2500 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2501 			    struct lpfc_iocbq *saveq)
2502 {
2503 	IOCB_t           * irsp;
2504 	WORD5            * w5p;
2505 	uint32_t           Rctl, Type;
2506 	struct lpfc_iocbq *iocbq;
2507 	struct lpfc_dmabuf *dmzbuf;
2508 
2509 	irsp = &(saveq->iocb);
2510 
2511 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
2512 		if (pring->lpfc_sli_rcv_async_status)
2513 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
2514 		else
2515 			lpfc_printf_log(phba,
2516 					KERN_WARNING,
2517 					LOG_SLI,
2518 					"0316 Ring %d handler: unexpected "
2519 					"ASYNC_STATUS iocb received evt_code "
2520 					"0x%x\n",
2521 					pring->ringno,
2522 					irsp->un.asyncstat.evt_code);
2523 		return 1;
2524 	}
2525 
2526 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
2527 		(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
2528 		if (irsp->ulpBdeCount > 0) {
2529 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2530 					irsp->un.ulpWord[3]);
2531 			lpfc_in_buf_free(phba, dmzbuf);
2532 		}
2533 
2534 		if (irsp->ulpBdeCount > 1) {
2535 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2536 					irsp->unsli3.sli3Words[3]);
2537 			lpfc_in_buf_free(phba, dmzbuf);
2538 		}
2539 
2540 		if (irsp->ulpBdeCount > 2) {
2541 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2542 				irsp->unsli3.sli3Words[7]);
2543 			lpfc_in_buf_free(phba, dmzbuf);
2544 		}
2545 
2546 		return 1;
2547 	}
2548 
2549 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
2550 		if (irsp->ulpBdeCount != 0) {
2551 			saveq->context2 = lpfc_sli_get_buff(phba, pring,
2552 						irsp->un.ulpWord[3]);
2553 			if (!saveq->context2)
2554 				lpfc_printf_log(phba,
2555 					KERN_ERR,
2556 					LOG_SLI,
2557 					"0341 Ring %d Cannot find buffer for "
2558 					"an unsolicited iocb. tag 0x%x\n",
2559 					pring->ringno,
2560 					irsp->un.ulpWord[3]);
2561 		}
2562 		if (irsp->ulpBdeCount == 2) {
2563 			saveq->context3 = lpfc_sli_get_buff(phba, pring,
2564 						irsp->unsli3.sli3Words[7]);
2565 			if (!saveq->context3)
2566 				lpfc_printf_log(phba,
2567 					KERN_ERR,
2568 					LOG_SLI,
2569 					"0342 Ring %d Cannot find buffer for an"
2570 					" unsolicited iocb. tag 0x%x\n",
2571 					pring->ringno,
2572 					irsp->unsli3.sli3Words[7]);
2573 		}
2574 		list_for_each_entry(iocbq, &saveq->list, list) {
2575 			irsp = &(iocbq->iocb);
2576 			if (irsp->ulpBdeCount != 0) {
2577 				iocbq->context2 = lpfc_sli_get_buff(phba, pring,
2578 							irsp->un.ulpWord[3]);
2579 				if (!iocbq->context2)
2580 					lpfc_printf_log(phba,
2581 						KERN_ERR,
2582 						LOG_SLI,
2583 						"0343 Ring %d Cannot find "
2584 						"buffer for an unsolicited iocb"
2585 						". tag 0x%x\n", pring->ringno,
2586 						irsp->un.ulpWord[3]);
2587 			}
2588 			if (irsp->ulpBdeCount == 2) {
2589 				iocbq->context3 = lpfc_sli_get_buff(phba, pring,
2590 						irsp->unsli3.sli3Words[7]);
2591 				if (!iocbq->context3)
2592 					lpfc_printf_log(phba,
2593 						KERN_ERR,
2594 						LOG_SLI,
2595 						"0344 Ring %d Cannot find "
2596 						"buffer for an unsolicited "
2597 						"iocb. tag 0x%x\n",
2598 						pring->ringno,
2599 						irsp->unsli3.sli3Words[7]);
2600 			}
2601 		}
2602 	}
2603 	if (irsp->ulpBdeCount != 0 &&
2604 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
2605 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
2606 		int found = 0;
2607 
2608 		/* search continue save q for same XRI */
2609 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
2610 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
2611 				saveq->iocb.unsli3.rcvsli3.ox_id) {
2612 				list_add_tail(&saveq->list, &iocbq->list);
2613 				found = 1;
2614 				break;
2615 			}
2616 		}
2617 		if (!found)
2618 			list_add_tail(&saveq->clist,
2619 				      &pring->iocb_continue_saveq);
2620 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
2621 			list_del_init(&iocbq->clist);
2622 			saveq = iocbq;
2623 			irsp = &(saveq->iocb);
2624 		} else
2625 			return 0;
2626 	}
2627 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
2628 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
2629 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
2630 		Rctl = FC_RCTL_ELS_REQ;
2631 		Type = FC_TYPE_ELS;
2632 	} else {
2633 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
2634 		Rctl = w5p->hcsw.Rctl;
2635 		Type = w5p->hcsw.Type;
2636 
2637 		/* Firmware Workaround */
2638 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
2639 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
2640 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
2641 			Rctl = FC_RCTL_ELS_REQ;
2642 			Type = FC_TYPE_ELS;
2643 			w5p->hcsw.Rctl = Rctl;
2644 			w5p->hcsw.Type = Type;
2645 		}
2646 	}
2647 
2648 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
2649 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2650 				"0313 Ring %d handler: unexpected Rctl x%x "
2651 				"Type x%x received\n",
2652 				pring->ringno, Rctl, Type);
2653 
2654 	return 1;
2655 }
2656 
2657 /**
2658  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
2659  * @phba: Pointer to HBA context object.
2660  * @pring: Pointer to driver SLI ring object.
2661  * @prspiocb: Pointer to response iocb object.
2662  *
2663  * This function looks up the iocb_lookup table to get the command iocb
2664  * corresponding to the given response iocb using the iotag of the
2665  * response iocb. This function is called with the hbalock held.
2666  * This function returns the command iocb object if it finds the command
2667  * iocb else returns NULL.
2668  **/
2669 static struct lpfc_iocbq *
2670 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
2671 		      struct lpfc_sli_ring *pring,
2672 		      struct lpfc_iocbq *prspiocb)
2673 {
2674 	struct lpfc_iocbq *cmd_iocb = NULL;
2675 	uint16_t iotag;
2676 	lockdep_assert_held(&phba->hbalock);
2677 
2678 	iotag = prspiocb->iocb.ulpIoTag;
2679 
2680 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
2681 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
2682 		list_del_init(&cmd_iocb->list);
2683 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
2684 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
2685 		}
2686 		return cmd_iocb;
2687 	}
2688 
2689 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2690 			"0317 iotag x%x is out off "
2691 			"range: max iotag x%x wd0 x%x\n",
2692 			iotag, phba->sli.last_iotag,
2693 			*(((uint32_t *) &prspiocb->iocb) + 7));
2694 	return NULL;
2695 }
2696 
2697 /**
2698  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
2699  * @phba: Pointer to HBA context object.
2700  * @pring: Pointer to driver SLI ring object.
2701  * @iotag: IOCB tag.
2702  *
2703  * This function looks up the iocb_lookup table to get the command iocb
2704  * corresponding to the given iotag. This function is called with the
2705  * hbalock held.
2706  * This function returns the command iocb object if it finds the command
2707  * iocb else returns NULL.
2708  **/
2709 static struct lpfc_iocbq *
2710 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
2711 			     struct lpfc_sli_ring *pring, uint16_t iotag)
2712 {
2713 	struct lpfc_iocbq *cmd_iocb;
2714 
2715 	lockdep_assert_held(&phba->hbalock);
2716 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
2717 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
2718 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
2719 			/* remove from txcmpl queue list */
2720 			list_del_init(&cmd_iocb->list);
2721 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
2722 			return cmd_iocb;
2723 		}
2724 	}
2725 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2726 			"0372 iotag x%x is out off range: max iotag (x%x)\n",
2727 			iotag, phba->sli.last_iotag);
2728 	return NULL;
2729 }
2730 
2731 /**
2732  * lpfc_sli_process_sol_iocb - process solicited iocb completion
2733  * @phba: Pointer to HBA context object.
2734  * @pring: Pointer to driver SLI ring object.
2735  * @saveq: Pointer to the response iocb to be processed.
2736  *
2737  * This function is called by the ring event handler for non-fcp
2738  * rings when there is a new response iocb in the response ring.
2739  * The caller is not required to hold any locks. This function
2740  * gets the command iocb associated with the response iocb and
2741  * calls the completion handler for the command iocb. If there
2742  * is no completion handler, the function will free the resources
2743  * associated with command iocb. If the response iocb is for
2744  * an already aborted command iocb, the status of the completion
2745  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
2746  * This function always returns 1.
2747  **/
2748 static int
2749 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2750 			  struct lpfc_iocbq *saveq)
2751 {
2752 	struct lpfc_iocbq *cmdiocbp;
2753 	int rc = 1;
2754 	unsigned long iflag;
2755 
2756 	/* Based on the iotag field, get the cmd IOCB from the txcmplq */
2757 	spin_lock_irqsave(&phba->hbalock, iflag);
2758 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
2759 	spin_unlock_irqrestore(&phba->hbalock, iflag);
2760 
2761 	if (cmdiocbp) {
2762 		if (cmdiocbp->iocb_cmpl) {
2763 			/*
2764 			 * If an ELS command failed send an event to mgmt
2765 			 * application.
2766 			 */
2767 			if (saveq->iocb.ulpStatus &&
2768 			     (pring->ringno == LPFC_ELS_RING) &&
2769 			     (cmdiocbp->iocb.ulpCommand ==
2770 				CMD_ELS_REQUEST64_CR))
2771 				lpfc_send_els_failure_event(phba,
2772 					cmdiocbp, saveq);
2773 
2774 			/*
2775 			 * Post all ELS completions to the worker thread.
2776 			 * All other are passed to the completion callback.
2777 			 */
2778 			if (pring->ringno == LPFC_ELS_RING) {
2779 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
2780 				    (cmdiocbp->iocb_flag &
2781 							LPFC_DRIVER_ABORTED)) {
2782 					spin_lock_irqsave(&phba->hbalock,
2783 							  iflag);
2784 					cmdiocbp->iocb_flag &=
2785 						~LPFC_DRIVER_ABORTED;
2786 					spin_unlock_irqrestore(&phba->hbalock,
2787 							       iflag);
2788 					saveq->iocb.ulpStatus =
2789 						IOSTAT_LOCAL_REJECT;
2790 					saveq->iocb.un.ulpWord[4] =
2791 						IOERR_SLI_ABORTED;
2792 
2793 					/* Firmware could still be in progress
2794 					 * of DMAing payload, so don't free data
2795 					 * buffer till after a hbeat.
2796 					 */
2797 					spin_lock_irqsave(&phba->hbalock,
2798 							  iflag);
2799 					saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
2800 					spin_unlock_irqrestore(&phba->hbalock,
2801 							       iflag);
2802 				}
2803 				if (phba->sli_rev == LPFC_SLI_REV4) {
2804 					if (saveq->iocb_flag &
2805 					    LPFC_EXCHANGE_BUSY) {
2806 						/* Set cmdiocb flag for the
2807 						 * exchange busy so sgl (xri)
2808 						 * will not be released until
2809 						 * the abort xri is received
2810 						 * from hba.
2811 						 */
2812 						spin_lock_irqsave(
2813 							&phba->hbalock, iflag);
2814 						cmdiocbp->iocb_flag |=
2815 							LPFC_EXCHANGE_BUSY;
2816 						spin_unlock_irqrestore(
2817 							&phba->hbalock, iflag);
2818 					}
2819 					if (cmdiocbp->iocb_flag &
2820 					    LPFC_DRIVER_ABORTED) {
2821 						/*
2822 						 * Clear LPFC_DRIVER_ABORTED
2823 						 * bit in case it was driver
2824 						 * initiated abort.
2825 						 */
2826 						spin_lock_irqsave(
2827 							&phba->hbalock, iflag);
2828 						cmdiocbp->iocb_flag &=
2829 							~LPFC_DRIVER_ABORTED;
2830 						spin_unlock_irqrestore(
2831 							&phba->hbalock, iflag);
2832 						cmdiocbp->iocb.ulpStatus =
2833 							IOSTAT_LOCAL_REJECT;
2834 						cmdiocbp->iocb.un.ulpWord[4] =
2835 							IOERR_ABORT_REQUESTED;
2836 						/*
2837 						 * For SLI4, irsiocb contains
2838 						 * NO_XRI in sli_xritag, it
2839 						 * shall not affect releasing
2840 						 * sgl (xri) process.
2841 						 */
2842 						saveq->iocb.ulpStatus =
2843 							IOSTAT_LOCAL_REJECT;
2844 						saveq->iocb.un.ulpWord[4] =
2845 							IOERR_SLI_ABORTED;
2846 						spin_lock_irqsave(
2847 							&phba->hbalock, iflag);
2848 						saveq->iocb_flag |=
2849 							LPFC_DELAY_MEM_FREE;
2850 						spin_unlock_irqrestore(
2851 							&phba->hbalock, iflag);
2852 					}
2853 				}
2854 			}
2855 			(cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
2856 		} else
2857 			lpfc_sli_release_iocbq(phba, cmdiocbp);
2858 	} else {
2859 		/*
2860 		 * Unknown initiating command based on the response iotag.
2861 		 * This could be the case on the ELS ring because of
2862 		 * lpfc_els_abort().
2863 		 */
2864 		if (pring->ringno != LPFC_ELS_RING) {
2865 			/*
2866 			 * Ring <ringno> handler: unexpected completion IoTag
2867 			 * <IoTag>
2868 			 */
2869 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2870 					 "0322 Ring %d handler: "
2871 					 "unexpected completion IoTag x%x "
2872 					 "Data: x%x x%x x%x x%x\n",
2873 					 pring->ringno,
2874 					 saveq->iocb.ulpIoTag,
2875 					 saveq->iocb.ulpStatus,
2876 					 saveq->iocb.un.ulpWord[4],
2877 					 saveq->iocb.ulpCommand,
2878 					 saveq->iocb.ulpContext);
2879 		}
2880 	}
2881 
2882 	return rc;
2883 }
2884 
2885 /**
2886  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
2887  * @phba: Pointer to HBA context object.
2888  * @pring: Pointer to driver SLI ring object.
2889  *
2890  * This function is called from the iocb ring event handlers when
2891  * put pointer is ahead of the get pointer for a ring. This function signal
2892  * an error attention condition to the worker thread and the worker
2893  * thread will transition the HBA to offline state.
2894  **/
2895 static void
2896 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2897 {
2898 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2899 	/*
2900 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
2901 	 * rsp ring <portRspMax>
2902 	 */
2903 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2904 			"0312 Ring %d handler: portRspPut %d "
2905 			"is bigger than rsp ring %d\n",
2906 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
2907 			pring->sli.sli3.numRiocb);
2908 
2909 	phba->link_state = LPFC_HBA_ERROR;
2910 
2911 	/*
2912 	 * All error attention handlers are posted to
2913 	 * worker thread
2914 	 */
2915 	phba->work_ha |= HA_ERATT;
2916 	phba->work_hs = HS_FFER3;
2917 
2918 	lpfc_worker_wake_up(phba);
2919 
2920 	return;
2921 }
2922 
2923 /**
2924  * lpfc_poll_eratt - Error attention polling timer timeout handler
2925  * @ptr: Pointer to address of HBA context object.
2926  *
2927  * This function is invoked by the Error Attention polling timer when the
2928  * timer times out. It will check the SLI Error Attention register for
2929  * possible attention events. If so, it will post an Error Attention event
2930  * and wake up worker thread to process it. Otherwise, it will set up the
2931  * Error Attention polling timer for the next poll.
2932  **/
2933 void lpfc_poll_eratt(unsigned long ptr)
2934 {
2935 	struct lpfc_hba *phba;
2936 	uint32_t eratt = 0;
2937 	uint64_t sli_intr, cnt;
2938 
2939 	phba = (struct lpfc_hba *)ptr;
2940 
2941 	/* Here we will also keep track of interrupts per sec of the hba */
2942 	sli_intr = phba->sli.slistat.sli_intr;
2943 
2944 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
2945 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
2946 			sli_intr);
2947 	else
2948 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
2949 
2950 	/* 64-bit integer division not supporte on 32-bit x86 - use do_div */
2951 	do_div(cnt, LPFC_ERATT_POLL_INTERVAL);
2952 	phba->sli.slistat.sli_ips = cnt;
2953 
2954 	phba->sli.slistat.sli_prev_intr = sli_intr;
2955 
2956 	/* Check chip HA register for error event */
2957 	eratt = lpfc_sli_check_eratt(phba);
2958 
2959 	if (eratt)
2960 		/* Tell the worker thread there is work to do */
2961 		lpfc_worker_wake_up(phba);
2962 	else
2963 		/* Restart the timer for next eratt poll */
2964 		mod_timer(&phba->eratt_poll,
2965 			  jiffies +
2966 			  msecs_to_jiffies(1000 * LPFC_ERATT_POLL_INTERVAL));
2967 	return;
2968 }
2969 
2970 
2971 /**
2972  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
2973  * @phba: Pointer to HBA context object.
2974  * @pring: Pointer to driver SLI ring object.
2975  * @mask: Host attention register mask for this ring.
2976  *
2977  * This function is called from the interrupt context when there is a ring
2978  * event for the fcp ring. The caller does not hold any lock.
2979  * The function processes each response iocb in the response ring until it
2980  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
2981  * LE bit set. The function will call the completion handler of the command iocb
2982  * if the response iocb indicates a completion for a command iocb or it is
2983  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
2984  * function if this is an unsolicited iocb.
2985  * This routine presumes LPFC_FCP_RING handling and doesn't bother
2986  * to check it explicitly.
2987  */
2988 int
2989 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
2990 				struct lpfc_sli_ring *pring, uint32_t mask)
2991 {
2992 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2993 	IOCB_t *irsp = NULL;
2994 	IOCB_t *entry = NULL;
2995 	struct lpfc_iocbq *cmdiocbq = NULL;
2996 	struct lpfc_iocbq rspiocbq;
2997 	uint32_t status;
2998 	uint32_t portRspPut, portRspMax;
2999 	int rc = 1;
3000 	lpfc_iocb_type type;
3001 	unsigned long iflag;
3002 	uint32_t rsp_cmpl = 0;
3003 
3004 	spin_lock_irqsave(&phba->hbalock, iflag);
3005 	pring->stats.iocb_event++;
3006 
3007 	/*
3008 	 * The next available response entry should never exceed the maximum
3009 	 * entries.  If it does, treat it as an adapter hardware error.
3010 	 */
3011 	portRspMax = pring->sli.sli3.numRiocb;
3012 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3013 	if (unlikely(portRspPut >= portRspMax)) {
3014 		lpfc_sli_rsp_pointers_error(phba, pring);
3015 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3016 		return 1;
3017 	}
3018 	if (phba->fcp_ring_in_use) {
3019 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3020 		return 1;
3021 	} else
3022 		phba->fcp_ring_in_use = 1;
3023 
3024 	rmb();
3025 	while (pring->sli.sli3.rspidx != portRspPut) {
3026 		/*
3027 		 * Fetch an entry off the ring and copy it into a local data
3028 		 * structure.  The copy involves a byte-swap since the
3029 		 * network byte order and pci byte orders are different.
3030 		 */
3031 		entry = lpfc_resp_iocb(phba, pring);
3032 		phba->last_completion_time = jiffies;
3033 
3034 		if (++pring->sli.sli3.rspidx >= portRspMax)
3035 			pring->sli.sli3.rspidx = 0;
3036 
3037 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3038 				      (uint32_t *) &rspiocbq.iocb,
3039 				      phba->iocb_rsp_size);
3040 		INIT_LIST_HEAD(&(rspiocbq.list));
3041 		irsp = &rspiocbq.iocb;
3042 
3043 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3044 		pring->stats.iocb_rsp++;
3045 		rsp_cmpl++;
3046 
3047 		if (unlikely(irsp->ulpStatus)) {
3048 			/*
3049 			 * If resource errors reported from HBA, reduce
3050 			 * queuedepths of the SCSI device.
3051 			 */
3052 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3053 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3054 			     IOERR_NO_RESOURCES)) {
3055 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3056 				phba->lpfc_rampdown_queue_depth(phba);
3057 				spin_lock_irqsave(&phba->hbalock, iflag);
3058 			}
3059 
3060 			/* Rsp ring <ringno> error: IOCB */
3061 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3062 					"0336 Rsp Ring %d error: IOCB Data: "
3063 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
3064 					pring->ringno,
3065 					irsp->un.ulpWord[0],
3066 					irsp->un.ulpWord[1],
3067 					irsp->un.ulpWord[2],
3068 					irsp->un.ulpWord[3],
3069 					irsp->un.ulpWord[4],
3070 					irsp->un.ulpWord[5],
3071 					*(uint32_t *)&irsp->un1,
3072 					*((uint32_t *)&irsp->un1 + 1));
3073 		}
3074 
3075 		switch (type) {
3076 		case LPFC_ABORT_IOCB:
3077 		case LPFC_SOL_IOCB:
3078 			/*
3079 			 * Idle exchange closed via ABTS from port.  No iocb
3080 			 * resources need to be recovered.
3081 			 */
3082 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3083 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3084 						"0333 IOCB cmd 0x%x"
3085 						" processed. Skipping"
3086 						" completion\n",
3087 						irsp->ulpCommand);
3088 				break;
3089 			}
3090 
3091 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3092 							 &rspiocbq);
3093 			if (unlikely(!cmdiocbq))
3094 				break;
3095 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3096 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3097 			if (cmdiocbq->iocb_cmpl) {
3098 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3099 				(cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
3100 						      &rspiocbq);
3101 				spin_lock_irqsave(&phba->hbalock, iflag);
3102 			}
3103 			break;
3104 		case LPFC_UNSOL_IOCB:
3105 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3106 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
3107 			spin_lock_irqsave(&phba->hbalock, iflag);
3108 			break;
3109 		default:
3110 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3111 				char adaptermsg[LPFC_MAX_ADPTMSG];
3112 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3113 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
3114 				       MAX_MSG_DATA);
3115 				dev_warn(&((phba->pcidev)->dev),
3116 					 "lpfc%d: %s\n",
3117 					 phba->brd_no, adaptermsg);
3118 			} else {
3119 				/* Unknown IOCB command */
3120 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3121 						"0334 Unknown IOCB command "
3122 						"Data: x%x, x%x x%x x%x x%x\n",
3123 						type, irsp->ulpCommand,
3124 						irsp->ulpStatus,
3125 						irsp->ulpIoTag,
3126 						irsp->ulpContext);
3127 			}
3128 			break;
3129 		}
3130 
3131 		/*
3132 		 * The response IOCB has been processed.  Update the ring
3133 		 * pointer in SLIM.  If the port response put pointer has not
3134 		 * been updated, sync the pgp->rspPutInx and fetch the new port
3135 		 * response put pointer.
3136 		 */
3137 		writel(pring->sli.sli3.rspidx,
3138 			&phba->host_gp[pring->ringno].rspGetInx);
3139 
3140 		if (pring->sli.sli3.rspidx == portRspPut)
3141 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3142 	}
3143 
3144 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
3145 		pring->stats.iocb_rsp_full++;
3146 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3147 		writel(status, phba->CAregaddr);
3148 		readl(phba->CAregaddr);
3149 	}
3150 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3151 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3152 		pring->stats.iocb_cmd_empty++;
3153 
3154 		/* Force update of the local copy of cmdGetInx */
3155 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3156 		lpfc_sli_resume_iocb(phba, pring);
3157 
3158 		if ((pring->lpfc_sli_cmd_available))
3159 			(pring->lpfc_sli_cmd_available) (phba, pring);
3160 
3161 	}
3162 
3163 	phba->fcp_ring_in_use = 0;
3164 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3165 	return rc;
3166 }
3167 
3168 /**
3169  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
3170  * @phba: Pointer to HBA context object.
3171  * @pring: Pointer to driver SLI ring object.
3172  * @rspiocbp: Pointer to driver response IOCB object.
3173  *
3174  * This function is called from the worker thread when there is a slow-path
3175  * response IOCB to process. This function chains all the response iocbs until
3176  * seeing the iocb with the LE bit set. The function will call
3177  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
3178  * completion of a command iocb. The function will call the
3179  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
3180  * The function frees the resources or calls the completion handler if this
3181  * iocb is an abort completion. The function returns NULL when the response
3182  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
3183  * this function shall chain the iocb on to the iocb_continueq and return the
3184  * response iocb passed in.
3185  **/
3186 static struct lpfc_iocbq *
3187 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3188 			struct lpfc_iocbq *rspiocbp)
3189 {
3190 	struct lpfc_iocbq *saveq;
3191 	struct lpfc_iocbq *cmdiocbp;
3192 	struct lpfc_iocbq *next_iocb;
3193 	IOCB_t *irsp = NULL;
3194 	uint32_t free_saveq;
3195 	uint8_t iocb_cmd_type;
3196 	lpfc_iocb_type type;
3197 	unsigned long iflag;
3198 	int rc;
3199 
3200 	spin_lock_irqsave(&phba->hbalock, iflag);
3201 	/* First add the response iocb to the countinueq list */
3202 	list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
3203 	pring->iocb_continueq_cnt++;
3204 
3205 	/* Now, determine whether the list is completed for processing */
3206 	irsp = &rspiocbp->iocb;
3207 	if (irsp->ulpLe) {
3208 		/*
3209 		 * By default, the driver expects to free all resources
3210 		 * associated with this iocb completion.
3211 		 */
3212 		free_saveq = 1;
3213 		saveq = list_get_first(&pring->iocb_continueq,
3214 				       struct lpfc_iocbq, list);
3215 		irsp = &(saveq->iocb);
3216 		list_del_init(&pring->iocb_continueq);
3217 		pring->iocb_continueq_cnt = 0;
3218 
3219 		pring->stats.iocb_rsp++;
3220 
3221 		/*
3222 		 * If resource errors reported from HBA, reduce
3223 		 * queuedepths of the SCSI device.
3224 		 */
3225 		if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3226 		    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3227 		     IOERR_NO_RESOURCES)) {
3228 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3229 			phba->lpfc_rampdown_queue_depth(phba);
3230 			spin_lock_irqsave(&phba->hbalock, iflag);
3231 		}
3232 
3233 		if (irsp->ulpStatus) {
3234 			/* Rsp ring <ringno> error: IOCB */
3235 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3236 					"0328 Rsp Ring %d error: "
3237 					"IOCB Data: "
3238 					"x%x x%x x%x x%x "
3239 					"x%x x%x x%x x%x "
3240 					"x%x x%x x%x x%x "
3241 					"x%x x%x x%x x%x\n",
3242 					pring->ringno,
3243 					irsp->un.ulpWord[0],
3244 					irsp->un.ulpWord[1],
3245 					irsp->un.ulpWord[2],
3246 					irsp->un.ulpWord[3],
3247 					irsp->un.ulpWord[4],
3248 					irsp->un.ulpWord[5],
3249 					*(((uint32_t *) irsp) + 6),
3250 					*(((uint32_t *) irsp) + 7),
3251 					*(((uint32_t *) irsp) + 8),
3252 					*(((uint32_t *) irsp) + 9),
3253 					*(((uint32_t *) irsp) + 10),
3254 					*(((uint32_t *) irsp) + 11),
3255 					*(((uint32_t *) irsp) + 12),
3256 					*(((uint32_t *) irsp) + 13),
3257 					*(((uint32_t *) irsp) + 14),
3258 					*(((uint32_t *) irsp) + 15));
3259 		}
3260 
3261 		/*
3262 		 * Fetch the IOCB command type and call the correct completion
3263 		 * routine. Solicited and Unsolicited IOCBs on the ELS ring
3264 		 * get freed back to the lpfc_iocb_list by the discovery
3265 		 * kernel thread.
3266 		 */
3267 		iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
3268 		type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
3269 		switch (type) {
3270 		case LPFC_SOL_IOCB:
3271 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3272 			rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
3273 			spin_lock_irqsave(&phba->hbalock, iflag);
3274 			break;
3275 
3276 		case LPFC_UNSOL_IOCB:
3277 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3278 			rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
3279 			spin_lock_irqsave(&phba->hbalock, iflag);
3280 			if (!rc)
3281 				free_saveq = 0;
3282 			break;
3283 
3284 		case LPFC_ABORT_IOCB:
3285 			cmdiocbp = NULL;
3286 			if (irsp->ulpCommand != CMD_XRI_ABORTED_CX)
3287 				cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
3288 								 saveq);
3289 			if (cmdiocbp) {
3290 				/* Call the specified completion routine */
3291 				if (cmdiocbp->iocb_cmpl) {
3292 					spin_unlock_irqrestore(&phba->hbalock,
3293 							       iflag);
3294 					(cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
3295 							      saveq);
3296 					spin_lock_irqsave(&phba->hbalock,
3297 							  iflag);
3298 				} else
3299 					__lpfc_sli_release_iocbq(phba,
3300 								 cmdiocbp);
3301 			}
3302 			break;
3303 
3304 		case LPFC_UNKNOWN_IOCB:
3305 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3306 				char adaptermsg[LPFC_MAX_ADPTMSG];
3307 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3308 				memcpy(&adaptermsg[0], (uint8_t *)irsp,
3309 				       MAX_MSG_DATA);
3310 				dev_warn(&((phba->pcidev)->dev),
3311 					 "lpfc%d: %s\n",
3312 					 phba->brd_no, adaptermsg);
3313 			} else {
3314 				/* Unknown IOCB command */
3315 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3316 						"0335 Unknown IOCB "
3317 						"command Data: x%x "
3318 						"x%x x%x x%x\n",
3319 						irsp->ulpCommand,
3320 						irsp->ulpStatus,
3321 						irsp->ulpIoTag,
3322 						irsp->ulpContext);
3323 			}
3324 			break;
3325 		}
3326 
3327 		if (free_saveq) {
3328 			list_for_each_entry_safe(rspiocbp, next_iocb,
3329 						 &saveq->list, list) {
3330 				list_del_init(&rspiocbp->list);
3331 				__lpfc_sli_release_iocbq(phba, rspiocbp);
3332 			}
3333 			__lpfc_sli_release_iocbq(phba, saveq);
3334 		}
3335 		rspiocbp = NULL;
3336 	}
3337 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3338 	return rspiocbp;
3339 }
3340 
3341 /**
3342  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
3343  * @phba: Pointer to HBA context object.
3344  * @pring: Pointer to driver SLI ring object.
3345  * @mask: Host attention register mask for this ring.
3346  *
3347  * This routine wraps the actual slow_ring event process routine from the
3348  * API jump table function pointer from the lpfc_hba struct.
3349  **/
3350 void
3351 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
3352 				struct lpfc_sli_ring *pring, uint32_t mask)
3353 {
3354 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
3355 }
3356 
3357 /**
3358  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
3359  * @phba: Pointer to HBA context object.
3360  * @pring: Pointer to driver SLI ring object.
3361  * @mask: Host attention register mask for this ring.
3362  *
3363  * This function is called from the worker thread when there is a ring event
3364  * for non-fcp rings. The caller does not hold any lock. The function will
3365  * remove each response iocb in the response ring and calls the handle
3366  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3367  **/
3368 static void
3369 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
3370 				   struct lpfc_sli_ring *pring, uint32_t mask)
3371 {
3372 	struct lpfc_pgp *pgp;
3373 	IOCB_t *entry;
3374 	IOCB_t *irsp = NULL;
3375 	struct lpfc_iocbq *rspiocbp = NULL;
3376 	uint32_t portRspPut, portRspMax;
3377 	unsigned long iflag;
3378 	uint32_t status;
3379 
3380 	pgp = &phba->port_gp[pring->ringno];
3381 	spin_lock_irqsave(&phba->hbalock, iflag);
3382 	pring->stats.iocb_event++;
3383 
3384 	/*
3385 	 * The next available response entry should never exceed the maximum
3386 	 * entries.  If it does, treat it as an adapter hardware error.
3387 	 */
3388 	portRspMax = pring->sli.sli3.numRiocb;
3389 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3390 	if (portRspPut >= portRspMax) {
3391 		/*
3392 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3393 		 * rsp ring <portRspMax>
3394 		 */
3395 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3396 				"0303 Ring %d handler: portRspPut %d "
3397 				"is bigger than rsp ring %d\n",
3398 				pring->ringno, portRspPut, portRspMax);
3399 
3400 		phba->link_state = LPFC_HBA_ERROR;
3401 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3402 
3403 		phba->work_hs = HS_FFER3;
3404 		lpfc_handle_eratt(phba);
3405 
3406 		return;
3407 	}
3408 
3409 	rmb();
3410 	while (pring->sli.sli3.rspidx != portRspPut) {
3411 		/*
3412 		 * Build a completion list and call the appropriate handler.
3413 		 * The process is to get the next available response iocb, get
3414 		 * a free iocb from the list, copy the response data into the
3415 		 * free iocb, insert to the continuation list, and update the
3416 		 * next response index to slim.  This process makes response
3417 		 * iocb's in the ring available to DMA as fast as possible but
3418 		 * pays a penalty for a copy operation.  Since the iocb is
3419 		 * only 32 bytes, this penalty is considered small relative to
3420 		 * the PCI reads for register values and a slim write.  When
3421 		 * the ulpLe field is set, the entire Command has been
3422 		 * received.
3423 		 */
3424 		entry = lpfc_resp_iocb(phba, pring);
3425 
3426 		phba->last_completion_time = jiffies;
3427 		rspiocbp = __lpfc_sli_get_iocbq(phba);
3428 		if (rspiocbp == NULL) {
3429 			printk(KERN_ERR "%s: out of buffers! Failing "
3430 			       "completion.\n", __func__);
3431 			break;
3432 		}
3433 
3434 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
3435 				      phba->iocb_rsp_size);
3436 		irsp = &rspiocbp->iocb;
3437 
3438 		if (++pring->sli.sli3.rspidx >= portRspMax)
3439 			pring->sli.sli3.rspidx = 0;
3440 
3441 		if (pring->ringno == LPFC_ELS_RING) {
3442 			lpfc_debugfs_slow_ring_trc(phba,
3443 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
3444 				*(((uint32_t *) irsp) + 4),
3445 				*(((uint32_t *) irsp) + 6),
3446 				*(((uint32_t *) irsp) + 7));
3447 		}
3448 
3449 		writel(pring->sli.sli3.rspidx,
3450 			&phba->host_gp[pring->ringno].rspGetInx);
3451 
3452 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3453 		/* Handle the response IOCB */
3454 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
3455 		spin_lock_irqsave(&phba->hbalock, iflag);
3456 
3457 		/*
3458 		 * If the port response put pointer has not been updated, sync
3459 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
3460 		 * response put pointer.
3461 		 */
3462 		if (pring->sli.sli3.rspidx == portRspPut) {
3463 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3464 		}
3465 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
3466 
3467 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
3468 		/* At least one response entry has been freed */
3469 		pring->stats.iocb_rsp_full++;
3470 		/* SET RxRE_RSP in Chip Att register */
3471 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3472 		writel(status, phba->CAregaddr);
3473 		readl(phba->CAregaddr); /* flush */
3474 	}
3475 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3476 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3477 		pring->stats.iocb_cmd_empty++;
3478 
3479 		/* Force update of the local copy of cmdGetInx */
3480 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3481 		lpfc_sli_resume_iocb(phba, pring);
3482 
3483 		if ((pring->lpfc_sli_cmd_available))
3484 			(pring->lpfc_sli_cmd_available) (phba, pring);
3485 
3486 	}
3487 
3488 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3489 	return;
3490 }
3491 
3492 /**
3493  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
3494  * @phba: Pointer to HBA context object.
3495  * @pring: Pointer to driver SLI ring object.
3496  * @mask: Host attention register mask for this ring.
3497  *
3498  * This function is called from the worker thread when there is a pending
3499  * ELS response iocb on the driver internal slow-path response iocb worker
3500  * queue. The caller does not hold any lock. The function will remove each
3501  * response iocb from the response worker queue and calls the handle
3502  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3503  **/
3504 static void
3505 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
3506 				   struct lpfc_sli_ring *pring, uint32_t mask)
3507 {
3508 	struct lpfc_iocbq *irspiocbq;
3509 	struct hbq_dmabuf *dmabuf;
3510 	struct lpfc_cq_event *cq_event;
3511 	unsigned long iflag;
3512 
3513 	spin_lock_irqsave(&phba->hbalock, iflag);
3514 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
3515 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3516 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
3517 		/* Get the response iocb from the head of work queue */
3518 		spin_lock_irqsave(&phba->hbalock, iflag);
3519 		list_remove_head(&phba->sli4_hba.sp_queue_event,
3520 				 cq_event, struct lpfc_cq_event, list);
3521 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3522 
3523 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
3524 		case CQE_CODE_COMPL_WQE:
3525 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
3526 						 cq_event);
3527 			/* Translate ELS WCQE to response IOCBQ */
3528 			irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
3529 								   irspiocbq);
3530 			if (irspiocbq)
3531 				lpfc_sli_sp_handle_rspiocb(phba, pring,
3532 							   irspiocbq);
3533 			break;
3534 		case CQE_CODE_RECEIVE:
3535 		case CQE_CODE_RECEIVE_V1:
3536 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
3537 					      cq_event);
3538 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
3539 			break;
3540 		default:
3541 			break;
3542 		}
3543 	}
3544 }
3545 
3546 /**
3547  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
3548  * @phba: Pointer to HBA context object.
3549  * @pring: Pointer to driver SLI ring object.
3550  *
3551  * This function aborts all iocbs in the given ring and frees all the iocb
3552  * objects in txq. This function issues an abort iocb for all the iocb commands
3553  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3554  * the return of this function. The caller is not required to hold any locks.
3555  **/
3556 void
3557 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3558 {
3559 	LIST_HEAD(completions);
3560 	struct lpfc_iocbq *iocb, *next_iocb;
3561 
3562 	if (pring->ringno == LPFC_ELS_RING) {
3563 		lpfc_fabric_abort_hba(phba);
3564 	}
3565 
3566 	/* Error everything on txq and txcmplq
3567 	 * First do the txq.
3568 	 */
3569 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3570 		spin_lock_irq(&pring->ring_lock);
3571 		list_splice_init(&pring->txq, &completions);
3572 		pring->txq_cnt = 0;
3573 		spin_unlock_irq(&pring->ring_lock);
3574 
3575 		spin_lock_irq(&phba->hbalock);
3576 		/* Next issue ABTS for everything on the txcmplq */
3577 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3578 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3579 		spin_unlock_irq(&phba->hbalock);
3580 	} else {
3581 		spin_lock_irq(&phba->hbalock);
3582 		list_splice_init(&pring->txq, &completions);
3583 		pring->txq_cnt = 0;
3584 
3585 		/* Next issue ABTS for everything on the txcmplq */
3586 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3587 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3588 		spin_unlock_irq(&phba->hbalock);
3589 	}
3590 
3591 	/* Cancel all the IOCBs from the completions list */
3592 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
3593 			      IOERR_SLI_ABORTED);
3594 }
3595 
3596 /**
3597  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
3598  * @phba: Pointer to HBA context object.
3599  * @pring: Pointer to driver SLI ring object.
3600  *
3601  * This function aborts all iocbs in FCP rings and frees all the iocb
3602  * objects in txq. This function issues an abort iocb for all the iocb commands
3603  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3604  * the return of this function. The caller is not required to hold any locks.
3605  **/
3606 void
3607 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
3608 {
3609 	struct lpfc_sli *psli = &phba->sli;
3610 	struct lpfc_sli_ring  *pring;
3611 	uint32_t i;
3612 
3613 	/* Look on all the FCP Rings for the iotag */
3614 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3615 		for (i = 0; i < phba->cfg_fcp_io_channel; i++) {
3616 			pring = &psli->ring[i + MAX_SLI3_CONFIGURED_RINGS];
3617 			lpfc_sli_abort_iocb_ring(phba, pring);
3618 		}
3619 	} else {
3620 		pring = &psli->ring[psli->fcp_ring];
3621 		lpfc_sli_abort_iocb_ring(phba, pring);
3622 	}
3623 }
3624 
3625 
3626 /**
3627  * lpfc_sli_flush_fcp_rings - flush all iocbs in the fcp ring
3628  * @phba: Pointer to HBA context object.
3629  *
3630  * This function flushes all iocbs in the fcp ring and frees all the iocb
3631  * objects in txq and txcmplq. This function will not issue abort iocbs
3632  * for all the iocb commands in txcmplq, they will just be returned with
3633  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
3634  * slot has been permanently disabled.
3635  **/
3636 void
3637 lpfc_sli_flush_fcp_rings(struct lpfc_hba *phba)
3638 {
3639 	LIST_HEAD(txq);
3640 	LIST_HEAD(txcmplq);
3641 	struct lpfc_sli *psli = &phba->sli;
3642 	struct lpfc_sli_ring  *pring;
3643 	uint32_t i;
3644 
3645 	spin_lock_irq(&phba->hbalock);
3646 	/* Indicate the I/O queues are flushed */
3647 	phba->hba_flag |= HBA_FCP_IOQ_FLUSH;
3648 	spin_unlock_irq(&phba->hbalock);
3649 
3650 	/* Look on all the FCP Rings for the iotag */
3651 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3652 		for (i = 0; i < phba->cfg_fcp_io_channel; i++) {
3653 			pring = &psli->ring[i + MAX_SLI3_CONFIGURED_RINGS];
3654 
3655 			spin_lock_irq(&pring->ring_lock);
3656 			/* Retrieve everything on txq */
3657 			list_splice_init(&pring->txq, &txq);
3658 			/* Retrieve everything on the txcmplq */
3659 			list_splice_init(&pring->txcmplq, &txcmplq);
3660 			pring->txq_cnt = 0;
3661 			pring->txcmplq_cnt = 0;
3662 			spin_unlock_irq(&pring->ring_lock);
3663 
3664 			/* Flush the txq */
3665 			lpfc_sli_cancel_iocbs(phba, &txq,
3666 					      IOSTAT_LOCAL_REJECT,
3667 					      IOERR_SLI_DOWN);
3668 			/* Flush the txcmpq */
3669 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
3670 					      IOSTAT_LOCAL_REJECT,
3671 					      IOERR_SLI_DOWN);
3672 		}
3673 	} else {
3674 		pring = &psli->ring[psli->fcp_ring];
3675 
3676 		spin_lock_irq(&phba->hbalock);
3677 		/* Retrieve everything on txq */
3678 		list_splice_init(&pring->txq, &txq);
3679 		/* Retrieve everything on the txcmplq */
3680 		list_splice_init(&pring->txcmplq, &txcmplq);
3681 		pring->txq_cnt = 0;
3682 		pring->txcmplq_cnt = 0;
3683 		spin_unlock_irq(&phba->hbalock);
3684 
3685 		/* Flush the txq */
3686 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
3687 				      IOERR_SLI_DOWN);
3688 		/* Flush the txcmpq */
3689 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
3690 				      IOERR_SLI_DOWN);
3691 	}
3692 }
3693 
3694 /**
3695  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
3696  * @phba: Pointer to HBA context object.
3697  * @mask: Bit mask to be checked.
3698  *
3699  * This function reads the host status register and compares
3700  * with the provided bit mask to check if HBA completed
3701  * the restart. This function will wait in a loop for the
3702  * HBA to complete restart. If the HBA does not restart within
3703  * 15 iterations, the function will reset the HBA again. The
3704  * function returns 1 when HBA fail to restart otherwise returns
3705  * zero.
3706  **/
3707 static int
3708 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
3709 {
3710 	uint32_t status;
3711 	int i = 0;
3712 	int retval = 0;
3713 
3714 	/* Read the HBA Host Status Register */
3715 	if (lpfc_readl(phba->HSregaddr, &status))
3716 		return 1;
3717 
3718 	/*
3719 	 * Check status register every 100ms for 5 retries, then every
3720 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
3721 	 * every 2.5 sec for 4.
3722 	 * Break our of the loop if errors occurred during init.
3723 	 */
3724 	while (((status & mask) != mask) &&
3725 	       !(status & HS_FFERM) &&
3726 	       i++ < 20) {
3727 
3728 		if (i <= 5)
3729 			msleep(10);
3730 		else if (i <= 10)
3731 			msleep(500);
3732 		else
3733 			msleep(2500);
3734 
3735 		if (i == 15) {
3736 				/* Do post */
3737 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
3738 			lpfc_sli_brdrestart(phba);
3739 		}
3740 		/* Read the HBA Host Status Register */
3741 		if (lpfc_readl(phba->HSregaddr, &status)) {
3742 			retval = 1;
3743 			break;
3744 		}
3745 	}
3746 
3747 	/* Check to see if any errors occurred during init */
3748 	if ((status & HS_FFERM) || (i >= 20)) {
3749 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3750 				"2751 Adapter failed to restart, "
3751 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
3752 				status,
3753 				readl(phba->MBslimaddr + 0xa8),
3754 				readl(phba->MBslimaddr + 0xac));
3755 		phba->link_state = LPFC_HBA_ERROR;
3756 		retval = 1;
3757 	}
3758 
3759 	return retval;
3760 }
3761 
3762 /**
3763  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
3764  * @phba: Pointer to HBA context object.
3765  * @mask: Bit mask to be checked.
3766  *
3767  * This function checks the host status register to check if HBA is
3768  * ready. This function will wait in a loop for the HBA to be ready
3769  * If the HBA is not ready , the function will will reset the HBA PCI
3770  * function again. The function returns 1 when HBA fail to be ready
3771  * otherwise returns zero.
3772  **/
3773 static int
3774 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
3775 {
3776 	uint32_t status;
3777 	int retval = 0;
3778 
3779 	/* Read the HBA Host Status Register */
3780 	status = lpfc_sli4_post_status_check(phba);
3781 
3782 	if (status) {
3783 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
3784 		lpfc_sli_brdrestart(phba);
3785 		status = lpfc_sli4_post_status_check(phba);
3786 	}
3787 
3788 	/* Check to see if any errors occurred during init */
3789 	if (status) {
3790 		phba->link_state = LPFC_HBA_ERROR;
3791 		retval = 1;
3792 	} else
3793 		phba->sli4_hba.intr_enable = 0;
3794 
3795 	return retval;
3796 }
3797 
3798 /**
3799  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
3800  * @phba: Pointer to HBA context object.
3801  * @mask: Bit mask to be checked.
3802  *
3803  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
3804  * from the API jump table function pointer from the lpfc_hba struct.
3805  **/
3806 int
3807 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
3808 {
3809 	return phba->lpfc_sli_brdready(phba, mask);
3810 }
3811 
3812 #define BARRIER_TEST_PATTERN (0xdeadbeef)
3813 
3814 /**
3815  * lpfc_reset_barrier - Make HBA ready for HBA reset
3816  * @phba: Pointer to HBA context object.
3817  *
3818  * This function is called before resetting an HBA. This function is called
3819  * with hbalock held and requests HBA to quiesce DMAs before a reset.
3820  **/
3821 void lpfc_reset_barrier(struct lpfc_hba *phba)
3822 {
3823 	uint32_t __iomem *resp_buf;
3824 	uint32_t __iomem *mbox_buf;
3825 	volatile uint32_t mbox;
3826 	uint32_t hc_copy, ha_copy, resp_data;
3827 	int  i;
3828 	uint8_t hdrtype;
3829 
3830 	lockdep_assert_held(&phba->hbalock);
3831 
3832 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
3833 	if (hdrtype != 0x80 ||
3834 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
3835 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
3836 		return;
3837 
3838 	/*
3839 	 * Tell the other part of the chip to suspend temporarily all
3840 	 * its DMA activity.
3841 	 */
3842 	resp_buf = phba->MBslimaddr;
3843 
3844 	/* Disable the error attention */
3845 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
3846 		return;
3847 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
3848 	readl(phba->HCregaddr); /* flush */
3849 	phba->link_flag |= LS_IGNORE_ERATT;
3850 
3851 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
3852 		return;
3853 	if (ha_copy & HA_ERATT) {
3854 		/* Clear Chip error bit */
3855 		writel(HA_ERATT, phba->HAregaddr);
3856 		phba->pport->stopped = 1;
3857 	}
3858 
3859 	mbox = 0;
3860 	((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
3861 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
3862 
3863 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
3864 	mbox_buf = phba->MBslimaddr;
3865 	writel(mbox, mbox_buf);
3866 
3867 	for (i = 0; i < 50; i++) {
3868 		if (lpfc_readl((resp_buf + 1), &resp_data))
3869 			return;
3870 		if (resp_data != ~(BARRIER_TEST_PATTERN))
3871 			mdelay(1);
3872 		else
3873 			break;
3874 	}
3875 	resp_data = 0;
3876 	if (lpfc_readl((resp_buf + 1), &resp_data))
3877 		return;
3878 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
3879 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
3880 		    phba->pport->stopped)
3881 			goto restore_hc;
3882 		else
3883 			goto clear_errat;
3884 	}
3885 
3886 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
3887 	resp_data = 0;
3888 	for (i = 0; i < 500; i++) {
3889 		if (lpfc_readl(resp_buf, &resp_data))
3890 			return;
3891 		if (resp_data != mbox)
3892 			mdelay(1);
3893 		else
3894 			break;
3895 	}
3896 
3897 clear_errat:
3898 
3899 	while (++i < 500) {
3900 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
3901 			return;
3902 		if (!(ha_copy & HA_ERATT))
3903 			mdelay(1);
3904 		else
3905 			break;
3906 	}
3907 
3908 	if (readl(phba->HAregaddr) & HA_ERATT) {
3909 		writel(HA_ERATT, phba->HAregaddr);
3910 		phba->pport->stopped = 1;
3911 	}
3912 
3913 restore_hc:
3914 	phba->link_flag &= ~LS_IGNORE_ERATT;
3915 	writel(hc_copy, phba->HCregaddr);
3916 	readl(phba->HCregaddr); /* flush */
3917 }
3918 
3919 /**
3920  * lpfc_sli_brdkill - Issue a kill_board mailbox command
3921  * @phba: Pointer to HBA context object.
3922  *
3923  * This function issues a kill_board mailbox command and waits for
3924  * the error attention interrupt. This function is called for stopping
3925  * the firmware processing. The caller is not required to hold any
3926  * locks. This function calls lpfc_hba_down_post function to free
3927  * any pending commands after the kill. The function will return 1 when it
3928  * fails to kill the board else will return 0.
3929  **/
3930 int
3931 lpfc_sli_brdkill(struct lpfc_hba *phba)
3932 {
3933 	struct lpfc_sli *psli;
3934 	LPFC_MBOXQ_t *pmb;
3935 	uint32_t status;
3936 	uint32_t ha_copy;
3937 	int retval;
3938 	int i = 0;
3939 
3940 	psli = &phba->sli;
3941 
3942 	/* Kill HBA */
3943 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3944 			"0329 Kill HBA Data: x%x x%x\n",
3945 			phba->pport->port_state, psli->sli_flag);
3946 
3947 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
3948 	if (!pmb)
3949 		return 1;
3950 
3951 	/* Disable the error attention */
3952 	spin_lock_irq(&phba->hbalock);
3953 	if (lpfc_readl(phba->HCregaddr, &status)) {
3954 		spin_unlock_irq(&phba->hbalock);
3955 		mempool_free(pmb, phba->mbox_mem_pool);
3956 		return 1;
3957 	}
3958 	status &= ~HC_ERINT_ENA;
3959 	writel(status, phba->HCregaddr);
3960 	readl(phba->HCregaddr); /* flush */
3961 	phba->link_flag |= LS_IGNORE_ERATT;
3962 	spin_unlock_irq(&phba->hbalock);
3963 
3964 	lpfc_kill_board(phba, pmb);
3965 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
3966 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3967 
3968 	if (retval != MBX_SUCCESS) {
3969 		if (retval != MBX_BUSY)
3970 			mempool_free(pmb, phba->mbox_mem_pool);
3971 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3972 				"2752 KILL_BOARD command failed retval %d\n",
3973 				retval);
3974 		spin_lock_irq(&phba->hbalock);
3975 		phba->link_flag &= ~LS_IGNORE_ERATT;
3976 		spin_unlock_irq(&phba->hbalock);
3977 		return 1;
3978 	}
3979 
3980 	spin_lock_irq(&phba->hbalock);
3981 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
3982 	spin_unlock_irq(&phba->hbalock);
3983 
3984 	mempool_free(pmb, phba->mbox_mem_pool);
3985 
3986 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
3987 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
3988 	 * 3 seconds we still set HBA_ERROR state because the status of the
3989 	 * board is now undefined.
3990 	 */
3991 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
3992 		return 1;
3993 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
3994 		mdelay(100);
3995 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
3996 			return 1;
3997 	}
3998 
3999 	del_timer_sync(&psli->mbox_tmo);
4000 	if (ha_copy & HA_ERATT) {
4001 		writel(HA_ERATT, phba->HAregaddr);
4002 		phba->pport->stopped = 1;
4003 	}
4004 	spin_lock_irq(&phba->hbalock);
4005 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4006 	psli->mbox_active = NULL;
4007 	phba->link_flag &= ~LS_IGNORE_ERATT;
4008 	spin_unlock_irq(&phba->hbalock);
4009 
4010 	lpfc_hba_down_post(phba);
4011 	phba->link_state = LPFC_HBA_ERROR;
4012 
4013 	return ha_copy & HA_ERATT ? 0 : 1;
4014 }
4015 
4016 /**
4017  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
4018  * @phba: Pointer to HBA context object.
4019  *
4020  * This function resets the HBA by writing HC_INITFF to the control
4021  * register. After the HBA resets, this function resets all the iocb ring
4022  * indices. This function disables PCI layer parity checking during
4023  * the reset.
4024  * This function returns 0 always.
4025  * The caller is not required to hold any locks.
4026  **/
4027 int
4028 lpfc_sli_brdreset(struct lpfc_hba *phba)
4029 {
4030 	struct lpfc_sli *psli;
4031 	struct lpfc_sli_ring *pring;
4032 	uint16_t cfg_value;
4033 	int i;
4034 
4035 	psli = &phba->sli;
4036 
4037 	/* Reset HBA */
4038 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4039 			"0325 Reset HBA Data: x%x x%x\n",
4040 			phba->pport->port_state, psli->sli_flag);
4041 
4042 	/* perform board reset */
4043 	phba->fc_eventTag = 0;
4044 	phba->link_events = 0;
4045 	phba->pport->fc_myDID = 0;
4046 	phba->pport->fc_prevDID = 0;
4047 
4048 	/* Turn off parity checking and serr during the physical reset */
4049 	pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value);
4050 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
4051 			      (cfg_value &
4052 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4053 
4054 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4055 
4056 	/* Now toggle INITFF bit in the Host Control Register */
4057 	writel(HC_INITFF, phba->HCregaddr);
4058 	mdelay(1);
4059 	readl(phba->HCregaddr); /* flush */
4060 	writel(0, phba->HCregaddr);
4061 	readl(phba->HCregaddr); /* flush */
4062 
4063 	/* Restore PCI cmd register */
4064 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4065 
4066 	/* Initialize relevant SLI info */
4067 	for (i = 0; i < psli->num_rings; i++) {
4068 		pring = &psli->ring[i];
4069 		pring->flag = 0;
4070 		pring->sli.sli3.rspidx = 0;
4071 		pring->sli.sli3.next_cmdidx  = 0;
4072 		pring->sli.sli3.local_getidx = 0;
4073 		pring->sli.sli3.cmdidx = 0;
4074 		pring->missbufcnt = 0;
4075 	}
4076 
4077 	phba->link_state = LPFC_WARM_START;
4078 	return 0;
4079 }
4080 
4081 /**
4082  * lpfc_sli4_brdreset - Reset a sli-4 HBA
4083  * @phba: Pointer to HBA context object.
4084  *
4085  * This function resets a SLI4 HBA. This function disables PCI layer parity
4086  * checking during resets the device. The caller is not required to hold
4087  * any locks.
4088  *
4089  * This function returns 0 always.
4090  **/
4091 int
4092 lpfc_sli4_brdreset(struct lpfc_hba *phba)
4093 {
4094 	struct lpfc_sli *psli = &phba->sli;
4095 	uint16_t cfg_value;
4096 	int rc = 0;
4097 
4098 	/* Reset HBA */
4099 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4100 			"0295 Reset HBA Data: x%x x%x x%x\n",
4101 			phba->pport->port_state, psli->sli_flag,
4102 			phba->hba_flag);
4103 
4104 	/* perform board reset */
4105 	phba->fc_eventTag = 0;
4106 	phba->link_events = 0;
4107 	phba->pport->fc_myDID = 0;
4108 	phba->pport->fc_prevDID = 0;
4109 
4110 	spin_lock_irq(&phba->hbalock);
4111 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
4112 	phba->fcf.fcf_flag = 0;
4113 	spin_unlock_irq(&phba->hbalock);
4114 
4115 	/* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
4116 	if (phba->hba_flag & HBA_FW_DUMP_OP) {
4117 		phba->hba_flag &= ~HBA_FW_DUMP_OP;
4118 		return rc;
4119 	}
4120 
4121 	/* Now physically reset the device */
4122 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4123 			"0389 Performing PCI function reset!\n");
4124 
4125 	/* Turn off parity checking and serr during the physical reset */
4126 	pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value);
4127 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
4128 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4129 
4130 	/* Perform FCoE PCI function reset before freeing queue memory */
4131 	rc = lpfc_pci_function_reset(phba);
4132 	lpfc_sli4_queue_destroy(phba);
4133 
4134 	/* Restore PCI cmd register */
4135 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4136 
4137 	return rc;
4138 }
4139 
4140 /**
4141  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
4142  * @phba: Pointer to HBA context object.
4143  *
4144  * This function is called in the SLI initialization code path to
4145  * restart the HBA. The caller is not required to hold any lock.
4146  * This function writes MBX_RESTART mailbox command to the SLIM and
4147  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
4148  * function to free any pending commands. The function enables
4149  * POST only during the first initialization. The function returns zero.
4150  * The function does not guarantee completion of MBX_RESTART mailbox
4151  * command before the return of this function.
4152  **/
4153 static int
4154 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
4155 {
4156 	MAILBOX_t *mb;
4157 	struct lpfc_sli *psli;
4158 	volatile uint32_t word0;
4159 	void __iomem *to_slim;
4160 	uint32_t hba_aer_enabled;
4161 
4162 	spin_lock_irq(&phba->hbalock);
4163 
4164 	/* Take PCIe device Advanced Error Reporting (AER) state */
4165 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4166 
4167 	psli = &phba->sli;
4168 
4169 	/* Restart HBA */
4170 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4171 			"0337 Restart HBA Data: x%x x%x\n",
4172 			phba->pport->port_state, psli->sli_flag);
4173 
4174 	word0 = 0;
4175 	mb = (MAILBOX_t *) &word0;
4176 	mb->mbxCommand = MBX_RESTART;
4177 	mb->mbxHc = 1;
4178 
4179 	lpfc_reset_barrier(phba);
4180 
4181 	to_slim = phba->MBslimaddr;
4182 	writel(*(uint32_t *) mb, to_slim);
4183 	readl(to_slim); /* flush */
4184 
4185 	/* Only skip post after fc_ffinit is completed */
4186 	if (phba->pport->port_state)
4187 		word0 = 1;	/* This is really setting up word1 */
4188 	else
4189 		word0 = 0;	/* This is really setting up word1 */
4190 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
4191 	writel(*(uint32_t *) mb, to_slim);
4192 	readl(to_slim); /* flush */
4193 
4194 	lpfc_sli_brdreset(phba);
4195 	phba->pport->stopped = 0;
4196 	phba->link_state = LPFC_INIT_START;
4197 	phba->hba_flag = 0;
4198 	spin_unlock_irq(&phba->hbalock);
4199 
4200 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4201 	psli->stats_start = get_seconds();
4202 
4203 	/* Give the INITFF and Post time to settle. */
4204 	mdelay(100);
4205 
4206 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4207 	if (hba_aer_enabled)
4208 		pci_disable_pcie_error_reporting(phba->pcidev);
4209 
4210 	lpfc_hba_down_post(phba);
4211 
4212 	return 0;
4213 }
4214 
4215 /**
4216  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
4217  * @phba: Pointer to HBA context object.
4218  *
4219  * This function is called in the SLI initialization code path to restart
4220  * a SLI4 HBA. The caller is not required to hold any lock.
4221  * At the end of the function, it calls lpfc_hba_down_post function to
4222  * free any pending commands.
4223  **/
4224 static int
4225 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
4226 {
4227 	struct lpfc_sli *psli = &phba->sli;
4228 	uint32_t hba_aer_enabled;
4229 	int rc;
4230 
4231 	/* Restart HBA */
4232 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4233 			"0296 Restart HBA Data: x%x x%x\n",
4234 			phba->pport->port_state, psli->sli_flag);
4235 
4236 	/* Take PCIe device Advanced Error Reporting (AER) state */
4237 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4238 
4239 	rc = lpfc_sli4_brdreset(phba);
4240 
4241 	spin_lock_irq(&phba->hbalock);
4242 	phba->pport->stopped = 0;
4243 	phba->link_state = LPFC_INIT_START;
4244 	phba->hba_flag = 0;
4245 	spin_unlock_irq(&phba->hbalock);
4246 
4247 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4248 	psli->stats_start = get_seconds();
4249 
4250 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4251 	if (hba_aer_enabled)
4252 		pci_disable_pcie_error_reporting(phba->pcidev);
4253 
4254 	lpfc_hba_down_post(phba);
4255 
4256 	return rc;
4257 }
4258 
4259 /**
4260  * lpfc_sli_brdrestart - Wrapper func for restarting hba
4261  * @phba: Pointer to HBA context object.
4262  *
4263  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
4264  * API jump table function pointer from the lpfc_hba struct.
4265 **/
4266 int
4267 lpfc_sli_brdrestart(struct lpfc_hba *phba)
4268 {
4269 	return phba->lpfc_sli_brdrestart(phba);
4270 }
4271 
4272 /**
4273  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
4274  * @phba: Pointer to HBA context object.
4275  *
4276  * This function is called after a HBA restart to wait for successful
4277  * restart of the HBA. Successful restart of the HBA is indicated by
4278  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
4279  * iteration, the function will restart the HBA again. The function returns
4280  * zero if HBA successfully restarted else returns negative error code.
4281  **/
4282 static int
4283 lpfc_sli_chipset_init(struct lpfc_hba *phba)
4284 {
4285 	uint32_t status, i = 0;
4286 
4287 	/* Read the HBA Host Status Register */
4288 	if (lpfc_readl(phba->HSregaddr, &status))
4289 		return -EIO;
4290 
4291 	/* Check status register to see what current state is */
4292 	i = 0;
4293 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
4294 
4295 		/* Check every 10ms for 10 retries, then every 100ms for 90
4296 		 * retries, then every 1 sec for 50 retires for a total of
4297 		 * ~60 seconds before reset the board again and check every
4298 		 * 1 sec for 50 retries. The up to 60 seconds before the
4299 		 * board ready is required by the Falcon FIPS zeroization
4300 		 * complete, and any reset the board in between shall cause
4301 		 * restart of zeroization, further delay the board ready.
4302 		 */
4303 		if (i++ >= 200) {
4304 			/* Adapter failed to init, timeout, status reg
4305 			   <status> */
4306 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4307 					"0436 Adapter failed to init, "
4308 					"timeout, status reg x%x, "
4309 					"FW Data: A8 x%x AC x%x\n", status,
4310 					readl(phba->MBslimaddr + 0xa8),
4311 					readl(phba->MBslimaddr + 0xac));
4312 			phba->link_state = LPFC_HBA_ERROR;
4313 			return -ETIMEDOUT;
4314 		}
4315 
4316 		/* Check to see if any errors occurred during init */
4317 		if (status & HS_FFERM) {
4318 			/* ERROR: During chipset initialization */
4319 			/* Adapter failed to init, chipset, status reg
4320 			   <status> */
4321 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4322 					"0437 Adapter failed to init, "
4323 					"chipset, status reg x%x, "
4324 					"FW Data: A8 x%x AC x%x\n", status,
4325 					readl(phba->MBslimaddr + 0xa8),
4326 					readl(phba->MBslimaddr + 0xac));
4327 			phba->link_state = LPFC_HBA_ERROR;
4328 			return -EIO;
4329 		}
4330 
4331 		if (i <= 10)
4332 			msleep(10);
4333 		else if (i <= 100)
4334 			msleep(100);
4335 		else
4336 			msleep(1000);
4337 
4338 		if (i == 150) {
4339 			/* Do post */
4340 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4341 			lpfc_sli_brdrestart(phba);
4342 		}
4343 		/* Read the HBA Host Status Register */
4344 		if (lpfc_readl(phba->HSregaddr, &status))
4345 			return -EIO;
4346 	}
4347 
4348 	/* Check to see if any errors occurred during init */
4349 	if (status & HS_FFERM) {
4350 		/* ERROR: During chipset initialization */
4351 		/* Adapter failed to init, chipset, status reg <status> */
4352 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4353 				"0438 Adapter failed to init, chipset, "
4354 				"status reg x%x, "
4355 				"FW Data: A8 x%x AC x%x\n", status,
4356 				readl(phba->MBslimaddr + 0xa8),
4357 				readl(phba->MBslimaddr + 0xac));
4358 		phba->link_state = LPFC_HBA_ERROR;
4359 		return -EIO;
4360 	}
4361 
4362 	/* Clear all interrupt enable conditions */
4363 	writel(0, phba->HCregaddr);
4364 	readl(phba->HCregaddr); /* flush */
4365 
4366 	/* setup host attn register */
4367 	writel(0xffffffff, phba->HAregaddr);
4368 	readl(phba->HAregaddr); /* flush */
4369 	return 0;
4370 }
4371 
4372 /**
4373  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
4374  *
4375  * This function calculates and returns the number of HBQs required to be
4376  * configured.
4377  **/
4378 int
4379 lpfc_sli_hbq_count(void)
4380 {
4381 	return ARRAY_SIZE(lpfc_hbq_defs);
4382 }
4383 
4384 /**
4385  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
4386  *
4387  * This function adds the number of hbq entries in every HBQ to get
4388  * the total number of hbq entries required for the HBA and returns
4389  * the total count.
4390  **/
4391 static int
4392 lpfc_sli_hbq_entry_count(void)
4393 {
4394 	int  hbq_count = lpfc_sli_hbq_count();
4395 	int  count = 0;
4396 	int  i;
4397 
4398 	for (i = 0; i < hbq_count; ++i)
4399 		count += lpfc_hbq_defs[i]->entry_count;
4400 	return count;
4401 }
4402 
4403 /**
4404  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
4405  *
4406  * This function calculates amount of memory required for all hbq entries
4407  * to be configured and returns the total memory required.
4408  **/
4409 int
4410 lpfc_sli_hbq_size(void)
4411 {
4412 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
4413 }
4414 
4415 /**
4416  * lpfc_sli_hbq_setup - configure and initialize HBQs
4417  * @phba: Pointer to HBA context object.
4418  *
4419  * This function is called during the SLI initialization to configure
4420  * all the HBQs and post buffers to the HBQ. The caller is not
4421  * required to hold any locks. This function will return zero if successful
4422  * else it will return negative error code.
4423  **/
4424 static int
4425 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
4426 {
4427 	int  hbq_count = lpfc_sli_hbq_count();
4428 	LPFC_MBOXQ_t *pmb;
4429 	MAILBOX_t *pmbox;
4430 	uint32_t hbqno;
4431 	uint32_t hbq_entry_index;
4432 
4433 				/* Get a Mailbox buffer to setup mailbox
4434 				 * commands for HBA initialization
4435 				 */
4436 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4437 
4438 	if (!pmb)
4439 		return -ENOMEM;
4440 
4441 	pmbox = &pmb->u.mb;
4442 
4443 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
4444 	phba->link_state = LPFC_INIT_MBX_CMDS;
4445 	phba->hbq_in_use = 1;
4446 
4447 	hbq_entry_index = 0;
4448 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
4449 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
4450 		phba->hbqs[hbqno].hbqPutIdx      = 0;
4451 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
4452 		phba->hbqs[hbqno].entry_count =
4453 			lpfc_hbq_defs[hbqno]->entry_count;
4454 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
4455 			hbq_entry_index, pmb);
4456 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
4457 
4458 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
4459 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
4460 			   mbxStatus <status>, ring <num> */
4461 
4462 			lpfc_printf_log(phba, KERN_ERR,
4463 					LOG_SLI | LOG_VPORT,
4464 					"1805 Adapter failed to init. "
4465 					"Data: x%x x%x x%x\n",
4466 					pmbox->mbxCommand,
4467 					pmbox->mbxStatus, hbqno);
4468 
4469 			phba->link_state = LPFC_HBA_ERROR;
4470 			mempool_free(pmb, phba->mbox_mem_pool);
4471 			return -ENXIO;
4472 		}
4473 	}
4474 	phba->hbq_count = hbq_count;
4475 
4476 	mempool_free(pmb, phba->mbox_mem_pool);
4477 
4478 	/* Initially populate or replenish the HBQs */
4479 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
4480 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
4481 	return 0;
4482 }
4483 
4484 /**
4485  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
4486  * @phba: Pointer to HBA context object.
4487  *
4488  * This function is called during the SLI initialization to configure
4489  * all the HBQs and post buffers to the HBQ. The caller is not
4490  * required to hold any locks. This function will return zero if successful
4491  * else it will return negative error code.
4492  **/
4493 static int
4494 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
4495 {
4496 	phba->hbq_in_use = 1;
4497 	phba->hbqs[0].entry_count = lpfc_hbq_defs[0]->entry_count;
4498 	phba->hbq_count = 1;
4499 	/* Initially populate or replenish the HBQs */
4500 	lpfc_sli_hbqbuf_init_hbqs(phba, 0);
4501 	return 0;
4502 }
4503 
4504 /**
4505  * lpfc_sli_config_port - Issue config port mailbox command
4506  * @phba: Pointer to HBA context object.
4507  * @sli_mode: sli mode - 2/3
4508  *
4509  * This function is called by the sli intialization code path
4510  * to issue config_port mailbox command. This function restarts the
4511  * HBA firmware and issues a config_port mailbox command to configure
4512  * the SLI interface in the sli mode specified by sli_mode
4513  * variable. The caller is not required to hold any locks.
4514  * The function returns 0 if successful, else returns negative error
4515  * code.
4516  **/
4517 int
4518 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
4519 {
4520 	LPFC_MBOXQ_t *pmb;
4521 	uint32_t resetcount = 0, rc = 0, done = 0;
4522 
4523 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4524 	if (!pmb) {
4525 		phba->link_state = LPFC_HBA_ERROR;
4526 		return -ENOMEM;
4527 	}
4528 
4529 	phba->sli_rev = sli_mode;
4530 	while (resetcount < 2 && !done) {
4531 		spin_lock_irq(&phba->hbalock);
4532 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
4533 		spin_unlock_irq(&phba->hbalock);
4534 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4535 		lpfc_sli_brdrestart(phba);
4536 		rc = lpfc_sli_chipset_init(phba);
4537 		if (rc)
4538 			break;
4539 
4540 		spin_lock_irq(&phba->hbalock);
4541 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4542 		spin_unlock_irq(&phba->hbalock);
4543 		resetcount++;
4544 
4545 		/* Call pre CONFIG_PORT mailbox command initialization.  A
4546 		 * value of 0 means the call was successful.  Any other
4547 		 * nonzero value is a failure, but if ERESTART is returned,
4548 		 * the driver may reset the HBA and try again.
4549 		 */
4550 		rc = lpfc_config_port_prep(phba);
4551 		if (rc == -ERESTART) {
4552 			phba->link_state = LPFC_LINK_UNKNOWN;
4553 			continue;
4554 		} else if (rc)
4555 			break;
4556 
4557 		phba->link_state = LPFC_INIT_MBX_CMDS;
4558 		lpfc_config_port(phba, pmb);
4559 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
4560 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
4561 					LPFC_SLI3_HBQ_ENABLED |
4562 					LPFC_SLI3_CRP_ENABLED |
4563 					LPFC_SLI3_BG_ENABLED |
4564 					LPFC_SLI3_DSS_ENABLED);
4565 		if (rc != MBX_SUCCESS) {
4566 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4567 				"0442 Adapter failed to init, mbxCmd x%x "
4568 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
4569 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
4570 			spin_lock_irq(&phba->hbalock);
4571 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
4572 			spin_unlock_irq(&phba->hbalock);
4573 			rc = -ENXIO;
4574 		} else {
4575 			/* Allow asynchronous mailbox command to go through */
4576 			spin_lock_irq(&phba->hbalock);
4577 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
4578 			spin_unlock_irq(&phba->hbalock);
4579 			done = 1;
4580 
4581 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
4582 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
4583 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
4584 					"3110 Port did not grant ASABT\n");
4585 		}
4586 	}
4587 	if (!done) {
4588 		rc = -EINVAL;
4589 		goto do_prep_failed;
4590 	}
4591 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
4592 		if (!pmb->u.mb.un.varCfgPort.cMA) {
4593 			rc = -ENXIO;
4594 			goto do_prep_failed;
4595 		}
4596 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
4597 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
4598 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
4599 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
4600 				phba->max_vpi : phba->max_vports;
4601 
4602 		} else
4603 			phba->max_vpi = 0;
4604 		phba->fips_level = 0;
4605 		phba->fips_spec_rev = 0;
4606 		if (pmb->u.mb.un.varCfgPort.gdss) {
4607 			phba->sli3_options |= LPFC_SLI3_DSS_ENABLED;
4608 			phba->fips_level = pmb->u.mb.un.varCfgPort.fips_level;
4609 			phba->fips_spec_rev = pmb->u.mb.un.varCfgPort.fips_rev;
4610 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4611 					"2850 Security Crypto Active. FIPS x%d "
4612 					"(Spec Rev: x%d)",
4613 					phba->fips_level, phba->fips_spec_rev);
4614 		}
4615 		if (pmb->u.mb.un.varCfgPort.sec_err) {
4616 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4617 					"2856 Config Port Security Crypto "
4618 					"Error: x%x ",
4619 					pmb->u.mb.un.varCfgPort.sec_err);
4620 		}
4621 		if (pmb->u.mb.un.varCfgPort.gerbm)
4622 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
4623 		if (pmb->u.mb.un.varCfgPort.gcrp)
4624 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
4625 
4626 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
4627 		phba->port_gp = phba->mbox->us.s3_pgp.port;
4628 
4629 		if (phba->cfg_enable_bg) {
4630 			if (pmb->u.mb.un.varCfgPort.gbg)
4631 				phba->sli3_options |= LPFC_SLI3_BG_ENABLED;
4632 			else
4633 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4634 						"0443 Adapter did not grant "
4635 						"BlockGuard\n");
4636 		}
4637 	} else {
4638 		phba->hbq_get = NULL;
4639 		phba->port_gp = phba->mbox->us.s2.port;
4640 		phba->max_vpi = 0;
4641 	}
4642 do_prep_failed:
4643 	mempool_free(pmb, phba->mbox_mem_pool);
4644 	return rc;
4645 }
4646 
4647 
4648 /**
4649  * lpfc_sli_hba_setup - SLI intialization function
4650  * @phba: Pointer to HBA context object.
4651  *
4652  * This function is the main SLI intialization function. This function
4653  * is called by the HBA intialization code, HBA reset code and HBA
4654  * error attention handler code. Caller is not required to hold any
4655  * locks. This function issues config_port mailbox command to configure
4656  * the SLI, setup iocb rings and HBQ rings. In the end the function
4657  * calls the config_port_post function to issue init_link mailbox
4658  * command and to start the discovery. The function will return zero
4659  * if successful, else it will return negative error code.
4660  **/
4661 int
4662 lpfc_sli_hba_setup(struct lpfc_hba *phba)
4663 {
4664 	uint32_t rc;
4665 	int  mode = 3, i;
4666 	int longs;
4667 
4668 	switch (lpfc_sli_mode) {
4669 	case 2:
4670 		if (phba->cfg_enable_npiv) {
4671 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4672 				"1824 NPIV enabled: Override lpfc_sli_mode "
4673 				"parameter (%d) to auto (0).\n",
4674 				lpfc_sli_mode);
4675 			break;
4676 		}
4677 		mode = 2;
4678 		break;
4679 	case 0:
4680 	case 3:
4681 		break;
4682 	default:
4683 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4684 				"1819 Unrecognized lpfc_sli_mode "
4685 				"parameter: %d.\n", lpfc_sli_mode);
4686 
4687 		break;
4688 	}
4689 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
4690 
4691 	rc = lpfc_sli_config_port(phba, mode);
4692 
4693 	if (rc && lpfc_sli_mode == 3)
4694 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4695 				"1820 Unable to select SLI-3.  "
4696 				"Not supported by adapter.\n");
4697 	if (rc && mode != 2)
4698 		rc = lpfc_sli_config_port(phba, 2);
4699 	if (rc)
4700 		goto lpfc_sli_hba_setup_error;
4701 
4702 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
4703 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
4704 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
4705 		if (!rc) {
4706 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4707 					"2709 This device supports "
4708 					"Advanced Error Reporting (AER)\n");
4709 			spin_lock_irq(&phba->hbalock);
4710 			phba->hba_flag |= HBA_AER_ENABLED;
4711 			spin_unlock_irq(&phba->hbalock);
4712 		} else {
4713 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4714 					"2708 This device does not support "
4715 					"Advanced Error Reporting (AER): %d\n",
4716 					rc);
4717 			phba->cfg_aer_support = 0;
4718 		}
4719 	}
4720 
4721 	if (phba->sli_rev == 3) {
4722 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
4723 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
4724 	} else {
4725 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
4726 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
4727 		phba->sli3_options = 0;
4728 	}
4729 
4730 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4731 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
4732 			phba->sli_rev, phba->max_vpi);
4733 	rc = lpfc_sli_ring_map(phba);
4734 
4735 	if (rc)
4736 		goto lpfc_sli_hba_setup_error;
4737 
4738 	/* Initialize VPIs. */
4739 	if (phba->sli_rev == LPFC_SLI_REV3) {
4740 		/*
4741 		 * The VPI bitmask and physical ID array are allocated
4742 		 * and initialized once only - at driver load.  A port
4743 		 * reset doesn't need to reinitialize this memory.
4744 		 */
4745 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
4746 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
4747 			phba->vpi_bmask = kzalloc(longs * sizeof(unsigned long),
4748 						  GFP_KERNEL);
4749 			if (!phba->vpi_bmask) {
4750 				rc = -ENOMEM;
4751 				goto lpfc_sli_hba_setup_error;
4752 			}
4753 
4754 			phba->vpi_ids = kzalloc(
4755 					(phba->max_vpi+1) * sizeof(uint16_t),
4756 					GFP_KERNEL);
4757 			if (!phba->vpi_ids) {
4758 				kfree(phba->vpi_bmask);
4759 				rc = -ENOMEM;
4760 				goto lpfc_sli_hba_setup_error;
4761 			}
4762 			for (i = 0; i < phba->max_vpi; i++)
4763 				phba->vpi_ids[i] = i;
4764 		}
4765 	}
4766 
4767 	/* Init HBQs */
4768 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
4769 		rc = lpfc_sli_hbq_setup(phba);
4770 		if (rc)
4771 			goto lpfc_sli_hba_setup_error;
4772 	}
4773 	spin_lock_irq(&phba->hbalock);
4774 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
4775 	spin_unlock_irq(&phba->hbalock);
4776 
4777 	rc = lpfc_config_port_post(phba);
4778 	if (rc)
4779 		goto lpfc_sli_hba_setup_error;
4780 
4781 	return rc;
4782 
4783 lpfc_sli_hba_setup_error:
4784 	phba->link_state = LPFC_HBA_ERROR;
4785 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4786 			"0445 Firmware initialization failed\n");
4787 	return rc;
4788 }
4789 
4790 /**
4791  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
4792  * @phba: Pointer to HBA context object.
4793  * @mboxq: mailbox pointer.
4794  * This function issue a dump mailbox command to read config region
4795  * 23 and parse the records in the region and populate driver
4796  * data structure.
4797  **/
4798 static int
4799 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
4800 {
4801 	LPFC_MBOXQ_t *mboxq;
4802 	struct lpfc_dmabuf *mp;
4803 	struct lpfc_mqe *mqe;
4804 	uint32_t data_length;
4805 	int rc;
4806 
4807 	/* Program the default value of vlan_id and fc_map */
4808 	phba->valid_vlan = 0;
4809 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
4810 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
4811 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
4812 
4813 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4814 	if (!mboxq)
4815 		return -ENOMEM;
4816 
4817 	mqe = &mboxq->u.mqe;
4818 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
4819 		rc = -ENOMEM;
4820 		goto out_free_mboxq;
4821 	}
4822 
4823 	mp = (struct lpfc_dmabuf *) mboxq->context1;
4824 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4825 
4826 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
4827 			"(%d):2571 Mailbox cmd x%x Status x%x "
4828 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
4829 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
4830 			"CQ: x%x x%x x%x x%x\n",
4831 			mboxq->vport ? mboxq->vport->vpi : 0,
4832 			bf_get(lpfc_mqe_command, mqe),
4833 			bf_get(lpfc_mqe_status, mqe),
4834 			mqe->un.mb_words[0], mqe->un.mb_words[1],
4835 			mqe->un.mb_words[2], mqe->un.mb_words[3],
4836 			mqe->un.mb_words[4], mqe->un.mb_words[5],
4837 			mqe->un.mb_words[6], mqe->un.mb_words[7],
4838 			mqe->un.mb_words[8], mqe->un.mb_words[9],
4839 			mqe->un.mb_words[10], mqe->un.mb_words[11],
4840 			mqe->un.mb_words[12], mqe->un.mb_words[13],
4841 			mqe->un.mb_words[14], mqe->un.mb_words[15],
4842 			mqe->un.mb_words[16], mqe->un.mb_words[50],
4843 			mboxq->mcqe.word0,
4844 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
4845 			mboxq->mcqe.trailer);
4846 
4847 	if (rc) {
4848 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
4849 		kfree(mp);
4850 		rc = -EIO;
4851 		goto out_free_mboxq;
4852 	}
4853 	data_length = mqe->un.mb_words[5];
4854 	if (data_length > DMP_RGN23_SIZE) {
4855 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
4856 		kfree(mp);
4857 		rc = -EIO;
4858 		goto out_free_mboxq;
4859 	}
4860 
4861 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
4862 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
4863 	kfree(mp);
4864 	rc = 0;
4865 
4866 out_free_mboxq:
4867 	mempool_free(mboxq, phba->mbox_mem_pool);
4868 	return rc;
4869 }
4870 
4871 /**
4872  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
4873  * @phba: pointer to lpfc hba data structure.
4874  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
4875  * @vpd: pointer to the memory to hold resulting port vpd data.
4876  * @vpd_size: On input, the number of bytes allocated to @vpd.
4877  *	      On output, the number of data bytes in @vpd.
4878  *
4879  * This routine executes a READ_REV SLI4 mailbox command.  In
4880  * addition, this routine gets the port vpd data.
4881  *
4882  * Return codes
4883  * 	0 - successful
4884  * 	-ENOMEM - could not allocated memory.
4885  **/
4886 static int
4887 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
4888 		    uint8_t *vpd, uint32_t *vpd_size)
4889 {
4890 	int rc = 0;
4891 	uint32_t dma_size;
4892 	struct lpfc_dmabuf *dmabuf;
4893 	struct lpfc_mqe *mqe;
4894 
4895 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
4896 	if (!dmabuf)
4897 		return -ENOMEM;
4898 
4899 	/*
4900 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
4901 	 * mailbox command.
4902 	 */
4903 	dma_size = *vpd_size;
4904 	dmabuf->virt = dma_zalloc_coherent(&phba->pcidev->dev, dma_size,
4905 					   &dmabuf->phys, GFP_KERNEL);
4906 	if (!dmabuf->virt) {
4907 		kfree(dmabuf);
4908 		return -ENOMEM;
4909 	}
4910 
4911 	/*
4912 	 * The SLI4 implementation of READ_REV conflicts at word1,
4913 	 * bits 31:16 and SLI4 adds vpd functionality not present
4914 	 * in SLI3.  This code corrects the conflicts.
4915 	 */
4916 	lpfc_read_rev(phba, mboxq);
4917 	mqe = &mboxq->u.mqe;
4918 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
4919 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
4920 	mqe->un.read_rev.word1 &= 0x0000FFFF;
4921 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
4922 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
4923 
4924 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4925 	if (rc) {
4926 		dma_free_coherent(&phba->pcidev->dev, dma_size,
4927 				  dmabuf->virt, dmabuf->phys);
4928 		kfree(dmabuf);
4929 		return -EIO;
4930 	}
4931 
4932 	/*
4933 	 * The available vpd length cannot be bigger than the
4934 	 * DMA buffer passed to the port.  Catch the less than
4935 	 * case and update the caller's size.
4936 	 */
4937 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
4938 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
4939 
4940 	memcpy(vpd, dmabuf->virt, *vpd_size);
4941 
4942 	dma_free_coherent(&phba->pcidev->dev, dma_size,
4943 			  dmabuf->virt, dmabuf->phys);
4944 	kfree(dmabuf);
4945 	return 0;
4946 }
4947 
4948 /**
4949  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
4950  * @phba: pointer to lpfc hba data structure.
4951  *
4952  * This routine retrieves SLI4 device physical port name this PCI function
4953  * is attached to.
4954  *
4955  * Return codes
4956  *      0 - successful
4957  *      otherwise - failed to retrieve physical port name
4958  **/
4959 static int
4960 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
4961 {
4962 	LPFC_MBOXQ_t *mboxq;
4963 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
4964 	struct lpfc_controller_attribute *cntl_attr;
4965 	struct lpfc_mbx_get_port_name *get_port_name;
4966 	void *virtaddr = NULL;
4967 	uint32_t alloclen, reqlen;
4968 	uint32_t shdr_status, shdr_add_status;
4969 	union lpfc_sli4_cfg_shdr *shdr;
4970 	char cport_name = 0;
4971 	int rc;
4972 
4973 	/* We assume nothing at this point */
4974 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
4975 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
4976 
4977 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4978 	if (!mboxq)
4979 		return -ENOMEM;
4980 	/* obtain link type and link number via READ_CONFIG */
4981 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
4982 	lpfc_sli4_read_config(phba);
4983 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
4984 		goto retrieve_ppname;
4985 
4986 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
4987 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
4988 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
4989 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
4990 			LPFC_SLI4_MBX_NEMBED);
4991 	if (alloclen < reqlen) {
4992 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4993 				"3084 Allocated DMA memory size (%d) is "
4994 				"less than the requested DMA memory size "
4995 				"(%d)\n", alloclen, reqlen);
4996 		rc = -ENOMEM;
4997 		goto out_free_mboxq;
4998 	}
4999 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5000 	virtaddr = mboxq->sge_array->addr[0];
5001 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5002 	shdr = &mbx_cntl_attr->cfg_shdr;
5003 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5004 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5005 	if (shdr_status || shdr_add_status || rc) {
5006 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5007 				"3085 Mailbox x%x (x%x/x%x) failed, "
5008 				"rc:x%x, status:x%x, add_status:x%x\n",
5009 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5010 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5011 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5012 				rc, shdr_status, shdr_add_status);
5013 		rc = -ENXIO;
5014 		goto out_free_mboxq;
5015 	}
5016 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5017 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5018 	phba->sli4_hba.lnk_info.lnk_tp =
5019 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5020 	phba->sli4_hba.lnk_info.lnk_no =
5021 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5022 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5023 			"3086 lnk_type:%d, lnk_numb:%d\n",
5024 			phba->sli4_hba.lnk_info.lnk_tp,
5025 			phba->sli4_hba.lnk_info.lnk_no);
5026 
5027 retrieve_ppname:
5028 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5029 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
5030 		sizeof(struct lpfc_mbx_get_port_name) -
5031 		sizeof(struct lpfc_sli4_cfg_mhdr),
5032 		LPFC_SLI4_MBX_EMBED);
5033 	get_port_name = &mboxq->u.mqe.un.get_port_name;
5034 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5035 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
5036 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
5037 		phba->sli4_hba.lnk_info.lnk_tp);
5038 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5039 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5040 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5041 	if (shdr_status || shdr_add_status || rc) {
5042 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5043 				"3087 Mailbox x%x (x%x/x%x) failed: "
5044 				"rc:x%x, status:x%x, add_status:x%x\n",
5045 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5046 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5047 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5048 				rc, shdr_status, shdr_add_status);
5049 		rc = -ENXIO;
5050 		goto out_free_mboxq;
5051 	}
5052 	switch (phba->sli4_hba.lnk_info.lnk_no) {
5053 	case LPFC_LINK_NUMBER_0:
5054 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
5055 				&get_port_name->u.response);
5056 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5057 		break;
5058 	case LPFC_LINK_NUMBER_1:
5059 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
5060 				&get_port_name->u.response);
5061 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5062 		break;
5063 	case LPFC_LINK_NUMBER_2:
5064 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
5065 				&get_port_name->u.response);
5066 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5067 		break;
5068 	case LPFC_LINK_NUMBER_3:
5069 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
5070 				&get_port_name->u.response);
5071 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5072 		break;
5073 	default:
5074 		break;
5075 	}
5076 
5077 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
5078 		phba->Port[0] = cport_name;
5079 		phba->Port[1] = '\0';
5080 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5081 				"3091 SLI get port name: %s\n", phba->Port);
5082 	}
5083 
5084 out_free_mboxq:
5085 	if (rc != MBX_TIMEOUT) {
5086 		if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5087 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
5088 		else
5089 			mempool_free(mboxq, phba->mbox_mem_pool);
5090 	}
5091 	return rc;
5092 }
5093 
5094 /**
5095  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
5096  * @phba: pointer to lpfc hba data structure.
5097  *
5098  * This routine is called to explicitly arm the SLI4 device's completion and
5099  * event queues
5100  **/
5101 static void
5102 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
5103 {
5104 	int fcp_eqidx;
5105 
5106 	lpfc_sli4_cq_release(phba->sli4_hba.mbx_cq, LPFC_QUEUE_REARM);
5107 	lpfc_sli4_cq_release(phba->sli4_hba.els_cq, LPFC_QUEUE_REARM);
5108 	fcp_eqidx = 0;
5109 	if (phba->sli4_hba.fcp_cq) {
5110 		do {
5111 			lpfc_sli4_cq_release(phba->sli4_hba.fcp_cq[fcp_eqidx],
5112 					     LPFC_QUEUE_REARM);
5113 		} while (++fcp_eqidx < phba->cfg_fcp_io_channel);
5114 	}
5115 
5116 	if (phba->cfg_fof)
5117 		lpfc_sli4_cq_release(phba->sli4_hba.oas_cq, LPFC_QUEUE_REARM);
5118 
5119 	if (phba->sli4_hba.hba_eq) {
5120 		for (fcp_eqidx = 0; fcp_eqidx < phba->cfg_fcp_io_channel;
5121 		     fcp_eqidx++)
5122 			lpfc_sli4_eq_release(phba->sli4_hba.hba_eq[fcp_eqidx],
5123 					     LPFC_QUEUE_REARM);
5124 	}
5125 
5126 	if (phba->cfg_fof)
5127 		lpfc_sli4_eq_release(phba->sli4_hba.fof_eq, LPFC_QUEUE_REARM);
5128 }
5129 
5130 /**
5131  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
5132  * @phba: Pointer to HBA context object.
5133  * @type: The resource extent type.
5134  * @extnt_count: buffer to hold port available extent count.
5135  * @extnt_size: buffer to hold element count per extent.
5136  *
5137  * This function calls the port and retrievs the number of available
5138  * extents and their size for a particular extent type.
5139  *
5140  * Returns: 0 if successful.  Nonzero otherwise.
5141  **/
5142 int
5143 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
5144 			       uint16_t *extnt_count, uint16_t *extnt_size)
5145 {
5146 	int rc = 0;
5147 	uint32_t length;
5148 	uint32_t mbox_tmo;
5149 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
5150 	LPFC_MBOXQ_t *mbox;
5151 
5152 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5153 	if (!mbox)
5154 		return -ENOMEM;
5155 
5156 	/* Find out how many extents are available for this resource type */
5157 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
5158 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5159 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5160 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
5161 			 length, LPFC_SLI4_MBX_EMBED);
5162 
5163 	/* Send an extents count of 0 - the GET doesn't use it. */
5164 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5165 					LPFC_SLI4_MBX_EMBED);
5166 	if (unlikely(rc)) {
5167 		rc = -EIO;
5168 		goto err_exit;
5169 	}
5170 
5171 	if (!phba->sli4_hba.intr_enable)
5172 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5173 	else {
5174 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5175 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5176 	}
5177 	if (unlikely(rc)) {
5178 		rc = -EIO;
5179 		goto err_exit;
5180 	}
5181 
5182 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
5183 	if (bf_get(lpfc_mbox_hdr_status,
5184 		   &rsrc_info->header.cfg_shdr.response)) {
5185 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5186 				"2930 Failed to get resource extents "
5187 				"Status 0x%x Add'l Status 0x%x\n",
5188 				bf_get(lpfc_mbox_hdr_status,
5189 				       &rsrc_info->header.cfg_shdr.response),
5190 				bf_get(lpfc_mbox_hdr_add_status,
5191 				       &rsrc_info->header.cfg_shdr.response));
5192 		rc = -EIO;
5193 		goto err_exit;
5194 	}
5195 
5196 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
5197 			      &rsrc_info->u.rsp);
5198 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
5199 			     &rsrc_info->u.rsp);
5200 
5201 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5202 			"3162 Retrieved extents type-%d from port: count:%d, "
5203 			"size:%d\n", type, *extnt_count, *extnt_size);
5204 
5205 err_exit:
5206 	mempool_free(mbox, phba->mbox_mem_pool);
5207 	return rc;
5208 }
5209 
5210 /**
5211  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
5212  * @phba: Pointer to HBA context object.
5213  * @type: The extent type to check.
5214  *
5215  * This function reads the current available extents from the port and checks
5216  * if the extent count or extent size has changed since the last access.
5217  * Callers use this routine post port reset to understand if there is a
5218  * extent reprovisioning requirement.
5219  *
5220  * Returns:
5221  *   -Error: error indicates problem.
5222  *   1: Extent count or size has changed.
5223  *   0: No changes.
5224  **/
5225 static int
5226 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
5227 {
5228 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
5229 	uint16_t size_diff, rsrc_ext_size;
5230 	int rc = 0;
5231 	struct lpfc_rsrc_blks *rsrc_entry;
5232 	struct list_head *rsrc_blk_list = NULL;
5233 
5234 	size_diff = 0;
5235 	curr_ext_cnt = 0;
5236 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5237 					    &rsrc_ext_cnt,
5238 					    &rsrc_ext_size);
5239 	if (unlikely(rc))
5240 		return -EIO;
5241 
5242 	switch (type) {
5243 	case LPFC_RSC_TYPE_FCOE_RPI:
5244 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5245 		break;
5246 	case LPFC_RSC_TYPE_FCOE_VPI:
5247 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
5248 		break;
5249 	case LPFC_RSC_TYPE_FCOE_XRI:
5250 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5251 		break;
5252 	case LPFC_RSC_TYPE_FCOE_VFI:
5253 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5254 		break;
5255 	default:
5256 		break;
5257 	}
5258 
5259 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
5260 		curr_ext_cnt++;
5261 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
5262 			size_diff++;
5263 	}
5264 
5265 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
5266 		rc = 1;
5267 
5268 	return rc;
5269 }
5270 
5271 /**
5272  * lpfc_sli4_cfg_post_extnts -
5273  * @phba: Pointer to HBA context object.
5274  * @extnt_cnt - number of available extents.
5275  * @type - the extent type (rpi, xri, vfi, vpi).
5276  * @emb - buffer to hold either MBX_EMBED or MBX_NEMBED operation.
5277  * @mbox - pointer to the caller's allocated mailbox structure.
5278  *
5279  * This function executes the extents allocation request.  It also
5280  * takes care of the amount of memory needed to allocate or get the
5281  * allocated extents. It is the caller's responsibility to evaluate
5282  * the response.
5283  *
5284  * Returns:
5285  *   -Error:  Error value describes the condition found.
5286  *   0: if successful
5287  **/
5288 static int
5289 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
5290 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
5291 {
5292 	int rc = 0;
5293 	uint32_t req_len;
5294 	uint32_t emb_len;
5295 	uint32_t alloc_len, mbox_tmo;
5296 
5297 	/* Calculate the total requested length of the dma memory */
5298 	req_len = extnt_cnt * sizeof(uint16_t);
5299 
5300 	/*
5301 	 * Calculate the size of an embedded mailbox.  The uint32_t
5302 	 * accounts for extents-specific word.
5303 	 */
5304 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
5305 		sizeof(uint32_t);
5306 
5307 	/*
5308 	 * Presume the allocation and response will fit into an embedded
5309 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
5310 	 */
5311 	*emb = LPFC_SLI4_MBX_EMBED;
5312 	if (req_len > emb_len) {
5313 		req_len = extnt_cnt * sizeof(uint16_t) +
5314 			sizeof(union lpfc_sli4_cfg_shdr) +
5315 			sizeof(uint32_t);
5316 		*emb = LPFC_SLI4_MBX_NEMBED;
5317 	}
5318 
5319 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5320 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
5321 				     req_len, *emb);
5322 	if (alloc_len < req_len) {
5323 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5324 			"2982 Allocated DMA memory size (x%x) is "
5325 			"less than the requested DMA memory "
5326 			"size (x%x)\n", alloc_len, req_len);
5327 		return -ENOMEM;
5328 	}
5329 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
5330 	if (unlikely(rc))
5331 		return -EIO;
5332 
5333 	if (!phba->sli4_hba.intr_enable)
5334 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5335 	else {
5336 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5337 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5338 	}
5339 
5340 	if (unlikely(rc))
5341 		rc = -EIO;
5342 	return rc;
5343 }
5344 
5345 /**
5346  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
5347  * @phba: Pointer to HBA context object.
5348  * @type:  The resource extent type to allocate.
5349  *
5350  * This function allocates the number of elements for the specified
5351  * resource type.
5352  **/
5353 static int
5354 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
5355 {
5356 	bool emb = false;
5357 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
5358 	uint16_t rsrc_id, rsrc_start, j, k;
5359 	uint16_t *ids;
5360 	int i, rc;
5361 	unsigned long longs;
5362 	unsigned long *bmask;
5363 	struct lpfc_rsrc_blks *rsrc_blks;
5364 	LPFC_MBOXQ_t *mbox;
5365 	uint32_t length;
5366 	struct lpfc_id_range *id_array = NULL;
5367 	void *virtaddr = NULL;
5368 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
5369 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
5370 	struct list_head *ext_blk_list;
5371 
5372 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5373 					    &rsrc_cnt,
5374 					    &rsrc_size);
5375 	if (unlikely(rc))
5376 		return -EIO;
5377 
5378 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
5379 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5380 			"3009 No available Resource Extents "
5381 			"for resource type 0x%x: Count: 0x%x, "
5382 			"Size 0x%x\n", type, rsrc_cnt,
5383 			rsrc_size);
5384 		return -ENOMEM;
5385 	}
5386 
5387 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
5388 			"2903 Post resource extents type-0x%x: "
5389 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
5390 
5391 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5392 	if (!mbox)
5393 		return -ENOMEM;
5394 
5395 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
5396 	if (unlikely(rc)) {
5397 		rc = -EIO;
5398 		goto err_exit;
5399 	}
5400 
5401 	/*
5402 	 * Figure out where the response is located.  Then get local pointers
5403 	 * to the response data.  The port does not guarantee to respond to
5404 	 * all extents counts request so update the local variable with the
5405 	 * allocated count from the port.
5406 	 */
5407 	if (emb == LPFC_SLI4_MBX_EMBED) {
5408 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
5409 		id_array = &rsrc_ext->u.rsp.id[0];
5410 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
5411 	} else {
5412 		virtaddr = mbox->sge_array->addr[0];
5413 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
5414 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
5415 		id_array = &n_rsrc->id;
5416 	}
5417 
5418 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
5419 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
5420 
5421 	/*
5422 	 * Based on the resource size and count, correct the base and max
5423 	 * resource values.
5424 	 */
5425 	length = sizeof(struct lpfc_rsrc_blks);
5426 	switch (type) {
5427 	case LPFC_RSC_TYPE_FCOE_RPI:
5428 		phba->sli4_hba.rpi_bmask = kzalloc(longs *
5429 						   sizeof(unsigned long),
5430 						   GFP_KERNEL);
5431 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
5432 			rc = -ENOMEM;
5433 			goto err_exit;
5434 		}
5435 		phba->sli4_hba.rpi_ids = kzalloc(rsrc_id_cnt *
5436 						 sizeof(uint16_t),
5437 						 GFP_KERNEL);
5438 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
5439 			kfree(phba->sli4_hba.rpi_bmask);
5440 			rc = -ENOMEM;
5441 			goto err_exit;
5442 		}
5443 
5444 		/*
5445 		 * The next_rpi was initialized with the maximum available
5446 		 * count but the port may allocate a smaller number.  Catch
5447 		 * that case and update the next_rpi.
5448 		 */
5449 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
5450 
5451 		/* Initialize local ptrs for common extent processing later. */
5452 		bmask = phba->sli4_hba.rpi_bmask;
5453 		ids = phba->sli4_hba.rpi_ids;
5454 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5455 		break;
5456 	case LPFC_RSC_TYPE_FCOE_VPI:
5457 		phba->vpi_bmask = kzalloc(longs *
5458 					  sizeof(unsigned long),
5459 					  GFP_KERNEL);
5460 		if (unlikely(!phba->vpi_bmask)) {
5461 			rc = -ENOMEM;
5462 			goto err_exit;
5463 		}
5464 		phba->vpi_ids = kzalloc(rsrc_id_cnt *
5465 					 sizeof(uint16_t),
5466 					 GFP_KERNEL);
5467 		if (unlikely(!phba->vpi_ids)) {
5468 			kfree(phba->vpi_bmask);
5469 			rc = -ENOMEM;
5470 			goto err_exit;
5471 		}
5472 
5473 		/* Initialize local ptrs for common extent processing later. */
5474 		bmask = phba->vpi_bmask;
5475 		ids = phba->vpi_ids;
5476 		ext_blk_list = &phba->lpfc_vpi_blk_list;
5477 		break;
5478 	case LPFC_RSC_TYPE_FCOE_XRI:
5479 		phba->sli4_hba.xri_bmask = kzalloc(longs *
5480 						   sizeof(unsigned long),
5481 						   GFP_KERNEL);
5482 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
5483 			rc = -ENOMEM;
5484 			goto err_exit;
5485 		}
5486 		phba->sli4_hba.max_cfg_param.xri_used = 0;
5487 		phba->sli4_hba.xri_ids = kzalloc(rsrc_id_cnt *
5488 						 sizeof(uint16_t),
5489 						 GFP_KERNEL);
5490 		if (unlikely(!phba->sli4_hba.xri_ids)) {
5491 			kfree(phba->sli4_hba.xri_bmask);
5492 			rc = -ENOMEM;
5493 			goto err_exit;
5494 		}
5495 
5496 		/* Initialize local ptrs for common extent processing later. */
5497 		bmask = phba->sli4_hba.xri_bmask;
5498 		ids = phba->sli4_hba.xri_ids;
5499 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5500 		break;
5501 	case LPFC_RSC_TYPE_FCOE_VFI:
5502 		phba->sli4_hba.vfi_bmask = kzalloc(longs *
5503 						   sizeof(unsigned long),
5504 						   GFP_KERNEL);
5505 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
5506 			rc = -ENOMEM;
5507 			goto err_exit;
5508 		}
5509 		phba->sli4_hba.vfi_ids = kzalloc(rsrc_id_cnt *
5510 						 sizeof(uint16_t),
5511 						 GFP_KERNEL);
5512 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
5513 			kfree(phba->sli4_hba.vfi_bmask);
5514 			rc = -ENOMEM;
5515 			goto err_exit;
5516 		}
5517 
5518 		/* Initialize local ptrs for common extent processing later. */
5519 		bmask = phba->sli4_hba.vfi_bmask;
5520 		ids = phba->sli4_hba.vfi_ids;
5521 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5522 		break;
5523 	default:
5524 		/* Unsupported Opcode.  Fail call. */
5525 		id_array = NULL;
5526 		bmask = NULL;
5527 		ids = NULL;
5528 		ext_blk_list = NULL;
5529 		goto err_exit;
5530 	}
5531 
5532 	/*
5533 	 * Complete initializing the extent configuration with the
5534 	 * allocated ids assigned to this function.  The bitmask serves
5535 	 * as an index into the array and manages the available ids.  The
5536 	 * array just stores the ids communicated to the port via the wqes.
5537 	 */
5538 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
5539 		if ((i % 2) == 0)
5540 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
5541 					 &id_array[k]);
5542 		else
5543 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
5544 					 &id_array[k]);
5545 
5546 		rsrc_blks = kzalloc(length, GFP_KERNEL);
5547 		if (unlikely(!rsrc_blks)) {
5548 			rc = -ENOMEM;
5549 			kfree(bmask);
5550 			kfree(ids);
5551 			goto err_exit;
5552 		}
5553 		rsrc_blks->rsrc_start = rsrc_id;
5554 		rsrc_blks->rsrc_size = rsrc_size;
5555 		list_add_tail(&rsrc_blks->list, ext_blk_list);
5556 		rsrc_start = rsrc_id;
5557 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0))
5558 			phba->sli4_hba.scsi_xri_start = rsrc_start +
5559 				lpfc_sli4_get_els_iocb_cnt(phba);
5560 
5561 		while (rsrc_id < (rsrc_start + rsrc_size)) {
5562 			ids[j] = rsrc_id;
5563 			rsrc_id++;
5564 			j++;
5565 		}
5566 		/* Entire word processed.  Get next word.*/
5567 		if ((i % 2) == 1)
5568 			k++;
5569 	}
5570  err_exit:
5571 	lpfc_sli4_mbox_cmd_free(phba, mbox);
5572 	return rc;
5573 }
5574 
5575 /**
5576  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
5577  * @phba: Pointer to HBA context object.
5578  * @type: the extent's type.
5579  *
5580  * This function deallocates all extents of a particular resource type.
5581  * SLI4 does not allow for deallocating a particular extent range.  It
5582  * is the caller's responsibility to release all kernel memory resources.
5583  **/
5584 static int
5585 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
5586 {
5587 	int rc;
5588 	uint32_t length, mbox_tmo = 0;
5589 	LPFC_MBOXQ_t *mbox;
5590 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
5591 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
5592 
5593 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5594 	if (!mbox)
5595 		return -ENOMEM;
5596 
5597 	/*
5598 	 * This function sends an embedded mailbox because it only sends the
5599 	 * the resource type.  All extents of this type are released by the
5600 	 * port.
5601 	 */
5602 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
5603 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5604 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5605 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
5606 			 length, LPFC_SLI4_MBX_EMBED);
5607 
5608 	/* Send an extents count of 0 - the dealloc doesn't use it. */
5609 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5610 					LPFC_SLI4_MBX_EMBED);
5611 	if (unlikely(rc)) {
5612 		rc = -EIO;
5613 		goto out_free_mbox;
5614 	}
5615 	if (!phba->sli4_hba.intr_enable)
5616 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5617 	else {
5618 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5619 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5620 	}
5621 	if (unlikely(rc)) {
5622 		rc = -EIO;
5623 		goto out_free_mbox;
5624 	}
5625 
5626 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
5627 	if (bf_get(lpfc_mbox_hdr_status,
5628 		   &dealloc_rsrc->header.cfg_shdr.response)) {
5629 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5630 				"2919 Failed to release resource extents "
5631 				"for type %d - Status 0x%x Add'l Status 0x%x. "
5632 				"Resource memory not released.\n",
5633 				type,
5634 				bf_get(lpfc_mbox_hdr_status,
5635 				    &dealloc_rsrc->header.cfg_shdr.response),
5636 				bf_get(lpfc_mbox_hdr_add_status,
5637 				    &dealloc_rsrc->header.cfg_shdr.response));
5638 		rc = -EIO;
5639 		goto out_free_mbox;
5640 	}
5641 
5642 	/* Release kernel memory resources for the specific type. */
5643 	switch (type) {
5644 	case LPFC_RSC_TYPE_FCOE_VPI:
5645 		kfree(phba->vpi_bmask);
5646 		kfree(phba->vpi_ids);
5647 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5648 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5649 				    &phba->lpfc_vpi_blk_list, list) {
5650 			list_del_init(&rsrc_blk->list);
5651 			kfree(rsrc_blk);
5652 		}
5653 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
5654 		break;
5655 	case LPFC_RSC_TYPE_FCOE_XRI:
5656 		kfree(phba->sli4_hba.xri_bmask);
5657 		kfree(phba->sli4_hba.xri_ids);
5658 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5659 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
5660 			list_del_init(&rsrc_blk->list);
5661 			kfree(rsrc_blk);
5662 		}
5663 		break;
5664 	case LPFC_RSC_TYPE_FCOE_VFI:
5665 		kfree(phba->sli4_hba.vfi_bmask);
5666 		kfree(phba->sli4_hba.vfi_ids);
5667 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5668 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5669 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
5670 			list_del_init(&rsrc_blk->list);
5671 			kfree(rsrc_blk);
5672 		}
5673 		break;
5674 	case LPFC_RSC_TYPE_FCOE_RPI:
5675 		/* RPI bitmask and physical id array are cleaned up earlier. */
5676 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5677 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
5678 			list_del_init(&rsrc_blk->list);
5679 			kfree(rsrc_blk);
5680 		}
5681 		break;
5682 	default:
5683 		break;
5684 	}
5685 
5686 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5687 
5688  out_free_mbox:
5689 	mempool_free(mbox, phba->mbox_mem_pool);
5690 	return rc;
5691 }
5692 
5693 /**
5694  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
5695  * @phba: Pointer to HBA context object.
5696  *
5697  * This function allocates all SLI4 resource identifiers.
5698  **/
5699 int
5700 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
5701 {
5702 	int i, rc, error = 0;
5703 	uint16_t count, base;
5704 	unsigned long longs;
5705 
5706 	if (!phba->sli4_hba.rpi_hdrs_in_use)
5707 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
5708 	if (phba->sli4_hba.extents_in_use) {
5709 		/*
5710 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
5711 		 * resource extent count must be read and allocated before
5712 		 * provisioning the resource id arrays.
5713 		 */
5714 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
5715 		    LPFC_IDX_RSRC_RDY) {
5716 			/*
5717 			 * Extent-based resources are set - the driver could
5718 			 * be in a port reset. Figure out if any corrective
5719 			 * actions need to be taken.
5720 			 */
5721 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5722 						 LPFC_RSC_TYPE_FCOE_VFI);
5723 			if (rc != 0)
5724 				error++;
5725 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5726 						 LPFC_RSC_TYPE_FCOE_VPI);
5727 			if (rc != 0)
5728 				error++;
5729 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5730 						 LPFC_RSC_TYPE_FCOE_XRI);
5731 			if (rc != 0)
5732 				error++;
5733 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5734 						 LPFC_RSC_TYPE_FCOE_RPI);
5735 			if (rc != 0)
5736 				error++;
5737 
5738 			/*
5739 			 * It's possible that the number of resources
5740 			 * provided to this port instance changed between
5741 			 * resets.  Detect this condition and reallocate
5742 			 * resources.  Otherwise, there is no action.
5743 			 */
5744 			if (error) {
5745 				lpfc_printf_log(phba, KERN_INFO,
5746 						LOG_MBOX | LOG_INIT,
5747 						"2931 Detected extent resource "
5748 						"change.  Reallocating all "
5749 						"extents.\n");
5750 				rc = lpfc_sli4_dealloc_extent(phba,
5751 						 LPFC_RSC_TYPE_FCOE_VFI);
5752 				rc = lpfc_sli4_dealloc_extent(phba,
5753 						 LPFC_RSC_TYPE_FCOE_VPI);
5754 				rc = lpfc_sli4_dealloc_extent(phba,
5755 						 LPFC_RSC_TYPE_FCOE_XRI);
5756 				rc = lpfc_sli4_dealloc_extent(phba,
5757 						 LPFC_RSC_TYPE_FCOE_RPI);
5758 			} else
5759 				return 0;
5760 		}
5761 
5762 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
5763 		if (unlikely(rc))
5764 			goto err_exit;
5765 
5766 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
5767 		if (unlikely(rc))
5768 			goto err_exit;
5769 
5770 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
5771 		if (unlikely(rc))
5772 			goto err_exit;
5773 
5774 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
5775 		if (unlikely(rc))
5776 			goto err_exit;
5777 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
5778 		       LPFC_IDX_RSRC_RDY);
5779 		return rc;
5780 	} else {
5781 		/*
5782 		 * The port does not support resource extents.  The XRI, VPI,
5783 		 * VFI, RPI resource ids were determined from READ_CONFIG.
5784 		 * Just allocate the bitmasks and provision the resource id
5785 		 * arrays.  If a port reset is active, the resources don't
5786 		 * need any action - just exit.
5787 		 */
5788 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
5789 		    LPFC_IDX_RSRC_RDY) {
5790 			lpfc_sli4_dealloc_resource_identifiers(phba);
5791 			lpfc_sli4_remove_rpis(phba);
5792 		}
5793 		/* RPIs. */
5794 		count = phba->sli4_hba.max_cfg_param.max_rpi;
5795 		if (count <= 0) {
5796 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5797 					"3279 Invalid provisioning of "
5798 					"rpi:%d\n", count);
5799 			rc = -EINVAL;
5800 			goto err_exit;
5801 		}
5802 		base = phba->sli4_hba.max_cfg_param.rpi_base;
5803 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5804 		phba->sli4_hba.rpi_bmask = kzalloc(longs *
5805 						   sizeof(unsigned long),
5806 						   GFP_KERNEL);
5807 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
5808 			rc = -ENOMEM;
5809 			goto err_exit;
5810 		}
5811 		phba->sli4_hba.rpi_ids = kzalloc(count *
5812 						 sizeof(uint16_t),
5813 						 GFP_KERNEL);
5814 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
5815 			rc = -ENOMEM;
5816 			goto free_rpi_bmask;
5817 		}
5818 
5819 		for (i = 0; i < count; i++)
5820 			phba->sli4_hba.rpi_ids[i] = base + i;
5821 
5822 		/* VPIs. */
5823 		count = phba->sli4_hba.max_cfg_param.max_vpi;
5824 		if (count <= 0) {
5825 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5826 					"3280 Invalid provisioning of "
5827 					"vpi:%d\n", count);
5828 			rc = -EINVAL;
5829 			goto free_rpi_ids;
5830 		}
5831 		base = phba->sli4_hba.max_cfg_param.vpi_base;
5832 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5833 		phba->vpi_bmask = kzalloc(longs *
5834 					  sizeof(unsigned long),
5835 					  GFP_KERNEL);
5836 		if (unlikely(!phba->vpi_bmask)) {
5837 			rc = -ENOMEM;
5838 			goto free_rpi_ids;
5839 		}
5840 		phba->vpi_ids = kzalloc(count *
5841 					sizeof(uint16_t),
5842 					GFP_KERNEL);
5843 		if (unlikely(!phba->vpi_ids)) {
5844 			rc = -ENOMEM;
5845 			goto free_vpi_bmask;
5846 		}
5847 
5848 		for (i = 0; i < count; i++)
5849 			phba->vpi_ids[i] = base + i;
5850 
5851 		/* XRIs. */
5852 		count = phba->sli4_hba.max_cfg_param.max_xri;
5853 		if (count <= 0) {
5854 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5855 					"3281 Invalid provisioning of "
5856 					"xri:%d\n", count);
5857 			rc = -EINVAL;
5858 			goto free_vpi_ids;
5859 		}
5860 		base = phba->sli4_hba.max_cfg_param.xri_base;
5861 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5862 		phba->sli4_hba.xri_bmask = kzalloc(longs *
5863 						   sizeof(unsigned long),
5864 						   GFP_KERNEL);
5865 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
5866 			rc = -ENOMEM;
5867 			goto free_vpi_ids;
5868 		}
5869 		phba->sli4_hba.max_cfg_param.xri_used = 0;
5870 		phba->sli4_hba.xri_ids = kzalloc(count *
5871 						 sizeof(uint16_t),
5872 						 GFP_KERNEL);
5873 		if (unlikely(!phba->sli4_hba.xri_ids)) {
5874 			rc = -ENOMEM;
5875 			goto free_xri_bmask;
5876 		}
5877 
5878 		for (i = 0; i < count; i++)
5879 			phba->sli4_hba.xri_ids[i] = base + i;
5880 
5881 		/* VFIs. */
5882 		count = phba->sli4_hba.max_cfg_param.max_vfi;
5883 		if (count <= 0) {
5884 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5885 					"3282 Invalid provisioning of "
5886 					"vfi:%d\n", count);
5887 			rc = -EINVAL;
5888 			goto free_xri_ids;
5889 		}
5890 		base = phba->sli4_hba.max_cfg_param.vfi_base;
5891 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5892 		phba->sli4_hba.vfi_bmask = kzalloc(longs *
5893 						   sizeof(unsigned long),
5894 						   GFP_KERNEL);
5895 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
5896 			rc = -ENOMEM;
5897 			goto free_xri_ids;
5898 		}
5899 		phba->sli4_hba.vfi_ids = kzalloc(count *
5900 						 sizeof(uint16_t),
5901 						 GFP_KERNEL);
5902 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
5903 			rc = -ENOMEM;
5904 			goto free_vfi_bmask;
5905 		}
5906 
5907 		for (i = 0; i < count; i++)
5908 			phba->sli4_hba.vfi_ids[i] = base + i;
5909 
5910 		/*
5911 		 * Mark all resources ready.  An HBA reset doesn't need
5912 		 * to reset the initialization.
5913 		 */
5914 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
5915 		       LPFC_IDX_RSRC_RDY);
5916 		return 0;
5917 	}
5918 
5919  free_vfi_bmask:
5920 	kfree(phba->sli4_hba.vfi_bmask);
5921  free_xri_ids:
5922 	kfree(phba->sli4_hba.xri_ids);
5923  free_xri_bmask:
5924 	kfree(phba->sli4_hba.xri_bmask);
5925  free_vpi_ids:
5926 	kfree(phba->vpi_ids);
5927  free_vpi_bmask:
5928 	kfree(phba->vpi_bmask);
5929  free_rpi_ids:
5930 	kfree(phba->sli4_hba.rpi_ids);
5931  free_rpi_bmask:
5932 	kfree(phba->sli4_hba.rpi_bmask);
5933  err_exit:
5934 	return rc;
5935 }
5936 
5937 /**
5938  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
5939  * @phba: Pointer to HBA context object.
5940  *
5941  * This function allocates the number of elements for the specified
5942  * resource type.
5943  **/
5944 int
5945 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
5946 {
5947 	if (phba->sli4_hba.extents_in_use) {
5948 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
5949 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
5950 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
5951 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
5952 	} else {
5953 		kfree(phba->vpi_bmask);
5954 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
5955 		kfree(phba->vpi_ids);
5956 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5957 		kfree(phba->sli4_hba.xri_bmask);
5958 		kfree(phba->sli4_hba.xri_ids);
5959 		kfree(phba->sli4_hba.vfi_bmask);
5960 		kfree(phba->sli4_hba.vfi_ids);
5961 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5962 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5963 	}
5964 
5965 	return 0;
5966 }
5967 
5968 /**
5969  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
5970  * @phba: Pointer to HBA context object.
5971  * @type: The resource extent type.
5972  * @extnt_count: buffer to hold port extent count response
5973  * @extnt_size: buffer to hold port extent size response.
5974  *
5975  * This function calls the port to read the host allocated extents
5976  * for a particular type.
5977  **/
5978 int
5979 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
5980 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
5981 {
5982 	bool emb;
5983 	int rc = 0;
5984 	uint16_t curr_blks = 0;
5985 	uint32_t req_len, emb_len;
5986 	uint32_t alloc_len, mbox_tmo;
5987 	struct list_head *blk_list_head;
5988 	struct lpfc_rsrc_blks *rsrc_blk;
5989 	LPFC_MBOXQ_t *mbox;
5990 	void *virtaddr = NULL;
5991 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
5992 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
5993 	union  lpfc_sli4_cfg_shdr *shdr;
5994 
5995 	switch (type) {
5996 	case LPFC_RSC_TYPE_FCOE_VPI:
5997 		blk_list_head = &phba->lpfc_vpi_blk_list;
5998 		break;
5999 	case LPFC_RSC_TYPE_FCOE_XRI:
6000 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
6001 		break;
6002 	case LPFC_RSC_TYPE_FCOE_VFI:
6003 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
6004 		break;
6005 	case LPFC_RSC_TYPE_FCOE_RPI:
6006 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
6007 		break;
6008 	default:
6009 		return -EIO;
6010 	}
6011 
6012 	/* Count the number of extents currently allocatd for this type. */
6013 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
6014 		if (curr_blks == 0) {
6015 			/*
6016 			 * The GET_ALLOCATED mailbox does not return the size,
6017 			 * just the count.  The size should be just the size
6018 			 * stored in the current allocated block and all sizes
6019 			 * for an extent type are the same so set the return
6020 			 * value now.
6021 			 */
6022 			*extnt_size = rsrc_blk->rsrc_size;
6023 		}
6024 		curr_blks++;
6025 	}
6026 
6027 	/*
6028 	 * Calculate the size of an embedded mailbox.  The uint32_t
6029 	 * accounts for extents-specific word.
6030 	 */
6031 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6032 		sizeof(uint32_t);
6033 
6034 	/*
6035 	 * Presume the allocation and response will fit into an embedded
6036 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6037 	 */
6038 	emb = LPFC_SLI4_MBX_EMBED;
6039 	req_len = emb_len;
6040 	if (req_len > emb_len) {
6041 		req_len = curr_blks * sizeof(uint16_t) +
6042 			sizeof(union lpfc_sli4_cfg_shdr) +
6043 			sizeof(uint32_t);
6044 		emb = LPFC_SLI4_MBX_NEMBED;
6045 	}
6046 
6047 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6048 	if (!mbox)
6049 		return -ENOMEM;
6050 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
6051 
6052 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6053 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
6054 				     req_len, emb);
6055 	if (alloc_len < req_len) {
6056 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6057 			"2983 Allocated DMA memory size (x%x) is "
6058 			"less than the requested DMA memory "
6059 			"size (x%x)\n", alloc_len, req_len);
6060 		rc = -ENOMEM;
6061 		goto err_exit;
6062 	}
6063 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
6064 	if (unlikely(rc)) {
6065 		rc = -EIO;
6066 		goto err_exit;
6067 	}
6068 
6069 	if (!phba->sli4_hba.intr_enable)
6070 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6071 	else {
6072 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6073 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6074 	}
6075 
6076 	if (unlikely(rc)) {
6077 		rc = -EIO;
6078 		goto err_exit;
6079 	}
6080 
6081 	/*
6082 	 * Figure out where the response is located.  Then get local pointers
6083 	 * to the response data.  The port does not guarantee to respond to
6084 	 * all extents counts request so update the local variable with the
6085 	 * allocated count from the port.
6086 	 */
6087 	if (emb == LPFC_SLI4_MBX_EMBED) {
6088 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6089 		shdr = &rsrc_ext->header.cfg_shdr;
6090 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6091 	} else {
6092 		virtaddr = mbox->sge_array->addr[0];
6093 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6094 		shdr = &n_rsrc->cfg_shdr;
6095 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6096 	}
6097 
6098 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
6099 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
6100 			"2984 Failed to read allocated resources "
6101 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
6102 			type,
6103 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
6104 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
6105 		rc = -EIO;
6106 		goto err_exit;
6107 	}
6108  err_exit:
6109 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6110 	return rc;
6111 }
6112 
6113 /**
6114  * lpfc_sli4_repost_els_sgl_list - Repsot the els buffers sgl pages as block
6115  * @phba: pointer to lpfc hba data structure.
6116  *
6117  * This routine walks the list of els buffers that have been allocated and
6118  * repost them to the port by using SGL block post. This is needed after a
6119  * pci_function_reset/warm_start or start. It attempts to construct blocks
6120  * of els buffer sgls which contains contiguous xris and uses the non-embedded
6121  * SGL block post mailbox commands to post them to the port. For single els
6122  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
6123  * mailbox command for posting.
6124  *
6125  * Returns: 0 = success, non-zero failure.
6126  **/
6127 static int
6128 lpfc_sli4_repost_els_sgl_list(struct lpfc_hba *phba)
6129 {
6130 	struct lpfc_sglq *sglq_entry = NULL;
6131 	struct lpfc_sglq *sglq_entry_next = NULL;
6132 	struct lpfc_sglq *sglq_entry_first = NULL;
6133 	int status, total_cnt, post_cnt = 0, num_posted = 0, block_cnt = 0;
6134 	int last_xritag = NO_XRI;
6135 	struct lpfc_sli_ring *pring;
6136 	LIST_HEAD(prep_sgl_list);
6137 	LIST_HEAD(blck_sgl_list);
6138 	LIST_HEAD(allc_sgl_list);
6139 	LIST_HEAD(post_sgl_list);
6140 	LIST_HEAD(free_sgl_list);
6141 
6142 	pring = &phba->sli.ring[LPFC_ELS_RING];
6143 	spin_lock_irq(&phba->hbalock);
6144 	spin_lock(&pring->ring_lock);
6145 	list_splice_init(&phba->sli4_hba.lpfc_sgl_list, &allc_sgl_list);
6146 	spin_unlock(&pring->ring_lock);
6147 	spin_unlock_irq(&phba->hbalock);
6148 
6149 	total_cnt = phba->sli4_hba.els_xri_cnt;
6150 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
6151 				 &allc_sgl_list, list) {
6152 		list_del_init(&sglq_entry->list);
6153 		block_cnt++;
6154 		if ((last_xritag != NO_XRI) &&
6155 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
6156 			/* a hole in xri block, form a sgl posting block */
6157 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
6158 			post_cnt = block_cnt - 1;
6159 			/* prepare list for next posting block */
6160 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6161 			block_cnt = 1;
6162 		} else {
6163 			/* prepare list for next posting block */
6164 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6165 			/* enough sgls for non-embed sgl mbox command */
6166 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
6167 				list_splice_init(&prep_sgl_list,
6168 						 &blck_sgl_list);
6169 				post_cnt = block_cnt;
6170 				block_cnt = 0;
6171 			}
6172 		}
6173 		num_posted++;
6174 
6175 		/* keep track of last sgl's xritag */
6176 		last_xritag = sglq_entry->sli4_xritag;
6177 
6178 		/* end of repost sgl list condition for els buffers */
6179 		if (num_posted == phba->sli4_hba.els_xri_cnt) {
6180 			if (post_cnt == 0) {
6181 				list_splice_init(&prep_sgl_list,
6182 						 &blck_sgl_list);
6183 				post_cnt = block_cnt;
6184 			} else if (block_cnt == 1) {
6185 				status = lpfc_sli4_post_sgl(phba,
6186 						sglq_entry->phys, 0,
6187 						sglq_entry->sli4_xritag);
6188 				if (!status) {
6189 					/* successful, put sgl to posted list */
6190 					list_add_tail(&sglq_entry->list,
6191 						      &post_sgl_list);
6192 				} else {
6193 					/* Failure, put sgl to free list */
6194 					lpfc_printf_log(phba, KERN_WARNING,
6195 						LOG_SLI,
6196 						"3159 Failed to post els "
6197 						"sgl, xritag:x%x\n",
6198 						sglq_entry->sli4_xritag);
6199 					list_add_tail(&sglq_entry->list,
6200 						      &free_sgl_list);
6201 					total_cnt--;
6202 				}
6203 			}
6204 		}
6205 
6206 		/* continue until a nembed page worth of sgls */
6207 		if (post_cnt == 0)
6208 			continue;
6209 
6210 		/* post the els buffer list sgls as a block */
6211 		status = lpfc_sli4_post_els_sgl_list(phba, &blck_sgl_list,
6212 						     post_cnt);
6213 
6214 		if (!status) {
6215 			/* success, put sgl list to posted sgl list */
6216 			list_splice_init(&blck_sgl_list, &post_sgl_list);
6217 		} else {
6218 			/* Failure, put sgl list to free sgl list */
6219 			sglq_entry_first = list_first_entry(&blck_sgl_list,
6220 							    struct lpfc_sglq,
6221 							    list);
6222 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6223 					"3160 Failed to post els sgl-list, "
6224 					"xritag:x%x-x%x\n",
6225 					sglq_entry_first->sli4_xritag,
6226 					(sglq_entry_first->sli4_xritag +
6227 					 post_cnt - 1));
6228 			list_splice_init(&blck_sgl_list, &free_sgl_list);
6229 			total_cnt -= post_cnt;
6230 		}
6231 
6232 		/* don't reset xirtag due to hole in xri block */
6233 		if (block_cnt == 0)
6234 			last_xritag = NO_XRI;
6235 
6236 		/* reset els sgl post count for next round of posting */
6237 		post_cnt = 0;
6238 	}
6239 	/* update the number of XRIs posted for ELS */
6240 	phba->sli4_hba.els_xri_cnt = total_cnt;
6241 
6242 	/* free the els sgls failed to post */
6243 	lpfc_free_sgl_list(phba, &free_sgl_list);
6244 
6245 	/* push els sgls posted to the availble list */
6246 	if (!list_empty(&post_sgl_list)) {
6247 		spin_lock_irq(&phba->hbalock);
6248 		spin_lock(&pring->ring_lock);
6249 		list_splice_init(&post_sgl_list,
6250 				 &phba->sli4_hba.lpfc_sgl_list);
6251 		spin_unlock(&pring->ring_lock);
6252 		spin_unlock_irq(&phba->hbalock);
6253 	} else {
6254 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6255 				"3161 Failure to post els sgl to port.\n");
6256 		return -EIO;
6257 	}
6258 	return 0;
6259 }
6260 
6261 /**
6262  * lpfc_sli4_hba_setup - SLI4 device intialization PCI function
6263  * @phba: Pointer to HBA context object.
6264  *
6265  * This function is the main SLI4 device intialization PCI function. This
6266  * function is called by the HBA intialization code, HBA reset code and
6267  * HBA error attention handler code. Caller is not required to hold any
6268  * locks.
6269  **/
6270 int
6271 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
6272 {
6273 	int rc;
6274 	LPFC_MBOXQ_t *mboxq;
6275 	struct lpfc_mqe *mqe;
6276 	uint8_t *vpd;
6277 	uint32_t vpd_size;
6278 	uint32_t ftr_rsp = 0;
6279 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
6280 	struct lpfc_vport *vport = phba->pport;
6281 	struct lpfc_dmabuf *mp;
6282 
6283 	/* Perform a PCI function reset to start from clean */
6284 	rc = lpfc_pci_function_reset(phba);
6285 	if (unlikely(rc))
6286 		return -ENODEV;
6287 
6288 	/* Check the HBA Host Status Register for readyness */
6289 	rc = lpfc_sli4_post_status_check(phba);
6290 	if (unlikely(rc))
6291 		return -ENODEV;
6292 	else {
6293 		spin_lock_irq(&phba->hbalock);
6294 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
6295 		spin_unlock_irq(&phba->hbalock);
6296 	}
6297 
6298 	/*
6299 	 * Allocate a single mailbox container for initializing the
6300 	 * port.
6301 	 */
6302 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6303 	if (!mboxq)
6304 		return -ENOMEM;
6305 
6306 	/* Issue READ_REV to collect vpd and FW information. */
6307 	vpd_size = SLI4_PAGE_SIZE;
6308 	vpd = kzalloc(vpd_size, GFP_KERNEL);
6309 	if (!vpd) {
6310 		rc = -ENOMEM;
6311 		goto out_free_mbox;
6312 	}
6313 
6314 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
6315 	if (unlikely(rc)) {
6316 		kfree(vpd);
6317 		goto out_free_mbox;
6318 	}
6319 
6320 	mqe = &mboxq->u.mqe;
6321 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
6322 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
6323 		phba->hba_flag |= HBA_FCOE_MODE;
6324 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
6325 	} else {
6326 		phba->hba_flag &= ~HBA_FCOE_MODE;
6327 	}
6328 
6329 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
6330 		LPFC_DCBX_CEE_MODE)
6331 		phba->hba_flag |= HBA_FIP_SUPPORT;
6332 	else
6333 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
6334 
6335 	phba->hba_flag &= ~HBA_FCP_IOQ_FLUSH;
6336 
6337 	if (phba->sli_rev != LPFC_SLI_REV4) {
6338 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6339 			"0376 READ_REV Error. SLI Level %d "
6340 			"FCoE enabled %d\n",
6341 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
6342 		rc = -EIO;
6343 		kfree(vpd);
6344 		goto out_free_mbox;
6345 	}
6346 
6347 	/*
6348 	 * Continue initialization with default values even if driver failed
6349 	 * to read FCoE param config regions, only read parameters if the
6350 	 * board is FCoE
6351 	 */
6352 	if (phba->hba_flag & HBA_FCOE_MODE &&
6353 	    lpfc_sli4_read_fcoe_params(phba))
6354 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
6355 			"2570 Failed to read FCoE parameters\n");
6356 
6357 	/*
6358 	 * Retrieve sli4 device physical port name, failure of doing it
6359 	 * is considered as non-fatal.
6360 	 */
6361 	rc = lpfc_sli4_retrieve_pport_name(phba);
6362 	if (!rc)
6363 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
6364 				"3080 Successful retrieving SLI4 device "
6365 				"physical port name: %s.\n", phba->Port);
6366 
6367 	/*
6368 	 * Evaluate the read rev and vpd data. Populate the driver
6369 	 * state with the results. If this routine fails, the failure
6370 	 * is not fatal as the driver will use generic values.
6371 	 */
6372 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
6373 	if (unlikely(!rc)) {
6374 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6375 				"0377 Error %d parsing vpd. "
6376 				"Using defaults.\n", rc);
6377 		rc = 0;
6378 	}
6379 	kfree(vpd);
6380 
6381 	/* Save information as VPD data */
6382 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
6383 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
6384 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
6385 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
6386 					 &mqe->un.read_rev);
6387 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
6388 				       &mqe->un.read_rev);
6389 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
6390 					    &mqe->un.read_rev);
6391 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
6392 					   &mqe->un.read_rev);
6393 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
6394 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
6395 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
6396 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
6397 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
6398 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
6399 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
6400 			"(%d):0380 READ_REV Status x%x "
6401 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
6402 			mboxq->vport ? mboxq->vport->vpi : 0,
6403 			bf_get(lpfc_mqe_status, mqe),
6404 			phba->vpd.rev.opFwName,
6405 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
6406 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
6407 
6408 	/* Reset the DFT_LUN_Q_DEPTH to (max xri >> 3)  */
6409 	rc = (phba->sli4_hba.max_cfg_param.max_xri >> 3);
6410 	if (phba->pport->cfg_lun_queue_depth > rc) {
6411 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6412 				"3362 LUN queue depth changed from %d to %d\n",
6413 				phba->pport->cfg_lun_queue_depth, rc);
6414 		phba->pport->cfg_lun_queue_depth = rc;
6415 	}
6416 
6417 
6418 	/*
6419 	 * Discover the port's supported feature set and match it against the
6420 	 * hosts requests.
6421 	 */
6422 	lpfc_request_features(phba, mboxq);
6423 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6424 	if (unlikely(rc)) {
6425 		rc = -EIO;
6426 		goto out_free_mbox;
6427 	}
6428 
6429 	/*
6430 	 * The port must support FCP initiator mode as this is the
6431 	 * only mode running in the host.
6432 	 */
6433 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
6434 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
6435 				"0378 No support for fcpi mode.\n");
6436 		ftr_rsp++;
6437 	}
6438 	if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
6439 		phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
6440 	else
6441 		phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
6442 	/*
6443 	 * If the port cannot support the host's requested features
6444 	 * then turn off the global config parameters to disable the
6445 	 * feature in the driver.  This is not a fatal error.
6446 	 */
6447 	phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
6448 	if (phba->cfg_enable_bg) {
6449 		if (bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))
6450 			phba->sli3_options |= LPFC_SLI3_BG_ENABLED;
6451 		else
6452 			ftr_rsp++;
6453 	}
6454 
6455 	if (phba->max_vpi && phba->cfg_enable_npiv &&
6456 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
6457 		ftr_rsp++;
6458 
6459 	if (ftr_rsp) {
6460 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
6461 				"0379 Feature Mismatch Data: x%08x %08x "
6462 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
6463 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
6464 				phba->cfg_enable_npiv, phba->max_vpi);
6465 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
6466 			phba->cfg_enable_bg = 0;
6467 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
6468 			phba->cfg_enable_npiv = 0;
6469 	}
6470 
6471 	/* These SLI3 features are assumed in SLI4 */
6472 	spin_lock_irq(&phba->hbalock);
6473 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
6474 	spin_unlock_irq(&phba->hbalock);
6475 
6476 	/*
6477 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
6478 	 * calls depends on these resources to complete port setup.
6479 	 */
6480 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
6481 	if (rc) {
6482 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6483 				"2920 Failed to alloc Resource IDs "
6484 				"rc = x%x\n", rc);
6485 		goto out_free_mbox;
6486 	}
6487 
6488 	/* Read the port's service parameters. */
6489 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
6490 	if (rc) {
6491 		phba->link_state = LPFC_HBA_ERROR;
6492 		rc = -ENOMEM;
6493 		goto out_free_mbox;
6494 	}
6495 
6496 	mboxq->vport = vport;
6497 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6498 	mp = (struct lpfc_dmabuf *) mboxq->context1;
6499 	if (rc == MBX_SUCCESS) {
6500 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
6501 		rc = 0;
6502 	}
6503 
6504 	/*
6505 	 * This memory was allocated by the lpfc_read_sparam routine. Release
6506 	 * it to the mbuf pool.
6507 	 */
6508 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
6509 	kfree(mp);
6510 	mboxq->context1 = NULL;
6511 	if (unlikely(rc)) {
6512 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6513 				"0382 READ_SPARAM command failed "
6514 				"status %d, mbxStatus x%x\n",
6515 				rc, bf_get(lpfc_mqe_status, mqe));
6516 		phba->link_state = LPFC_HBA_ERROR;
6517 		rc = -EIO;
6518 		goto out_free_mbox;
6519 	}
6520 
6521 	lpfc_update_vport_wwn(vport);
6522 
6523 	/* Update the fc_host data structures with new wwn. */
6524 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
6525 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
6526 
6527 	/* update host els and scsi xri-sgl sizes and mappings */
6528 	rc = lpfc_sli4_xri_sgl_update(phba);
6529 	if (unlikely(rc)) {
6530 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6531 				"1400 Failed to update xri-sgl size and "
6532 				"mapping: %d\n", rc);
6533 		goto out_free_mbox;
6534 	}
6535 
6536 	/* register the els sgl pool to the port */
6537 	rc = lpfc_sli4_repost_els_sgl_list(phba);
6538 	if (unlikely(rc)) {
6539 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6540 				"0582 Error %d during els sgl post "
6541 				"operation\n", rc);
6542 		rc = -ENODEV;
6543 		goto out_free_mbox;
6544 	}
6545 
6546 	/* register the allocated scsi sgl pool to the port */
6547 	rc = lpfc_sli4_repost_scsi_sgl_list(phba);
6548 	if (unlikely(rc)) {
6549 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6550 				"0383 Error %d during scsi sgl post "
6551 				"operation\n", rc);
6552 		/* Some Scsi buffers were moved to the abort scsi list */
6553 		/* A pci function reset will repost them */
6554 		rc = -ENODEV;
6555 		goto out_free_mbox;
6556 	}
6557 
6558 	/* Post the rpi header region to the device. */
6559 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
6560 	if (unlikely(rc)) {
6561 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6562 				"0393 Error %d during rpi post operation\n",
6563 				rc);
6564 		rc = -ENODEV;
6565 		goto out_free_mbox;
6566 	}
6567 	lpfc_sli4_node_prep(phba);
6568 
6569 	/* Create all the SLI4 queues */
6570 	rc = lpfc_sli4_queue_create(phba);
6571 	if (rc) {
6572 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6573 				"3089 Failed to allocate queues\n");
6574 		rc = -ENODEV;
6575 		goto out_stop_timers;
6576 	}
6577 	/* Set up all the queues to the device */
6578 	rc = lpfc_sli4_queue_setup(phba);
6579 	if (unlikely(rc)) {
6580 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6581 				"0381 Error %d during queue setup.\n ", rc);
6582 		goto out_destroy_queue;
6583 	}
6584 
6585 	/* Arm the CQs and then EQs on device */
6586 	lpfc_sli4_arm_cqeq_intr(phba);
6587 
6588 	/* Indicate device interrupt mode */
6589 	phba->sli4_hba.intr_enable = 1;
6590 
6591 	/* Allow asynchronous mailbox command to go through */
6592 	spin_lock_irq(&phba->hbalock);
6593 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
6594 	spin_unlock_irq(&phba->hbalock);
6595 
6596 	/* Post receive buffers to the device */
6597 	lpfc_sli4_rb_setup(phba);
6598 
6599 	/* Reset HBA FCF states after HBA reset */
6600 	phba->fcf.fcf_flag = 0;
6601 	phba->fcf.current_rec.flag = 0;
6602 
6603 	/* Start the ELS watchdog timer */
6604 	mod_timer(&vport->els_tmofunc,
6605 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
6606 
6607 	/* Start heart beat timer */
6608 	mod_timer(&phba->hb_tmofunc,
6609 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
6610 	phba->hb_outstanding = 0;
6611 	phba->last_completion_time = jiffies;
6612 
6613 	/* Start error attention (ERATT) polling timer */
6614 	mod_timer(&phba->eratt_poll,
6615 		  jiffies + msecs_to_jiffies(1000 * LPFC_ERATT_POLL_INTERVAL));
6616 
6617 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
6618 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
6619 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
6620 		if (!rc) {
6621 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6622 					"2829 This device supports "
6623 					"Advanced Error Reporting (AER)\n");
6624 			spin_lock_irq(&phba->hbalock);
6625 			phba->hba_flag |= HBA_AER_ENABLED;
6626 			spin_unlock_irq(&phba->hbalock);
6627 		} else {
6628 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6629 					"2830 This device does not support "
6630 					"Advanced Error Reporting (AER)\n");
6631 			phba->cfg_aer_support = 0;
6632 		}
6633 		rc = 0;
6634 	}
6635 
6636 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
6637 		/*
6638 		 * The FC Port needs to register FCFI (index 0)
6639 		 */
6640 		lpfc_reg_fcfi(phba, mboxq);
6641 		mboxq->vport = phba->pport;
6642 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6643 		if (rc != MBX_SUCCESS)
6644 			goto out_unset_queue;
6645 		rc = 0;
6646 		phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
6647 					&mboxq->u.mqe.un.reg_fcfi);
6648 
6649 		/* Check if the port is configured to be disabled */
6650 		lpfc_sli_read_link_ste(phba);
6651 	}
6652 
6653 	/*
6654 	 * The port is ready, set the host's link state to LINK_DOWN
6655 	 * in preparation for link interrupts.
6656 	 */
6657 	spin_lock_irq(&phba->hbalock);
6658 	phba->link_state = LPFC_LINK_DOWN;
6659 	spin_unlock_irq(&phba->hbalock);
6660 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
6661 	    (phba->hba_flag & LINK_DISABLED)) {
6662 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
6663 				"3103 Adapter Link is disabled.\n");
6664 		lpfc_down_link(phba, mboxq);
6665 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6666 		if (rc != MBX_SUCCESS) {
6667 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
6668 					"3104 Adapter failed to issue "
6669 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
6670 			goto out_unset_queue;
6671 		}
6672 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
6673 		/* don't perform init_link on SLI4 FC port loopback test */
6674 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
6675 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
6676 			if (rc)
6677 				goto out_unset_queue;
6678 		}
6679 	}
6680 	mempool_free(mboxq, phba->mbox_mem_pool);
6681 	return rc;
6682 out_unset_queue:
6683 	/* Unset all the queues set up in this routine when error out */
6684 	lpfc_sli4_queue_unset(phba);
6685 out_destroy_queue:
6686 	lpfc_sli4_queue_destroy(phba);
6687 out_stop_timers:
6688 	lpfc_stop_hba_timers(phba);
6689 out_free_mbox:
6690 	mempool_free(mboxq, phba->mbox_mem_pool);
6691 	return rc;
6692 }
6693 
6694 /**
6695  * lpfc_mbox_timeout - Timeout call back function for mbox timer
6696  * @ptr: context object - pointer to hba structure.
6697  *
6698  * This is the callback function for mailbox timer. The mailbox
6699  * timer is armed when a new mailbox command is issued and the timer
6700  * is deleted when the mailbox complete. The function is called by
6701  * the kernel timer code when a mailbox does not complete within
6702  * expected time. This function wakes up the worker thread to
6703  * process the mailbox timeout and returns. All the processing is
6704  * done by the worker thread function lpfc_mbox_timeout_handler.
6705  **/
6706 void
6707 lpfc_mbox_timeout(unsigned long ptr)
6708 {
6709 	struct lpfc_hba  *phba = (struct lpfc_hba *) ptr;
6710 	unsigned long iflag;
6711 	uint32_t tmo_posted;
6712 
6713 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
6714 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
6715 	if (!tmo_posted)
6716 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
6717 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
6718 
6719 	if (!tmo_posted)
6720 		lpfc_worker_wake_up(phba);
6721 	return;
6722 }
6723 
6724 /**
6725  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
6726  *                                    are pending
6727  * @phba: Pointer to HBA context object.
6728  *
6729  * This function checks if any mailbox completions are present on the mailbox
6730  * completion queue.
6731  **/
6732 static bool
6733 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
6734 {
6735 
6736 	uint32_t idx;
6737 	struct lpfc_queue *mcq;
6738 	struct lpfc_mcqe *mcqe;
6739 	bool pending_completions = false;
6740 
6741 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
6742 		return false;
6743 
6744 	/* Check for completions on mailbox completion queue */
6745 
6746 	mcq = phba->sli4_hba.mbx_cq;
6747 	idx = mcq->hba_index;
6748 	while (bf_get_le32(lpfc_cqe_valid, mcq->qe[idx].cqe)) {
6749 		mcqe = (struct lpfc_mcqe *)mcq->qe[idx].cqe;
6750 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
6751 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
6752 			pending_completions = true;
6753 			break;
6754 		}
6755 		idx = (idx + 1) % mcq->entry_count;
6756 		if (mcq->hba_index == idx)
6757 			break;
6758 	}
6759 	return pending_completions;
6760 
6761 }
6762 
6763 /**
6764  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
6765  *					      that were missed.
6766  * @phba: Pointer to HBA context object.
6767  *
6768  * For sli4, it is possible to miss an interrupt. As such mbox completions
6769  * maybe missed causing erroneous mailbox timeouts to occur. This function
6770  * checks to see if mbox completions are on the mailbox completion queue
6771  * and will process all the completions associated with the eq for the
6772  * mailbox completion queue.
6773  **/
6774 bool
6775 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
6776 {
6777 
6778 	uint32_t eqidx;
6779 	struct lpfc_queue *fpeq = NULL;
6780 	struct lpfc_eqe *eqe;
6781 	bool mbox_pending;
6782 
6783 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
6784 		return false;
6785 
6786 	/* Find the eq associated with the mcq */
6787 
6788 	if (phba->sli4_hba.hba_eq)
6789 		for (eqidx = 0; eqidx < phba->cfg_fcp_io_channel; eqidx++)
6790 			if (phba->sli4_hba.hba_eq[eqidx]->queue_id ==
6791 			    phba->sli4_hba.mbx_cq->assoc_qid) {
6792 				fpeq = phba->sli4_hba.hba_eq[eqidx];
6793 				break;
6794 			}
6795 	if (!fpeq)
6796 		return false;
6797 
6798 	/* Turn off interrupts from this EQ */
6799 
6800 	lpfc_sli4_eq_clr_intr(fpeq);
6801 
6802 	/* Check to see if a mbox completion is pending */
6803 
6804 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
6805 
6806 	/*
6807 	 * If a mbox completion is pending, process all the events on EQ
6808 	 * associated with the mbox completion queue (this could include
6809 	 * mailbox commands, async events, els commands, receive queue data
6810 	 * and fcp commands)
6811 	 */
6812 
6813 	if (mbox_pending)
6814 		while ((eqe = lpfc_sli4_eq_get(fpeq))) {
6815 			lpfc_sli4_hba_handle_eqe(phba, eqe, eqidx);
6816 			fpeq->EQ_processed++;
6817 		}
6818 
6819 	/* Always clear and re-arm the EQ */
6820 
6821 	lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_REARM);
6822 
6823 	return mbox_pending;
6824 
6825 }
6826 
6827 /**
6828  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
6829  * @phba: Pointer to HBA context object.
6830  *
6831  * This function is called from worker thread when a mailbox command times out.
6832  * The caller is not required to hold any locks. This function will reset the
6833  * HBA and recover all the pending commands.
6834  **/
6835 void
6836 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
6837 {
6838 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
6839 	MAILBOX_t *mb = NULL;
6840 
6841 	struct lpfc_sli *psli = &phba->sli;
6842 
6843 	/* If the mailbox completed, process the completion and return */
6844 	if (lpfc_sli4_process_missed_mbox_completions(phba))
6845 		return;
6846 
6847 	if (pmbox != NULL)
6848 		mb = &pmbox->u.mb;
6849 	/* Check the pmbox pointer first.  There is a race condition
6850 	 * between the mbox timeout handler getting executed in the
6851 	 * worklist and the mailbox actually completing. When this
6852 	 * race condition occurs, the mbox_active will be NULL.
6853 	 */
6854 	spin_lock_irq(&phba->hbalock);
6855 	if (pmbox == NULL) {
6856 		lpfc_printf_log(phba, KERN_WARNING,
6857 				LOG_MBOX | LOG_SLI,
6858 				"0353 Active Mailbox cleared - mailbox timeout "
6859 				"exiting\n");
6860 		spin_unlock_irq(&phba->hbalock);
6861 		return;
6862 	}
6863 
6864 	/* Mbox cmd <mbxCommand> timeout */
6865 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6866 			"0310 Mailbox command x%x timeout Data: x%x x%x x%p\n",
6867 			mb->mbxCommand,
6868 			phba->pport->port_state,
6869 			phba->sli.sli_flag,
6870 			phba->sli.mbox_active);
6871 	spin_unlock_irq(&phba->hbalock);
6872 
6873 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
6874 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
6875 	 * it to fail all outstanding SCSI IO.
6876 	 */
6877 	spin_lock_irq(&phba->pport->work_port_lock);
6878 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
6879 	spin_unlock_irq(&phba->pport->work_port_lock);
6880 	spin_lock_irq(&phba->hbalock);
6881 	phba->link_state = LPFC_LINK_UNKNOWN;
6882 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
6883 	spin_unlock_irq(&phba->hbalock);
6884 
6885 	lpfc_sli_abort_fcp_rings(phba);
6886 
6887 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6888 			"0345 Resetting board due to mailbox timeout\n");
6889 
6890 	/* Reset the HBA device */
6891 	lpfc_reset_hba(phba);
6892 }
6893 
6894 /**
6895  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
6896  * @phba: Pointer to HBA context object.
6897  * @pmbox: Pointer to mailbox object.
6898  * @flag: Flag indicating how the mailbox need to be processed.
6899  *
6900  * This function is called by discovery code and HBA management code
6901  * to submit a mailbox command to firmware with SLI-3 interface spec. This
6902  * function gets the hbalock to protect the data structures.
6903  * The mailbox command can be submitted in polling mode, in which case
6904  * this function will wait in a polling loop for the completion of the
6905  * mailbox.
6906  * If the mailbox is submitted in no_wait mode (not polling) the
6907  * function will submit the command and returns immediately without waiting
6908  * for the mailbox completion. The no_wait is supported only when HBA
6909  * is in SLI2/SLI3 mode - interrupts are enabled.
6910  * The SLI interface allows only one mailbox pending at a time. If the
6911  * mailbox is issued in polling mode and there is already a mailbox
6912  * pending, then the function will return an error. If the mailbox is issued
6913  * in NO_WAIT mode and there is a mailbox pending already, the function
6914  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
6915  * The sli layer owns the mailbox object until the completion of mailbox
6916  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
6917  * return codes the caller owns the mailbox command after the return of
6918  * the function.
6919  **/
6920 static int
6921 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
6922 		       uint32_t flag)
6923 {
6924 	MAILBOX_t *mbx;
6925 	struct lpfc_sli *psli = &phba->sli;
6926 	uint32_t status, evtctr;
6927 	uint32_t ha_copy, hc_copy;
6928 	int i;
6929 	unsigned long timeout;
6930 	unsigned long drvr_flag = 0;
6931 	uint32_t word0, ldata;
6932 	void __iomem *to_slim;
6933 	int processing_queue = 0;
6934 
6935 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
6936 	if (!pmbox) {
6937 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
6938 		/* processing mbox queue from intr_handler */
6939 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
6940 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6941 			return MBX_SUCCESS;
6942 		}
6943 		processing_queue = 1;
6944 		pmbox = lpfc_mbox_get(phba);
6945 		if (!pmbox) {
6946 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6947 			return MBX_SUCCESS;
6948 		}
6949 	}
6950 
6951 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
6952 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
6953 		if(!pmbox->vport) {
6954 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6955 			lpfc_printf_log(phba, KERN_ERR,
6956 					LOG_MBOX | LOG_VPORT,
6957 					"1806 Mbox x%x failed. No vport\n",
6958 					pmbox->u.mb.mbxCommand);
6959 			dump_stack();
6960 			goto out_not_finished;
6961 		}
6962 	}
6963 
6964 	/* If the PCI channel is in offline state, do not post mbox. */
6965 	if (unlikely(pci_channel_offline(phba->pcidev))) {
6966 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6967 		goto out_not_finished;
6968 	}
6969 
6970 	/* If HBA has a deferred error attention, fail the iocb. */
6971 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
6972 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6973 		goto out_not_finished;
6974 	}
6975 
6976 	psli = &phba->sli;
6977 
6978 	mbx = &pmbox->u.mb;
6979 	status = MBX_SUCCESS;
6980 
6981 	if (phba->link_state == LPFC_HBA_ERROR) {
6982 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6983 
6984 		/* Mbox command <mbxCommand> cannot issue */
6985 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6986 				"(%d):0311 Mailbox command x%x cannot "
6987 				"issue Data: x%x x%x\n",
6988 				pmbox->vport ? pmbox->vport->vpi : 0,
6989 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
6990 		goto out_not_finished;
6991 	}
6992 
6993 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
6994 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
6995 			!(hc_copy & HC_MBINT_ENA)) {
6996 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6997 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6998 				"(%d):2528 Mailbox command x%x cannot "
6999 				"issue Data: x%x x%x\n",
7000 				pmbox->vport ? pmbox->vport->vpi : 0,
7001 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
7002 			goto out_not_finished;
7003 		}
7004 	}
7005 
7006 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
7007 		/* Polling for a mbox command when another one is already active
7008 		 * is not allowed in SLI. Also, the driver must have established
7009 		 * SLI2 mode to queue and process multiple mbox commands.
7010 		 */
7011 
7012 		if (flag & MBX_POLL) {
7013 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7014 
7015 			/* Mbox command <mbxCommand> cannot issue */
7016 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7017 					"(%d):2529 Mailbox command x%x "
7018 					"cannot issue Data: x%x x%x\n",
7019 					pmbox->vport ? pmbox->vport->vpi : 0,
7020 					pmbox->u.mb.mbxCommand,
7021 					psli->sli_flag, flag);
7022 			goto out_not_finished;
7023 		}
7024 
7025 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
7026 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7027 			/* Mbox command <mbxCommand> cannot issue */
7028 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7029 					"(%d):2530 Mailbox command x%x "
7030 					"cannot issue Data: x%x x%x\n",
7031 					pmbox->vport ? pmbox->vport->vpi : 0,
7032 					pmbox->u.mb.mbxCommand,
7033 					psli->sli_flag, flag);
7034 			goto out_not_finished;
7035 		}
7036 
7037 		/* Another mailbox command is still being processed, queue this
7038 		 * command to be processed later.
7039 		 */
7040 		lpfc_mbox_put(phba, pmbox);
7041 
7042 		/* Mbox cmd issue - BUSY */
7043 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7044 				"(%d):0308 Mbox cmd issue - BUSY Data: "
7045 				"x%x x%x x%x x%x\n",
7046 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
7047 				mbx->mbxCommand, phba->pport->port_state,
7048 				psli->sli_flag, flag);
7049 
7050 		psli->slistat.mbox_busy++;
7051 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7052 
7053 		if (pmbox->vport) {
7054 			lpfc_debugfs_disc_trc(pmbox->vport,
7055 				LPFC_DISC_TRC_MBOX_VPORT,
7056 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
7057 				(uint32_t)mbx->mbxCommand,
7058 				mbx->un.varWords[0], mbx->un.varWords[1]);
7059 		}
7060 		else {
7061 			lpfc_debugfs_disc_trc(phba->pport,
7062 				LPFC_DISC_TRC_MBOX,
7063 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
7064 				(uint32_t)mbx->mbxCommand,
7065 				mbx->un.varWords[0], mbx->un.varWords[1]);
7066 		}
7067 
7068 		return MBX_BUSY;
7069 	}
7070 
7071 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7072 
7073 	/* If we are not polling, we MUST be in SLI2 mode */
7074 	if (flag != MBX_POLL) {
7075 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
7076 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
7077 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7078 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7079 			/* Mbox command <mbxCommand> cannot issue */
7080 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7081 					"(%d):2531 Mailbox command x%x "
7082 					"cannot issue Data: x%x x%x\n",
7083 					pmbox->vport ? pmbox->vport->vpi : 0,
7084 					pmbox->u.mb.mbxCommand,
7085 					psli->sli_flag, flag);
7086 			goto out_not_finished;
7087 		}
7088 		/* timeout active mbox command */
7089 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
7090 					   1000);
7091 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
7092 	}
7093 
7094 	/* Mailbox cmd <cmd> issue */
7095 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7096 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
7097 			"x%x\n",
7098 			pmbox->vport ? pmbox->vport->vpi : 0,
7099 			mbx->mbxCommand, phba->pport->port_state,
7100 			psli->sli_flag, flag);
7101 
7102 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
7103 		if (pmbox->vport) {
7104 			lpfc_debugfs_disc_trc(pmbox->vport,
7105 				LPFC_DISC_TRC_MBOX_VPORT,
7106 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
7107 				(uint32_t)mbx->mbxCommand,
7108 				mbx->un.varWords[0], mbx->un.varWords[1]);
7109 		}
7110 		else {
7111 			lpfc_debugfs_disc_trc(phba->pport,
7112 				LPFC_DISC_TRC_MBOX,
7113 				"MBOX Send:       cmd:x%x mb:x%x x%x",
7114 				(uint32_t)mbx->mbxCommand,
7115 				mbx->un.varWords[0], mbx->un.varWords[1]);
7116 		}
7117 	}
7118 
7119 	psli->slistat.mbox_cmd++;
7120 	evtctr = psli->slistat.mbox_event;
7121 
7122 	/* next set own bit for the adapter and copy over command word */
7123 	mbx->mbxOwner = OWN_CHIP;
7124 
7125 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7126 		/* Populate mbox extension offset word. */
7127 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
7128 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
7129 				= (uint8_t *)phba->mbox_ext
7130 				  - (uint8_t *)phba->mbox;
7131 		}
7132 
7133 		/* Copy the mailbox extension data */
7134 		if (pmbox->in_ext_byte_len && pmbox->context2) {
7135 			lpfc_sli_pcimem_bcopy(pmbox->context2,
7136 				(uint8_t *)phba->mbox_ext,
7137 				pmbox->in_ext_byte_len);
7138 		}
7139 		/* Copy command data to host SLIM area */
7140 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
7141 	} else {
7142 		/* Populate mbox extension offset word. */
7143 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
7144 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
7145 				= MAILBOX_HBA_EXT_OFFSET;
7146 
7147 		/* Copy the mailbox extension data */
7148 		if (pmbox->in_ext_byte_len && pmbox->context2) {
7149 			lpfc_memcpy_to_slim(phba->MBslimaddr +
7150 				MAILBOX_HBA_EXT_OFFSET,
7151 				pmbox->context2, pmbox->in_ext_byte_len);
7152 
7153 		}
7154 		if (mbx->mbxCommand == MBX_CONFIG_PORT) {
7155 			/* copy command data into host mbox for cmpl */
7156 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
7157 		}
7158 
7159 		/* First copy mbox command data to HBA SLIM, skip past first
7160 		   word */
7161 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
7162 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
7163 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
7164 
7165 		/* Next copy over first word, with mbxOwner set */
7166 		ldata = *((uint32_t *)mbx);
7167 		to_slim = phba->MBslimaddr;
7168 		writel(ldata, to_slim);
7169 		readl(to_slim); /* flush */
7170 
7171 		if (mbx->mbxCommand == MBX_CONFIG_PORT) {
7172 			/* switch over to host mailbox */
7173 			psli->sli_flag |= LPFC_SLI_ACTIVE;
7174 		}
7175 	}
7176 
7177 	wmb();
7178 
7179 	switch (flag) {
7180 	case MBX_NOWAIT:
7181 		/* Set up reference to mailbox command */
7182 		psli->mbox_active = pmbox;
7183 		/* Interrupt board to do it */
7184 		writel(CA_MBATT, phba->CAregaddr);
7185 		readl(phba->CAregaddr); /* flush */
7186 		/* Don't wait for it to finish, just return */
7187 		break;
7188 
7189 	case MBX_POLL:
7190 		/* Set up null reference to mailbox command */
7191 		psli->mbox_active = NULL;
7192 		/* Interrupt board to do it */
7193 		writel(CA_MBATT, phba->CAregaddr);
7194 		readl(phba->CAregaddr); /* flush */
7195 
7196 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7197 			/* First read mbox status word */
7198 			word0 = *((uint32_t *)phba->mbox);
7199 			word0 = le32_to_cpu(word0);
7200 		} else {
7201 			/* First read mbox status word */
7202 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
7203 				spin_unlock_irqrestore(&phba->hbalock,
7204 						       drvr_flag);
7205 				goto out_not_finished;
7206 			}
7207 		}
7208 
7209 		/* Read the HBA Host Attention Register */
7210 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
7211 			spin_unlock_irqrestore(&phba->hbalock,
7212 						       drvr_flag);
7213 			goto out_not_finished;
7214 		}
7215 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
7216 							1000) + jiffies;
7217 		i = 0;
7218 		/* Wait for command to complete */
7219 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
7220 		       (!(ha_copy & HA_MBATT) &&
7221 			(phba->link_state > LPFC_WARM_START))) {
7222 			if (time_after(jiffies, timeout)) {
7223 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7224 				spin_unlock_irqrestore(&phba->hbalock,
7225 						       drvr_flag);
7226 				goto out_not_finished;
7227 			}
7228 
7229 			/* Check if we took a mbox interrupt while we were
7230 			   polling */
7231 			if (((word0 & OWN_CHIP) != OWN_CHIP)
7232 			    && (evtctr != psli->slistat.mbox_event))
7233 				break;
7234 
7235 			if (i++ > 10) {
7236 				spin_unlock_irqrestore(&phba->hbalock,
7237 						       drvr_flag);
7238 				msleep(1);
7239 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
7240 			}
7241 
7242 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7243 				/* First copy command data */
7244 				word0 = *((uint32_t *)phba->mbox);
7245 				word0 = le32_to_cpu(word0);
7246 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
7247 					MAILBOX_t *slimmb;
7248 					uint32_t slimword0;
7249 					/* Check real SLIM for any errors */
7250 					slimword0 = readl(phba->MBslimaddr);
7251 					slimmb = (MAILBOX_t *) & slimword0;
7252 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
7253 					    && slimmb->mbxStatus) {
7254 						psli->sli_flag &=
7255 						    ~LPFC_SLI_ACTIVE;
7256 						word0 = slimword0;
7257 					}
7258 				}
7259 			} else {
7260 				/* First copy command data */
7261 				word0 = readl(phba->MBslimaddr);
7262 			}
7263 			/* Read the HBA Host Attention Register */
7264 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
7265 				spin_unlock_irqrestore(&phba->hbalock,
7266 						       drvr_flag);
7267 				goto out_not_finished;
7268 			}
7269 		}
7270 
7271 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7272 			/* copy results back to user */
7273 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx, MAILBOX_CMD_SIZE);
7274 			/* Copy the mailbox extension data */
7275 			if (pmbox->out_ext_byte_len && pmbox->context2) {
7276 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
7277 						      pmbox->context2,
7278 						      pmbox->out_ext_byte_len);
7279 			}
7280 		} else {
7281 			/* First copy command data */
7282 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
7283 							MAILBOX_CMD_SIZE);
7284 			/* Copy the mailbox extension data */
7285 			if (pmbox->out_ext_byte_len && pmbox->context2) {
7286 				lpfc_memcpy_from_slim(pmbox->context2,
7287 					phba->MBslimaddr +
7288 					MAILBOX_HBA_EXT_OFFSET,
7289 					pmbox->out_ext_byte_len);
7290 			}
7291 		}
7292 
7293 		writel(HA_MBATT, phba->HAregaddr);
7294 		readl(phba->HAregaddr); /* flush */
7295 
7296 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7297 		status = mbx->mbxStatus;
7298 	}
7299 
7300 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7301 	return status;
7302 
7303 out_not_finished:
7304 	if (processing_queue) {
7305 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
7306 		lpfc_mbox_cmpl_put(phba, pmbox);
7307 	}
7308 	return MBX_NOT_FINISHED;
7309 }
7310 
7311 /**
7312  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
7313  * @phba: Pointer to HBA context object.
7314  *
7315  * The function blocks the posting of SLI4 asynchronous mailbox commands from
7316  * the driver internal pending mailbox queue. It will then try to wait out the
7317  * possible outstanding mailbox command before return.
7318  *
7319  * Returns:
7320  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
7321  * 	the outstanding mailbox command timed out.
7322  **/
7323 static int
7324 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
7325 {
7326 	struct lpfc_sli *psli = &phba->sli;
7327 	int rc = 0;
7328 	unsigned long timeout = 0;
7329 
7330 	/* Mark the asynchronous mailbox command posting as blocked */
7331 	spin_lock_irq(&phba->hbalock);
7332 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
7333 	/* Determine how long we might wait for the active mailbox
7334 	 * command to be gracefully completed by firmware.
7335 	 */
7336 	if (phba->sli.mbox_active)
7337 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
7338 						phba->sli.mbox_active) *
7339 						1000) + jiffies;
7340 	spin_unlock_irq(&phba->hbalock);
7341 
7342 	/* Make sure the mailbox is really active */
7343 	if (timeout)
7344 		lpfc_sli4_process_missed_mbox_completions(phba);
7345 
7346 	/* Wait for the outstnading mailbox command to complete */
7347 	while (phba->sli.mbox_active) {
7348 		/* Check active mailbox complete status every 2ms */
7349 		msleep(2);
7350 		if (time_after(jiffies, timeout)) {
7351 			/* Timeout, marked the outstanding cmd not complete */
7352 			rc = 1;
7353 			break;
7354 		}
7355 	}
7356 
7357 	/* Can not cleanly block async mailbox command, fails it */
7358 	if (rc) {
7359 		spin_lock_irq(&phba->hbalock);
7360 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7361 		spin_unlock_irq(&phba->hbalock);
7362 	}
7363 	return rc;
7364 }
7365 
7366 /**
7367  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
7368  * @phba: Pointer to HBA context object.
7369  *
7370  * The function unblocks and resume posting of SLI4 asynchronous mailbox
7371  * commands from the driver internal pending mailbox queue. It makes sure
7372  * that there is no outstanding mailbox command before resuming posting
7373  * asynchronous mailbox commands. If, for any reason, there is outstanding
7374  * mailbox command, it will try to wait it out before resuming asynchronous
7375  * mailbox command posting.
7376  **/
7377 static void
7378 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
7379 {
7380 	struct lpfc_sli *psli = &phba->sli;
7381 
7382 	spin_lock_irq(&phba->hbalock);
7383 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
7384 		/* Asynchronous mailbox posting is not blocked, do nothing */
7385 		spin_unlock_irq(&phba->hbalock);
7386 		return;
7387 	}
7388 
7389 	/* Outstanding synchronous mailbox command is guaranteed to be done,
7390 	 * successful or timeout, after timing-out the outstanding mailbox
7391 	 * command shall always be removed, so just unblock posting async
7392 	 * mailbox command and resume
7393 	 */
7394 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7395 	spin_unlock_irq(&phba->hbalock);
7396 
7397 	/* wake up worker thread to post asynchronlous mailbox command */
7398 	lpfc_worker_wake_up(phba);
7399 }
7400 
7401 /**
7402  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
7403  * @phba: Pointer to HBA context object.
7404  * @mboxq: Pointer to mailbox object.
7405  *
7406  * The function waits for the bootstrap mailbox register ready bit from
7407  * port for twice the regular mailbox command timeout value.
7408  *
7409  *      0 - no timeout on waiting for bootstrap mailbox register ready.
7410  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
7411  **/
7412 static int
7413 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
7414 {
7415 	uint32_t db_ready;
7416 	unsigned long timeout;
7417 	struct lpfc_register bmbx_reg;
7418 
7419 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
7420 				   * 1000) + jiffies;
7421 
7422 	do {
7423 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
7424 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
7425 		if (!db_ready)
7426 			msleep(2);
7427 
7428 		if (time_after(jiffies, timeout))
7429 			return MBXERR_ERROR;
7430 	} while (!db_ready);
7431 
7432 	return 0;
7433 }
7434 
7435 /**
7436  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
7437  * @phba: Pointer to HBA context object.
7438  * @mboxq: Pointer to mailbox object.
7439  *
7440  * The function posts a mailbox to the port.  The mailbox is expected
7441  * to be comletely filled in and ready for the port to operate on it.
7442  * This routine executes a synchronous completion operation on the
7443  * mailbox by polling for its completion.
7444  *
7445  * The caller must not be holding any locks when calling this routine.
7446  *
7447  * Returns:
7448  *	MBX_SUCCESS - mailbox posted successfully
7449  *	Any of the MBX error values.
7450  **/
7451 static int
7452 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
7453 {
7454 	int rc = MBX_SUCCESS;
7455 	unsigned long iflag;
7456 	uint32_t mcqe_status;
7457 	uint32_t mbx_cmnd;
7458 	struct lpfc_sli *psli = &phba->sli;
7459 	struct lpfc_mqe *mb = &mboxq->u.mqe;
7460 	struct lpfc_bmbx_create *mbox_rgn;
7461 	struct dma_address *dma_address;
7462 
7463 	/*
7464 	 * Only one mailbox can be active to the bootstrap mailbox region
7465 	 * at a time and there is no queueing provided.
7466 	 */
7467 	spin_lock_irqsave(&phba->hbalock, iflag);
7468 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
7469 		spin_unlock_irqrestore(&phba->hbalock, iflag);
7470 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7471 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
7472 				"cannot issue Data: x%x x%x\n",
7473 				mboxq->vport ? mboxq->vport->vpi : 0,
7474 				mboxq->u.mb.mbxCommand,
7475 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7476 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7477 				psli->sli_flag, MBX_POLL);
7478 		return MBXERR_ERROR;
7479 	}
7480 	/* The server grabs the token and owns it until release */
7481 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7482 	phba->sli.mbox_active = mboxq;
7483 	spin_unlock_irqrestore(&phba->hbalock, iflag);
7484 
7485 	/* wait for bootstrap mbox register for readyness */
7486 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7487 	if (rc)
7488 		goto exit;
7489 
7490 	/*
7491 	 * Initialize the bootstrap memory region to avoid stale data areas
7492 	 * in the mailbox post.  Then copy the caller's mailbox contents to
7493 	 * the bmbx mailbox region.
7494 	 */
7495 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
7496 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
7497 	lpfc_sli_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
7498 			      sizeof(struct lpfc_mqe));
7499 
7500 	/* Post the high mailbox dma address to the port and wait for ready. */
7501 	dma_address = &phba->sli4_hba.bmbx.dma_address;
7502 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
7503 
7504 	/* wait for bootstrap mbox register for hi-address write done */
7505 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7506 	if (rc)
7507 		goto exit;
7508 
7509 	/* Post the low mailbox dma address to the port. */
7510 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
7511 
7512 	/* wait for bootstrap mbox register for low address write done */
7513 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7514 	if (rc)
7515 		goto exit;
7516 
7517 	/*
7518 	 * Read the CQ to ensure the mailbox has completed.
7519 	 * If so, update the mailbox status so that the upper layers
7520 	 * can complete the request normally.
7521 	 */
7522 	lpfc_sli_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
7523 			      sizeof(struct lpfc_mqe));
7524 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
7525 	lpfc_sli_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
7526 			      sizeof(struct lpfc_mcqe));
7527 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
7528 	/*
7529 	 * When the CQE status indicates a failure and the mailbox status
7530 	 * indicates success then copy the CQE status into the mailbox status
7531 	 * (and prefix it with x4000).
7532 	 */
7533 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
7534 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
7535 			bf_set(lpfc_mqe_status, mb,
7536 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
7537 		rc = MBXERR_ERROR;
7538 	} else
7539 		lpfc_sli4_swap_str(phba, mboxq);
7540 
7541 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7542 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
7543 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
7544 			" x%x x%x CQ: x%x x%x x%x x%x\n",
7545 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
7546 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7547 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7548 			bf_get(lpfc_mqe_status, mb),
7549 			mb->un.mb_words[0], mb->un.mb_words[1],
7550 			mb->un.mb_words[2], mb->un.mb_words[3],
7551 			mb->un.mb_words[4], mb->un.mb_words[5],
7552 			mb->un.mb_words[6], mb->un.mb_words[7],
7553 			mb->un.mb_words[8], mb->un.mb_words[9],
7554 			mb->un.mb_words[10], mb->un.mb_words[11],
7555 			mb->un.mb_words[12], mboxq->mcqe.word0,
7556 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
7557 			mboxq->mcqe.trailer);
7558 exit:
7559 	/* We are holding the token, no needed for lock when release */
7560 	spin_lock_irqsave(&phba->hbalock, iflag);
7561 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7562 	phba->sli.mbox_active = NULL;
7563 	spin_unlock_irqrestore(&phba->hbalock, iflag);
7564 	return rc;
7565 }
7566 
7567 /**
7568  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
7569  * @phba: Pointer to HBA context object.
7570  * @pmbox: Pointer to mailbox object.
7571  * @flag: Flag indicating how the mailbox need to be processed.
7572  *
7573  * This function is called by discovery code and HBA management code to submit
7574  * a mailbox command to firmware with SLI-4 interface spec.
7575  *
7576  * Return codes the caller owns the mailbox command after the return of the
7577  * function.
7578  **/
7579 static int
7580 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
7581 		       uint32_t flag)
7582 {
7583 	struct lpfc_sli *psli = &phba->sli;
7584 	unsigned long iflags;
7585 	int rc;
7586 
7587 	/* dump from issue mailbox command if setup */
7588 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
7589 
7590 	rc = lpfc_mbox_dev_check(phba);
7591 	if (unlikely(rc)) {
7592 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7593 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
7594 				"cannot issue Data: x%x x%x\n",
7595 				mboxq->vport ? mboxq->vport->vpi : 0,
7596 				mboxq->u.mb.mbxCommand,
7597 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7598 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7599 				psli->sli_flag, flag);
7600 		goto out_not_finished;
7601 	}
7602 
7603 	/* Detect polling mode and jump to a handler */
7604 	if (!phba->sli4_hba.intr_enable) {
7605 		if (flag == MBX_POLL)
7606 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
7607 		else
7608 			rc = -EIO;
7609 		if (rc != MBX_SUCCESS)
7610 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7611 					"(%d):2541 Mailbox command x%x "
7612 					"(x%x/x%x) failure: "
7613 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
7614 					"Data: x%x x%x\n,",
7615 					mboxq->vport ? mboxq->vport->vpi : 0,
7616 					mboxq->u.mb.mbxCommand,
7617 					lpfc_sli_config_mbox_subsys_get(phba,
7618 									mboxq),
7619 					lpfc_sli_config_mbox_opcode_get(phba,
7620 									mboxq),
7621 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
7622 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
7623 					bf_get(lpfc_mcqe_ext_status,
7624 					       &mboxq->mcqe),
7625 					psli->sli_flag, flag);
7626 		return rc;
7627 	} else if (flag == MBX_POLL) {
7628 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7629 				"(%d):2542 Try to issue mailbox command "
7630 				"x%x (x%x/x%x) synchronously ahead of async"
7631 				"mailbox command queue: x%x x%x\n",
7632 				mboxq->vport ? mboxq->vport->vpi : 0,
7633 				mboxq->u.mb.mbxCommand,
7634 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7635 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7636 				psli->sli_flag, flag);
7637 		/* Try to block the asynchronous mailbox posting */
7638 		rc = lpfc_sli4_async_mbox_block(phba);
7639 		if (!rc) {
7640 			/* Successfully blocked, now issue sync mbox cmd */
7641 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
7642 			if (rc != MBX_SUCCESS)
7643 				lpfc_printf_log(phba, KERN_WARNING,
7644 					LOG_MBOX | LOG_SLI,
7645 					"(%d):2597 Sync Mailbox command "
7646 					"x%x (x%x/x%x) failure: "
7647 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
7648 					"Data: x%x x%x\n,",
7649 					mboxq->vport ? mboxq->vport->vpi : 0,
7650 					mboxq->u.mb.mbxCommand,
7651 					lpfc_sli_config_mbox_subsys_get(phba,
7652 									mboxq),
7653 					lpfc_sli_config_mbox_opcode_get(phba,
7654 									mboxq),
7655 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
7656 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
7657 					bf_get(lpfc_mcqe_ext_status,
7658 					       &mboxq->mcqe),
7659 					psli->sli_flag, flag);
7660 			/* Unblock the async mailbox posting afterward */
7661 			lpfc_sli4_async_mbox_unblock(phba);
7662 		}
7663 		return rc;
7664 	}
7665 
7666 	/* Now, interrupt mode asynchrous mailbox command */
7667 	rc = lpfc_mbox_cmd_check(phba, mboxq);
7668 	if (rc) {
7669 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7670 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
7671 				"cannot issue Data: x%x x%x\n",
7672 				mboxq->vport ? mboxq->vport->vpi : 0,
7673 				mboxq->u.mb.mbxCommand,
7674 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7675 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7676 				psli->sli_flag, flag);
7677 		goto out_not_finished;
7678 	}
7679 
7680 	/* Put the mailbox command to the driver internal FIFO */
7681 	psli->slistat.mbox_busy++;
7682 	spin_lock_irqsave(&phba->hbalock, iflags);
7683 	lpfc_mbox_put(phba, mboxq);
7684 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7685 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7686 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
7687 			"x%x (x%x/x%x) x%x x%x x%x\n",
7688 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
7689 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7690 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7691 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7692 			phba->pport->port_state,
7693 			psli->sli_flag, MBX_NOWAIT);
7694 	/* Wake up worker thread to transport mailbox command from head */
7695 	lpfc_worker_wake_up(phba);
7696 
7697 	return MBX_BUSY;
7698 
7699 out_not_finished:
7700 	return MBX_NOT_FINISHED;
7701 }
7702 
7703 /**
7704  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
7705  * @phba: Pointer to HBA context object.
7706  *
7707  * This function is called by worker thread to send a mailbox command to
7708  * SLI4 HBA firmware.
7709  *
7710  **/
7711 int
7712 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
7713 {
7714 	struct lpfc_sli *psli = &phba->sli;
7715 	LPFC_MBOXQ_t *mboxq;
7716 	int rc = MBX_SUCCESS;
7717 	unsigned long iflags;
7718 	struct lpfc_mqe *mqe;
7719 	uint32_t mbx_cmnd;
7720 
7721 	/* Check interrupt mode before post async mailbox command */
7722 	if (unlikely(!phba->sli4_hba.intr_enable))
7723 		return MBX_NOT_FINISHED;
7724 
7725 	/* Check for mailbox command service token */
7726 	spin_lock_irqsave(&phba->hbalock, iflags);
7727 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
7728 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7729 		return MBX_NOT_FINISHED;
7730 	}
7731 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
7732 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7733 		return MBX_NOT_FINISHED;
7734 	}
7735 	if (unlikely(phba->sli.mbox_active)) {
7736 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7737 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7738 				"0384 There is pending active mailbox cmd\n");
7739 		return MBX_NOT_FINISHED;
7740 	}
7741 	/* Take the mailbox command service token */
7742 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7743 
7744 	/* Get the next mailbox command from head of queue */
7745 	mboxq = lpfc_mbox_get(phba);
7746 
7747 	/* If no more mailbox command waiting for post, we're done */
7748 	if (!mboxq) {
7749 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7750 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7751 		return MBX_SUCCESS;
7752 	}
7753 	phba->sli.mbox_active = mboxq;
7754 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7755 
7756 	/* Check device readiness for posting mailbox command */
7757 	rc = lpfc_mbox_dev_check(phba);
7758 	if (unlikely(rc))
7759 		/* Driver clean routine will clean up pending mailbox */
7760 		goto out_not_finished;
7761 
7762 	/* Prepare the mbox command to be posted */
7763 	mqe = &mboxq->u.mqe;
7764 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
7765 
7766 	/* Start timer for the mbox_tmo and log some mailbox post messages */
7767 	mod_timer(&psli->mbox_tmo, (jiffies +
7768 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
7769 
7770 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7771 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
7772 			"x%x x%x\n",
7773 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
7774 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7775 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7776 			phba->pport->port_state, psli->sli_flag);
7777 
7778 	if (mbx_cmnd != MBX_HEARTBEAT) {
7779 		if (mboxq->vport) {
7780 			lpfc_debugfs_disc_trc(mboxq->vport,
7781 				LPFC_DISC_TRC_MBOX_VPORT,
7782 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
7783 				mbx_cmnd, mqe->un.mb_words[0],
7784 				mqe->un.mb_words[1]);
7785 		} else {
7786 			lpfc_debugfs_disc_trc(phba->pport,
7787 				LPFC_DISC_TRC_MBOX,
7788 				"MBOX Send: cmd:x%x mb:x%x x%x",
7789 				mbx_cmnd, mqe->un.mb_words[0],
7790 				mqe->un.mb_words[1]);
7791 		}
7792 	}
7793 	psli->slistat.mbox_cmd++;
7794 
7795 	/* Post the mailbox command to the port */
7796 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
7797 	if (rc != MBX_SUCCESS) {
7798 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7799 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
7800 				"cannot issue Data: x%x x%x\n",
7801 				mboxq->vport ? mboxq->vport->vpi : 0,
7802 				mboxq->u.mb.mbxCommand,
7803 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7804 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7805 				psli->sli_flag, MBX_NOWAIT);
7806 		goto out_not_finished;
7807 	}
7808 
7809 	return rc;
7810 
7811 out_not_finished:
7812 	spin_lock_irqsave(&phba->hbalock, iflags);
7813 	if (phba->sli.mbox_active) {
7814 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
7815 		__lpfc_mbox_cmpl_put(phba, mboxq);
7816 		/* Release the token */
7817 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7818 		phba->sli.mbox_active = NULL;
7819 	}
7820 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7821 
7822 	return MBX_NOT_FINISHED;
7823 }
7824 
7825 /**
7826  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
7827  * @phba: Pointer to HBA context object.
7828  * @pmbox: Pointer to mailbox object.
7829  * @flag: Flag indicating how the mailbox need to be processed.
7830  *
7831  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
7832  * the API jump table function pointer from the lpfc_hba struct.
7833  *
7834  * Return codes the caller owns the mailbox command after the return of the
7835  * function.
7836  **/
7837 int
7838 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
7839 {
7840 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
7841 }
7842 
7843 /**
7844  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
7845  * @phba: The hba struct for which this call is being executed.
7846  * @dev_grp: The HBA PCI-Device group number.
7847  *
7848  * This routine sets up the mbox interface API function jump table in @phba
7849  * struct.
7850  * Returns: 0 - success, -ENODEV - failure.
7851  **/
7852 int
7853 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7854 {
7855 
7856 	switch (dev_grp) {
7857 	case LPFC_PCI_DEV_LP:
7858 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
7859 		phba->lpfc_sli_handle_slow_ring_event =
7860 				lpfc_sli_handle_slow_ring_event_s3;
7861 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
7862 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
7863 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
7864 		break;
7865 	case LPFC_PCI_DEV_OC:
7866 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
7867 		phba->lpfc_sli_handle_slow_ring_event =
7868 				lpfc_sli_handle_slow_ring_event_s4;
7869 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
7870 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
7871 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
7872 		break;
7873 	default:
7874 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7875 				"1420 Invalid HBA PCI-device group: 0x%x\n",
7876 				dev_grp);
7877 		return -ENODEV;
7878 		break;
7879 	}
7880 	return 0;
7881 }
7882 
7883 /**
7884  * __lpfc_sli_ringtx_put - Add an iocb to the txq
7885  * @phba: Pointer to HBA context object.
7886  * @pring: Pointer to driver SLI ring object.
7887  * @piocb: Pointer to address of newly added command iocb.
7888  *
7889  * This function is called with hbalock held to add a command
7890  * iocb to the txq when SLI layer cannot submit the command iocb
7891  * to the ring.
7892  **/
7893 void
7894 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
7895 		    struct lpfc_iocbq *piocb)
7896 {
7897 	lockdep_assert_held(&phba->hbalock);
7898 	/* Insert the caller's iocb in the txq tail for later processing. */
7899 	list_add_tail(&piocb->list, &pring->txq);
7900 }
7901 
7902 /**
7903  * lpfc_sli_next_iocb - Get the next iocb in the txq
7904  * @phba: Pointer to HBA context object.
7905  * @pring: Pointer to driver SLI ring object.
7906  * @piocb: Pointer to address of newly added command iocb.
7907  *
7908  * This function is called with hbalock held before a new
7909  * iocb is submitted to the firmware. This function checks
7910  * txq to flush the iocbs in txq to Firmware before
7911  * submitting new iocbs to the Firmware.
7912  * If there are iocbs in the txq which need to be submitted
7913  * to firmware, lpfc_sli_next_iocb returns the first element
7914  * of the txq after dequeuing it from txq.
7915  * If there is no iocb in the txq then the function will return
7916  * *piocb and *piocb is set to NULL. Caller needs to check
7917  * *piocb to find if there are more commands in the txq.
7918  **/
7919 static struct lpfc_iocbq *
7920 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
7921 		   struct lpfc_iocbq **piocb)
7922 {
7923 	struct lpfc_iocbq * nextiocb;
7924 
7925 	lockdep_assert_held(&phba->hbalock);
7926 
7927 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
7928 	if (!nextiocb) {
7929 		nextiocb = *piocb;
7930 		*piocb = NULL;
7931 	}
7932 
7933 	return nextiocb;
7934 }
7935 
7936 /**
7937  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
7938  * @phba: Pointer to HBA context object.
7939  * @ring_number: SLI ring number to issue iocb on.
7940  * @piocb: Pointer to command iocb.
7941  * @flag: Flag indicating if this command can be put into txq.
7942  *
7943  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
7944  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
7945  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
7946  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
7947  * this function allows only iocbs for posting buffers. This function finds
7948  * next available slot in the command ring and posts the command to the
7949  * available slot and writes the port attention register to request HBA start
7950  * processing new iocb. If there is no slot available in the ring and
7951  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
7952  * the function returns IOCB_BUSY.
7953  *
7954  * This function is called with hbalock held. The function will return success
7955  * after it successfully submit the iocb to firmware or after adding to the
7956  * txq.
7957  **/
7958 static int
7959 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
7960 		    struct lpfc_iocbq *piocb, uint32_t flag)
7961 {
7962 	struct lpfc_iocbq *nextiocb;
7963 	IOCB_t *iocb;
7964 	struct lpfc_sli_ring *pring = &phba->sli.ring[ring_number];
7965 
7966 	lockdep_assert_held(&phba->hbalock);
7967 
7968 	if (piocb->iocb_cmpl && (!piocb->vport) &&
7969 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
7970 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
7971 		lpfc_printf_log(phba, KERN_ERR,
7972 				LOG_SLI | LOG_VPORT,
7973 				"1807 IOCB x%x failed. No vport\n",
7974 				piocb->iocb.ulpCommand);
7975 		dump_stack();
7976 		return IOCB_ERROR;
7977 	}
7978 
7979 
7980 	/* If the PCI channel is in offline state, do not post iocbs. */
7981 	if (unlikely(pci_channel_offline(phba->pcidev)))
7982 		return IOCB_ERROR;
7983 
7984 	/* If HBA has a deferred error attention, fail the iocb. */
7985 	if (unlikely(phba->hba_flag & DEFER_ERATT))
7986 		return IOCB_ERROR;
7987 
7988 	/*
7989 	 * We should never get an IOCB if we are in a < LINK_DOWN state
7990 	 */
7991 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
7992 		return IOCB_ERROR;
7993 
7994 	/*
7995 	 * Check to see if we are blocking IOCB processing because of a
7996 	 * outstanding event.
7997 	 */
7998 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
7999 		goto iocb_busy;
8000 
8001 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
8002 		/*
8003 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
8004 		 * can be issued if the link is not up.
8005 		 */
8006 		switch (piocb->iocb.ulpCommand) {
8007 		case CMD_GEN_REQUEST64_CR:
8008 		case CMD_GEN_REQUEST64_CX:
8009 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
8010 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
8011 					FC_RCTL_DD_UNSOL_CMD) ||
8012 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
8013 					MENLO_TRANSPORT_TYPE))
8014 
8015 				goto iocb_busy;
8016 			break;
8017 		case CMD_QUE_RING_BUF_CN:
8018 		case CMD_QUE_RING_BUF64_CN:
8019 			/*
8020 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
8021 			 * completion, iocb_cmpl MUST be 0.
8022 			 */
8023 			if (piocb->iocb_cmpl)
8024 				piocb->iocb_cmpl = NULL;
8025 			/*FALLTHROUGH*/
8026 		case CMD_CREATE_XRI_CR:
8027 		case CMD_CLOSE_XRI_CN:
8028 		case CMD_CLOSE_XRI_CX:
8029 			break;
8030 		default:
8031 			goto iocb_busy;
8032 		}
8033 
8034 	/*
8035 	 * For FCP commands, we must be in a state where we can process link
8036 	 * attention events.
8037 	 */
8038 	} else if (unlikely(pring->ringno == phba->sli.fcp_ring &&
8039 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
8040 		goto iocb_busy;
8041 	}
8042 
8043 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
8044 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
8045 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
8046 
8047 	if (iocb)
8048 		lpfc_sli_update_ring(phba, pring);
8049 	else
8050 		lpfc_sli_update_full_ring(phba, pring);
8051 
8052 	if (!piocb)
8053 		return IOCB_SUCCESS;
8054 
8055 	goto out_busy;
8056 
8057  iocb_busy:
8058 	pring->stats.iocb_cmd_delay++;
8059 
8060  out_busy:
8061 
8062 	if (!(flag & SLI_IOCB_RET_IOCB)) {
8063 		__lpfc_sli_ringtx_put(phba, pring, piocb);
8064 		return IOCB_SUCCESS;
8065 	}
8066 
8067 	return IOCB_BUSY;
8068 }
8069 
8070 /**
8071  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
8072  * @phba: Pointer to HBA context object.
8073  * @piocb: Pointer to command iocb.
8074  * @sglq: Pointer to the scatter gather queue object.
8075  *
8076  * This routine converts the bpl or bde that is in the IOCB
8077  * to a sgl list for the sli4 hardware. The physical address
8078  * of the bpl/bde is converted back to a virtual address.
8079  * If the IOCB contains a BPL then the list of BDE's is
8080  * converted to sli4_sge's. If the IOCB contains a single
8081  * BDE then it is converted to a single sli_sge.
8082  * The IOCB is still in cpu endianess so the contents of
8083  * the bpl can be used without byte swapping.
8084  *
8085  * Returns valid XRI = Success, NO_XRI = Failure.
8086 **/
8087 static uint16_t
8088 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
8089 		struct lpfc_sglq *sglq)
8090 {
8091 	uint16_t xritag = NO_XRI;
8092 	struct ulp_bde64 *bpl = NULL;
8093 	struct ulp_bde64 bde;
8094 	struct sli4_sge *sgl  = NULL;
8095 	struct lpfc_dmabuf *dmabuf;
8096 	IOCB_t *icmd;
8097 	int numBdes = 0;
8098 	int i = 0;
8099 	uint32_t offset = 0; /* accumulated offset in the sg request list */
8100 	int inbound = 0; /* number of sg reply entries inbound from firmware */
8101 
8102 	if (!piocbq || !sglq)
8103 		return xritag;
8104 
8105 	sgl  = (struct sli4_sge *)sglq->sgl;
8106 	icmd = &piocbq->iocb;
8107 	if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
8108 		return sglq->sli4_xritag;
8109 	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
8110 		numBdes = icmd->un.genreq64.bdl.bdeSize /
8111 				sizeof(struct ulp_bde64);
8112 		/* The addrHigh and addrLow fields within the IOCB
8113 		 * have not been byteswapped yet so there is no
8114 		 * need to swap them back.
8115 		 */
8116 		if (piocbq->context3)
8117 			dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
8118 		else
8119 			return xritag;
8120 
8121 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
8122 		if (!bpl)
8123 			return xritag;
8124 
8125 		for (i = 0; i < numBdes; i++) {
8126 			/* Should already be byte swapped. */
8127 			sgl->addr_hi = bpl->addrHigh;
8128 			sgl->addr_lo = bpl->addrLow;
8129 
8130 			sgl->word2 = le32_to_cpu(sgl->word2);
8131 			if ((i+1) == numBdes)
8132 				bf_set(lpfc_sli4_sge_last, sgl, 1);
8133 			else
8134 				bf_set(lpfc_sli4_sge_last, sgl, 0);
8135 			/* swap the size field back to the cpu so we
8136 			 * can assign it to the sgl.
8137 			 */
8138 			bde.tus.w = le32_to_cpu(bpl->tus.w);
8139 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
8140 			/* The offsets in the sgl need to be accumulated
8141 			 * separately for the request and reply lists.
8142 			 * The request is always first, the reply follows.
8143 			 */
8144 			if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
8145 				/* add up the reply sg entries */
8146 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
8147 					inbound++;
8148 				/* first inbound? reset the offset */
8149 				if (inbound == 1)
8150 					offset = 0;
8151 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
8152 				bf_set(lpfc_sli4_sge_type, sgl,
8153 					LPFC_SGE_TYPE_DATA);
8154 				offset += bde.tus.f.bdeSize;
8155 			}
8156 			sgl->word2 = cpu_to_le32(sgl->word2);
8157 			bpl++;
8158 			sgl++;
8159 		}
8160 	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
8161 			/* The addrHigh and addrLow fields of the BDE have not
8162 			 * been byteswapped yet so they need to be swapped
8163 			 * before putting them in the sgl.
8164 			 */
8165 			sgl->addr_hi =
8166 				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
8167 			sgl->addr_lo =
8168 				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
8169 			sgl->word2 = le32_to_cpu(sgl->word2);
8170 			bf_set(lpfc_sli4_sge_last, sgl, 1);
8171 			sgl->word2 = cpu_to_le32(sgl->word2);
8172 			sgl->sge_len =
8173 				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
8174 	}
8175 	return sglq->sli4_xritag;
8176 }
8177 
8178 /**
8179  * lpfc_sli_iocb2wqe - Convert the IOCB to a work queue entry.
8180  * @phba: Pointer to HBA context object.
8181  * @piocb: Pointer to command iocb.
8182  * @wqe: Pointer to the work queue entry.
8183  *
8184  * This routine converts the iocb command to its Work Queue Entry
8185  * equivalent. The wqe pointer should not have any fields set when
8186  * this routine is called because it will memcpy over them.
8187  * This routine does not set the CQ_ID or the WQEC bits in the
8188  * wqe.
8189  *
8190  * Returns: 0 = Success, IOCB_ERROR = Failure.
8191  **/
8192 static int
8193 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
8194 		union lpfc_wqe *wqe)
8195 {
8196 	uint32_t xmit_len = 0, total_len = 0;
8197 	uint8_t ct = 0;
8198 	uint32_t fip;
8199 	uint32_t abort_tag;
8200 	uint8_t command_type = ELS_COMMAND_NON_FIP;
8201 	uint8_t cmnd;
8202 	uint16_t xritag;
8203 	uint16_t abrt_iotag;
8204 	struct lpfc_iocbq *abrtiocbq;
8205 	struct ulp_bde64 *bpl = NULL;
8206 	uint32_t els_id = LPFC_ELS_ID_DEFAULT;
8207 	int numBdes, i;
8208 	struct ulp_bde64 bde;
8209 	struct lpfc_nodelist *ndlp;
8210 	uint32_t *pcmd;
8211 	uint32_t if_type;
8212 
8213 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
8214 	/* The fcp commands will set command type */
8215 	if (iocbq->iocb_flag &  LPFC_IO_FCP)
8216 		command_type = FCP_COMMAND;
8217 	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
8218 		command_type = ELS_COMMAND_FIP;
8219 	else
8220 		command_type = ELS_COMMAND_NON_FIP;
8221 
8222 	if (phba->fcp_embed_io)
8223 		memset(wqe, 0, sizeof(union lpfc_wqe128));
8224 	/* Some of the fields are in the right position already */
8225 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
8226 	wqe->generic.wqe_com.word7 = 0; /* The ct field has moved so reset */
8227 	wqe->generic.wqe_com.word10 = 0;
8228 
8229 	abort_tag = (uint32_t) iocbq->iotag;
8230 	xritag = iocbq->sli4_xritag;
8231 	/* words0-2 bpl convert bde */
8232 	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
8233 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
8234 				sizeof(struct ulp_bde64);
8235 		bpl  = (struct ulp_bde64 *)
8236 			((struct lpfc_dmabuf *)iocbq->context3)->virt;
8237 		if (!bpl)
8238 			return IOCB_ERROR;
8239 
8240 		/* Should already be byte swapped. */
8241 		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
8242 		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
8243 		/* swap the size field back to the cpu so we
8244 		 * can assign it to the sgl.
8245 		 */
8246 		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
8247 		xmit_len = wqe->generic.bde.tus.f.bdeSize;
8248 		total_len = 0;
8249 		for (i = 0; i < numBdes; i++) {
8250 			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
8251 			total_len += bde.tus.f.bdeSize;
8252 		}
8253 	} else
8254 		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
8255 
8256 	iocbq->iocb.ulpIoTag = iocbq->iotag;
8257 	cmnd = iocbq->iocb.ulpCommand;
8258 
8259 	switch (iocbq->iocb.ulpCommand) {
8260 	case CMD_ELS_REQUEST64_CR:
8261 		if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
8262 			ndlp = iocbq->context_un.ndlp;
8263 		else
8264 			ndlp = (struct lpfc_nodelist *)iocbq->context1;
8265 		if (!iocbq->iocb.ulpLe) {
8266 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8267 				"2007 Only Limited Edition cmd Format"
8268 				" supported 0x%x\n",
8269 				iocbq->iocb.ulpCommand);
8270 			return IOCB_ERROR;
8271 		}
8272 
8273 		wqe->els_req.payload_len = xmit_len;
8274 		/* Els_reguest64 has a TMO */
8275 		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
8276 			iocbq->iocb.ulpTimeout);
8277 		/* Need a VF for word 4 set the vf bit*/
8278 		bf_set(els_req64_vf, &wqe->els_req, 0);
8279 		/* And a VFID for word 12 */
8280 		bf_set(els_req64_vfid, &wqe->els_req, 0);
8281 		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
8282 		bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8283 		       iocbq->iocb.ulpContext);
8284 		bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
8285 		bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
8286 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
8287 		if (command_type == ELS_COMMAND_FIP)
8288 			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
8289 					>> LPFC_FIP_ELS_ID_SHIFT);
8290 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
8291 					iocbq->context2)->virt);
8292 		if_type = bf_get(lpfc_sli_intf_if_type,
8293 					&phba->sli4_hba.sli_intf);
8294 		if (if_type == LPFC_SLI_INTF_IF_TYPE_2) {
8295 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
8296 				*pcmd == ELS_CMD_SCR ||
8297 				*pcmd == ELS_CMD_FDISC ||
8298 				*pcmd == ELS_CMD_LOGO ||
8299 				*pcmd == ELS_CMD_PLOGI)) {
8300 				bf_set(els_req64_sp, &wqe->els_req, 1);
8301 				bf_set(els_req64_sid, &wqe->els_req,
8302 					iocbq->vport->fc_myDID);
8303 				if ((*pcmd == ELS_CMD_FLOGI) &&
8304 					!(phba->fc_topology ==
8305 						LPFC_TOPOLOGY_LOOP))
8306 					bf_set(els_req64_sid, &wqe->els_req, 0);
8307 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
8308 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8309 					phba->vpi_ids[iocbq->vport->vpi]);
8310 			} else if (pcmd && iocbq->context1) {
8311 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
8312 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8313 					phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8314 			}
8315 		}
8316 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
8317 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8318 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
8319 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
8320 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
8321 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
8322 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
8323 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
8324 		wqe->els_req.max_response_payload_len = total_len - xmit_len;
8325 		break;
8326 	case CMD_XMIT_SEQUENCE64_CX:
8327 		bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
8328 		       iocbq->iocb.un.ulpWord[3]);
8329 		bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
8330 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
8331 		/* The entire sequence is transmitted for this IOCB */
8332 		xmit_len = total_len;
8333 		cmnd = CMD_XMIT_SEQUENCE64_CR;
8334 		if (phba->link_flag & LS_LOOPBACK_MODE)
8335 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
8336 	case CMD_XMIT_SEQUENCE64_CR:
8337 		/* word3 iocb=io_tag32 wqe=reserved */
8338 		wqe->xmit_sequence.rsvd3 = 0;
8339 		/* word4 relative_offset memcpy */
8340 		/* word5 r_ctl/df_ctl memcpy */
8341 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
8342 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
8343 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
8344 		       LPFC_WQE_IOD_WRITE);
8345 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
8346 		       LPFC_WQE_LENLOC_WORD12);
8347 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
8348 		wqe->xmit_sequence.xmit_len = xmit_len;
8349 		command_type = OTHER_COMMAND;
8350 		break;
8351 	case CMD_XMIT_BCAST64_CN:
8352 		/* word3 iocb=iotag32 wqe=seq_payload_len */
8353 		wqe->xmit_bcast64.seq_payload_len = xmit_len;
8354 		/* word4 iocb=rsvd wqe=rsvd */
8355 		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
8356 		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
8357 		bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
8358 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8359 		bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
8360 		bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
8361 		bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
8362 		       LPFC_WQE_LENLOC_WORD3);
8363 		bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
8364 		break;
8365 	case CMD_FCP_IWRITE64_CR:
8366 		command_type = FCP_COMMAND_DATA_OUT;
8367 		/* word3 iocb=iotag wqe=payload_offset_len */
8368 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8369 		bf_set(payload_offset_len, &wqe->fcp_iwrite,
8370 		       xmit_len + sizeof(struct fcp_rsp));
8371 		bf_set(cmd_buff_len, &wqe->fcp_iwrite,
8372 		       0);
8373 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
8374 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
8375 		bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
8376 		       iocbq->iocb.ulpFCP2Rcvy);
8377 		bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
8378 		/* Always open the exchange */
8379 		bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
8380 		bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
8381 		       LPFC_WQE_LENLOC_WORD4);
8382 		bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
8383 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
8384 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8385 			bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
8386 			if (phba->cfg_XLanePriority) {
8387 				bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
8388 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
8389 				       (phba->cfg_XLanePriority << 1));
8390 			}
8391 		}
8392 		/* Note, word 10 is already initialized to 0 */
8393 
8394 		if (phba->fcp_embed_io) {
8395 			struct lpfc_scsi_buf *lpfc_cmd;
8396 			struct sli4_sge *sgl;
8397 			union lpfc_wqe128 *wqe128;
8398 			struct fcp_cmnd *fcp_cmnd;
8399 			uint32_t *ptr;
8400 
8401 			/* 128 byte wqe support here */
8402 			wqe128 = (union lpfc_wqe128 *)wqe;
8403 
8404 			lpfc_cmd = iocbq->context1;
8405 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
8406 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
8407 
8408 			/* Word 0-2 - FCP_CMND */
8409 			wqe128->generic.bde.tus.f.bdeFlags =
8410 				BUFF_TYPE_BDE_IMMED;
8411 			wqe128->generic.bde.tus.f.bdeSize = sgl->sge_len;
8412 			wqe128->generic.bde.addrHigh = 0;
8413 			wqe128->generic.bde.addrLow =  88;  /* Word 22 */
8414 
8415 			bf_set(wqe_wqes, &wqe128->fcp_iwrite.wqe_com, 1);
8416 
8417 			/* Word 22-29  FCP CMND Payload */
8418 			ptr = &wqe128->words[22];
8419 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
8420 		}
8421 		break;
8422 	case CMD_FCP_IREAD64_CR:
8423 		/* word3 iocb=iotag wqe=payload_offset_len */
8424 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8425 		bf_set(payload_offset_len, &wqe->fcp_iread,
8426 		       xmit_len + sizeof(struct fcp_rsp));
8427 		bf_set(cmd_buff_len, &wqe->fcp_iread,
8428 		       0);
8429 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
8430 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
8431 		bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
8432 		       iocbq->iocb.ulpFCP2Rcvy);
8433 		bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
8434 		/* Always open the exchange */
8435 		bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
8436 		bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
8437 		       LPFC_WQE_LENLOC_WORD4);
8438 		bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
8439 		bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
8440 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8441 			bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
8442 			if (phba->cfg_XLanePriority) {
8443 				bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
8444 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
8445 				       (phba->cfg_XLanePriority << 1));
8446 			}
8447 		}
8448 		/* Note, word 10 is already initialized to 0 */
8449 
8450 		if (phba->fcp_embed_io) {
8451 			struct lpfc_scsi_buf *lpfc_cmd;
8452 			struct sli4_sge *sgl;
8453 			union lpfc_wqe128 *wqe128;
8454 			struct fcp_cmnd *fcp_cmnd;
8455 			uint32_t *ptr;
8456 
8457 			/* 128 byte wqe support here */
8458 			wqe128 = (union lpfc_wqe128 *)wqe;
8459 
8460 			lpfc_cmd = iocbq->context1;
8461 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
8462 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
8463 
8464 			/* Word 0-2 - FCP_CMND */
8465 			wqe128->generic.bde.tus.f.bdeFlags =
8466 				BUFF_TYPE_BDE_IMMED;
8467 			wqe128->generic.bde.tus.f.bdeSize = sgl->sge_len;
8468 			wqe128->generic.bde.addrHigh = 0;
8469 			wqe128->generic.bde.addrLow =  88;  /* Word 22 */
8470 
8471 			bf_set(wqe_wqes, &wqe128->fcp_iread.wqe_com, 1);
8472 
8473 			/* Word 22-29  FCP CMND Payload */
8474 			ptr = &wqe128->words[22];
8475 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
8476 		}
8477 		break;
8478 	case CMD_FCP_ICMND64_CR:
8479 		/* word3 iocb=iotag wqe=payload_offset_len */
8480 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8481 		bf_set(payload_offset_len, &wqe->fcp_icmd,
8482 		       xmit_len + sizeof(struct fcp_rsp));
8483 		bf_set(cmd_buff_len, &wqe->fcp_icmd,
8484 		       0);
8485 		/* word3 iocb=IO_TAG wqe=reserved */
8486 		bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
8487 		/* Always open the exchange */
8488 		bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
8489 		bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
8490 		bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
8491 		bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
8492 		       LPFC_WQE_LENLOC_NONE);
8493 		bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
8494 		       iocbq->iocb.ulpFCP2Rcvy);
8495 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8496 			bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
8497 			if (phba->cfg_XLanePriority) {
8498 				bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
8499 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
8500 				       (phba->cfg_XLanePriority << 1));
8501 			}
8502 		}
8503 		/* Note, word 10 is already initialized to 0 */
8504 
8505 		if (phba->fcp_embed_io) {
8506 			struct lpfc_scsi_buf *lpfc_cmd;
8507 			struct sli4_sge *sgl;
8508 			union lpfc_wqe128 *wqe128;
8509 			struct fcp_cmnd *fcp_cmnd;
8510 			uint32_t *ptr;
8511 
8512 			/* 128 byte wqe support here */
8513 			wqe128 = (union lpfc_wqe128 *)wqe;
8514 
8515 			lpfc_cmd = iocbq->context1;
8516 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
8517 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
8518 
8519 			/* Word 0-2 - FCP_CMND */
8520 			wqe128->generic.bde.tus.f.bdeFlags =
8521 				BUFF_TYPE_BDE_IMMED;
8522 			wqe128->generic.bde.tus.f.bdeSize = sgl->sge_len;
8523 			wqe128->generic.bde.addrHigh = 0;
8524 			wqe128->generic.bde.addrLow =  88;  /* Word 22 */
8525 
8526 			bf_set(wqe_wqes, &wqe128->fcp_icmd.wqe_com, 1);
8527 
8528 			/* Word 22-29  FCP CMND Payload */
8529 			ptr = &wqe128->words[22];
8530 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
8531 		}
8532 		break;
8533 	case CMD_GEN_REQUEST64_CR:
8534 		/* For this command calculate the xmit length of the
8535 		 * request bde.
8536 		 */
8537 		xmit_len = 0;
8538 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
8539 			sizeof(struct ulp_bde64);
8540 		for (i = 0; i < numBdes; i++) {
8541 			bde.tus.w = le32_to_cpu(bpl[i].tus.w);
8542 			if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
8543 				break;
8544 			xmit_len += bde.tus.f.bdeSize;
8545 		}
8546 		/* word3 iocb=IO_TAG wqe=request_payload_len */
8547 		wqe->gen_req.request_payload_len = xmit_len;
8548 		/* word4 iocb=parameter wqe=relative_offset memcpy */
8549 		/* word5 [rctl, type, df_ctl, la] copied in memcpy */
8550 		/* word6 context tag copied in memcpy */
8551 		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
8552 			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
8553 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8554 				"2015 Invalid CT %x command 0x%x\n",
8555 				ct, iocbq->iocb.ulpCommand);
8556 			return IOCB_ERROR;
8557 		}
8558 		bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
8559 		bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
8560 		bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
8561 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
8562 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
8563 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
8564 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
8565 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
8566 		wqe->gen_req.max_response_payload_len = total_len - xmit_len;
8567 		command_type = OTHER_COMMAND;
8568 		break;
8569 	case CMD_XMIT_ELS_RSP64_CX:
8570 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
8571 		/* words0-2 BDE memcpy */
8572 		/* word3 iocb=iotag32 wqe=response_payload_len */
8573 		wqe->xmit_els_rsp.response_payload_len = xmit_len;
8574 		/* word4 */
8575 		wqe->xmit_els_rsp.word4 = 0;
8576 		/* word5 iocb=rsvd wge=did */
8577 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
8578 			 iocbq->iocb.un.xseq64.xmit_els_remoteID);
8579 
8580 		if_type = bf_get(lpfc_sli_intf_if_type,
8581 					&phba->sli4_hba.sli_intf);
8582 		if (if_type == LPFC_SLI_INTF_IF_TYPE_2) {
8583 			if (iocbq->vport->fc_flag & FC_PT2PT) {
8584 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
8585 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
8586 					iocbq->vport->fc_myDID);
8587 				if (iocbq->vport->fc_myDID == Fabric_DID) {
8588 					bf_set(wqe_els_did,
8589 						&wqe->xmit_els_rsp.wqe_dest, 0);
8590 				}
8591 			}
8592 		}
8593 		bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
8594 		       ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8595 		bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
8596 		bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
8597 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
8598 		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
8599 			bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
8600 			       phba->vpi_ids[iocbq->vport->vpi]);
8601 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
8602 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
8603 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
8604 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
8605 		       LPFC_WQE_LENLOC_WORD3);
8606 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
8607 		bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
8608 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8609 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
8610 					iocbq->context2)->virt);
8611 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
8612 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
8613 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
8614 					iocbq->vport->fc_myDID);
8615 				bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
8616 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
8617 					phba->vpi_ids[phba->pport->vpi]);
8618 		}
8619 		command_type = OTHER_COMMAND;
8620 		break;
8621 	case CMD_CLOSE_XRI_CN:
8622 	case CMD_ABORT_XRI_CN:
8623 	case CMD_ABORT_XRI_CX:
8624 		/* words 0-2 memcpy should be 0 rserved */
8625 		/* port will send abts */
8626 		abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
8627 		if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
8628 			abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
8629 			fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
8630 		} else
8631 			fip = 0;
8632 
8633 		if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
8634 			/*
8635 			 * The link is down, or the command was ELS_FIP
8636 			 * so the fw does not need to send abts
8637 			 * on the wire.
8638 			 */
8639 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
8640 		else
8641 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
8642 		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
8643 		/* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
8644 		wqe->abort_cmd.rsrvd5 = 0;
8645 		bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
8646 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8647 		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
8648 		/*
8649 		 * The abort handler will send us CMD_ABORT_XRI_CN or
8650 		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
8651 		 */
8652 		bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
8653 		bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
8654 		bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
8655 		       LPFC_WQE_LENLOC_NONE);
8656 		cmnd = CMD_ABORT_XRI_CX;
8657 		command_type = OTHER_COMMAND;
8658 		xritag = 0;
8659 		break;
8660 	case CMD_XMIT_BLS_RSP64_CX:
8661 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
8662 		/* As BLS ABTS RSP WQE is very different from other WQEs,
8663 		 * we re-construct this WQE here based on information in
8664 		 * iocbq from scratch.
8665 		 */
8666 		memset(wqe, 0, sizeof(union lpfc_wqe));
8667 		/* OX_ID is invariable to who sent ABTS to CT exchange */
8668 		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
8669 		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
8670 		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
8671 		    LPFC_ABTS_UNSOL_INT) {
8672 			/* ABTS sent by initiator to CT exchange, the
8673 			 * RX_ID field will be filled with the newly
8674 			 * allocated responder XRI.
8675 			 */
8676 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
8677 			       iocbq->sli4_xritag);
8678 		} else {
8679 			/* ABTS sent by responder to CT exchange, the
8680 			 * RX_ID field will be filled with the responder
8681 			 * RX_ID from ABTS.
8682 			 */
8683 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
8684 			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
8685 		}
8686 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
8687 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
8688 
8689 		/* Use CT=VPI */
8690 		bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
8691 			ndlp->nlp_DID);
8692 		bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
8693 			iocbq->iocb.ulpContext);
8694 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
8695 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
8696 			phba->vpi_ids[phba->pport->vpi]);
8697 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
8698 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
8699 		       LPFC_WQE_LENLOC_NONE);
8700 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
8701 		command_type = OTHER_COMMAND;
8702 		if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
8703 			bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
8704 			       bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
8705 			bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
8706 			       bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
8707 			bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
8708 			       bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
8709 		}
8710 
8711 		break;
8712 	case CMD_XRI_ABORTED_CX:
8713 	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
8714 	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
8715 	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
8716 	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
8717 	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
8718 	default:
8719 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8720 				"2014 Invalid command 0x%x\n",
8721 				iocbq->iocb.ulpCommand);
8722 		return IOCB_ERROR;
8723 		break;
8724 	}
8725 
8726 	if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
8727 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
8728 	else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
8729 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
8730 	else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
8731 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
8732 	iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
8733 			      LPFC_IO_DIF_INSERT);
8734 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
8735 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
8736 	wqe->generic.wqe_com.abort_tag = abort_tag;
8737 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
8738 	bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
8739 	bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
8740 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
8741 	return 0;
8742 }
8743 
8744 /**
8745  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
8746  * @phba: Pointer to HBA context object.
8747  * @ring_number: SLI ring number to issue iocb on.
8748  * @piocb: Pointer to command iocb.
8749  * @flag: Flag indicating if this command can be put into txq.
8750  *
8751  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
8752  * an iocb command to an HBA with SLI-4 interface spec.
8753  *
8754  * This function is called with hbalock held. The function will return success
8755  * after it successfully submit the iocb to firmware or after adding to the
8756  * txq.
8757  **/
8758 static int
8759 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
8760 			 struct lpfc_iocbq *piocb, uint32_t flag)
8761 {
8762 	struct lpfc_sglq *sglq;
8763 	union lpfc_wqe *wqe;
8764 	union lpfc_wqe128 wqe128;
8765 	struct lpfc_queue *wq;
8766 	struct lpfc_sli_ring *pring = &phba->sli.ring[ring_number];
8767 
8768 	lockdep_assert_held(&phba->hbalock);
8769 
8770 	/*
8771 	 * The WQE can be either 64 or 128 bytes,
8772 	 * so allocate space on the stack assuming the largest.
8773 	 */
8774 	wqe = (union lpfc_wqe *)&wqe128;
8775 
8776 	if (piocb->sli4_xritag == NO_XRI) {
8777 		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
8778 		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
8779 			sglq = NULL;
8780 		else {
8781 			if (!list_empty(&pring->txq)) {
8782 				if (!(flag & SLI_IOCB_RET_IOCB)) {
8783 					__lpfc_sli_ringtx_put(phba,
8784 						pring, piocb);
8785 					return IOCB_SUCCESS;
8786 				} else {
8787 					return IOCB_BUSY;
8788 				}
8789 			} else {
8790 				sglq = __lpfc_sli_get_sglq(phba, piocb);
8791 				if (!sglq) {
8792 					if (!(flag & SLI_IOCB_RET_IOCB)) {
8793 						__lpfc_sli_ringtx_put(phba,
8794 								pring,
8795 								piocb);
8796 						return IOCB_SUCCESS;
8797 					} else
8798 						return IOCB_BUSY;
8799 				}
8800 			}
8801 		}
8802 	} else if (piocb->iocb_flag &  LPFC_IO_FCP) {
8803 		/* These IO's already have an XRI and a mapped sgl. */
8804 		sglq = NULL;
8805 	} else {
8806 		/*
8807 		 * This is a continuation of a commandi,(CX) so this
8808 		 * sglq is on the active list
8809 		 */
8810 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
8811 		if (!sglq)
8812 			return IOCB_ERROR;
8813 	}
8814 
8815 	if (sglq) {
8816 		piocb->sli4_lxritag = sglq->sli4_lxritag;
8817 		piocb->sli4_xritag = sglq->sli4_xritag;
8818 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
8819 			return IOCB_ERROR;
8820 	}
8821 
8822 	if (lpfc_sli4_iocb2wqe(phba, piocb, wqe))
8823 		return IOCB_ERROR;
8824 
8825 	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
8826 	    (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
8827 		if (!phba->cfg_fof || (!(piocb->iocb_flag & LPFC_IO_OAS))) {
8828 			wq = phba->sli4_hba.fcp_wq[piocb->fcp_wqidx];
8829 		} else {
8830 			wq = phba->sli4_hba.oas_wq;
8831 		}
8832 		if (lpfc_sli4_wq_put(wq, wqe))
8833 			return IOCB_ERROR;
8834 	} else {
8835 		if (unlikely(!phba->sli4_hba.els_wq))
8836 			return IOCB_ERROR;
8837 		if (lpfc_sli4_wq_put(phba->sli4_hba.els_wq, wqe))
8838 			return IOCB_ERROR;
8839 	}
8840 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
8841 
8842 	return 0;
8843 }
8844 
8845 /**
8846  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
8847  *
8848  * This routine wraps the actual lockless version for issusing IOCB function
8849  * pointer from the lpfc_hba struct.
8850  *
8851  * Return codes:
8852  * IOCB_ERROR - Error
8853  * IOCB_SUCCESS - Success
8854  * IOCB_BUSY - Busy
8855  **/
8856 int
8857 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
8858 		struct lpfc_iocbq *piocb, uint32_t flag)
8859 {
8860 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
8861 }
8862 
8863 /**
8864  * lpfc_sli_api_table_setup - Set up sli api function jump table
8865  * @phba: The hba struct for which this call is being executed.
8866  * @dev_grp: The HBA PCI-Device group number.
8867  *
8868  * This routine sets up the SLI interface API function jump table in @phba
8869  * struct.
8870  * Returns: 0 - success, -ENODEV - failure.
8871  **/
8872 int
8873 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8874 {
8875 
8876 	switch (dev_grp) {
8877 	case LPFC_PCI_DEV_LP:
8878 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
8879 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
8880 		break;
8881 	case LPFC_PCI_DEV_OC:
8882 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
8883 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
8884 		break;
8885 	default:
8886 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8887 				"1419 Invalid HBA PCI-device group: 0x%x\n",
8888 				dev_grp);
8889 		return -ENODEV;
8890 		break;
8891 	}
8892 	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
8893 	return 0;
8894 }
8895 
8896 /**
8897  * lpfc_sli_calc_ring - Calculates which ring to use
8898  * @phba: Pointer to HBA context object.
8899  * @ring_number: Initial ring
8900  * @piocb: Pointer to command iocb.
8901  *
8902  * For SLI4, FCP IO can deferred to one fo many WQs, based on
8903  * fcp_wqidx, thus we need to calculate the corresponding ring.
8904  * Since ABORTS must go on the same WQ of the command they are
8905  * aborting, we use command's fcp_wqidx.
8906  */
8907 int
8908 lpfc_sli_calc_ring(struct lpfc_hba *phba, uint32_t ring_number,
8909 		    struct lpfc_iocbq *piocb)
8910 {
8911 	if (phba->sli_rev < LPFC_SLI_REV4)
8912 		return ring_number;
8913 
8914 	if (piocb->iocb_flag &  (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
8915 		if (!(phba->cfg_fof) ||
8916 				(!(piocb->iocb_flag & LPFC_IO_FOF))) {
8917 			if (unlikely(!phba->sli4_hba.fcp_wq))
8918 				return LPFC_HBA_ERROR;
8919 			/*
8920 			 * for abort iocb fcp_wqidx should already
8921 			 * be setup based on what work queue we used.
8922 			 */
8923 			if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX))
8924 				piocb->fcp_wqidx =
8925 					lpfc_sli4_scmd_to_wqidx_distr(phba,
8926 							      piocb->context1);
8927 			ring_number = MAX_SLI3_CONFIGURED_RINGS +
8928 				piocb->fcp_wqidx;
8929 		} else {
8930 			if (unlikely(!phba->sli4_hba.oas_wq))
8931 				return LPFC_HBA_ERROR;
8932 			piocb->fcp_wqidx = 0;
8933 			ring_number =  LPFC_FCP_OAS_RING;
8934 		}
8935 	}
8936 	return ring_number;
8937 }
8938 
8939 /**
8940  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
8941  * @phba: Pointer to HBA context object.
8942  * @pring: Pointer to driver SLI ring object.
8943  * @piocb: Pointer to command iocb.
8944  * @flag: Flag indicating if this command can be put into txq.
8945  *
8946  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
8947  * function. This function gets the hbalock and calls
8948  * __lpfc_sli_issue_iocb function and will return the error returned
8949  * by __lpfc_sli_issue_iocb function. This wrapper is used by
8950  * functions which do not hold hbalock.
8951  **/
8952 int
8953 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
8954 		    struct lpfc_iocbq *piocb, uint32_t flag)
8955 {
8956 	struct lpfc_fcp_eq_hdl *fcp_eq_hdl;
8957 	struct lpfc_sli_ring *pring;
8958 	struct lpfc_queue *fpeq;
8959 	struct lpfc_eqe *eqe;
8960 	unsigned long iflags;
8961 	int rc, idx;
8962 
8963 	if (phba->sli_rev == LPFC_SLI_REV4) {
8964 		ring_number = lpfc_sli_calc_ring(phba, ring_number, piocb);
8965 		if (unlikely(ring_number == LPFC_HBA_ERROR))
8966 			return IOCB_ERROR;
8967 		idx = piocb->fcp_wqidx;
8968 
8969 		pring = &phba->sli.ring[ring_number];
8970 		spin_lock_irqsave(&pring->ring_lock, iflags);
8971 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
8972 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
8973 
8974 		if (lpfc_fcp_look_ahead && (piocb->iocb_flag &  LPFC_IO_FCP)) {
8975 			fcp_eq_hdl = &phba->sli4_hba.fcp_eq_hdl[idx];
8976 
8977 			if (atomic_dec_and_test(&fcp_eq_hdl->
8978 				fcp_eq_in_use)) {
8979 
8980 				/* Get associated EQ with this index */
8981 				fpeq = phba->sli4_hba.hba_eq[idx];
8982 
8983 				/* Turn off interrupts from this EQ */
8984 				lpfc_sli4_eq_clr_intr(fpeq);
8985 
8986 				/*
8987 				 * Process all the events on FCP EQ
8988 				 */
8989 				while ((eqe = lpfc_sli4_eq_get(fpeq))) {
8990 					lpfc_sli4_hba_handle_eqe(phba,
8991 						eqe, idx);
8992 					fpeq->EQ_processed++;
8993 				}
8994 
8995 				/* Always clear and re-arm the EQ */
8996 				lpfc_sli4_eq_release(fpeq,
8997 					LPFC_QUEUE_REARM);
8998 			}
8999 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
9000 		}
9001 	} else {
9002 		/* For now, SLI2/3 will still use hbalock */
9003 		spin_lock_irqsave(&phba->hbalock, iflags);
9004 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
9005 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9006 	}
9007 	return rc;
9008 }
9009 
9010 /**
9011  * lpfc_extra_ring_setup - Extra ring setup function
9012  * @phba: Pointer to HBA context object.
9013  *
9014  * This function is called while driver attaches with the
9015  * HBA to setup the extra ring. The extra ring is used
9016  * only when driver needs to support target mode functionality
9017  * or IP over FC functionalities.
9018  *
9019  * This function is called with no lock held.
9020  **/
9021 static int
9022 lpfc_extra_ring_setup( struct lpfc_hba *phba)
9023 {
9024 	struct lpfc_sli *psli;
9025 	struct lpfc_sli_ring *pring;
9026 
9027 	psli = &phba->sli;
9028 
9029 	/* Adjust cmd/rsp ring iocb entries more evenly */
9030 
9031 	/* Take some away from the FCP ring */
9032 	pring = &psli->ring[psli->fcp_ring];
9033 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
9034 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
9035 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
9036 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
9037 
9038 	/* and give them to the extra ring */
9039 	pring = &psli->ring[psli->extra_ring];
9040 
9041 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
9042 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
9043 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
9044 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
9045 
9046 	/* Setup default profile for this ring */
9047 	pring->iotag_max = 4096;
9048 	pring->num_mask = 1;
9049 	pring->prt[0].profile = 0;      /* Mask 0 */
9050 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
9051 	pring->prt[0].type = phba->cfg_multi_ring_type;
9052 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
9053 	return 0;
9054 }
9055 
9056 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
9057  * @phba: Pointer to HBA context object.
9058  * @iocbq: Pointer to iocb object.
9059  *
9060  * The async_event handler calls this routine when it receives
9061  * an ASYNC_STATUS_CN event from the port.  The port generates
9062  * this event when an Abort Sequence request to an rport fails
9063  * twice in succession.  The abort could be originated by the
9064  * driver or by the port.  The ABTS could have been for an ELS
9065  * or FCP IO.  The port only generates this event when an ABTS
9066  * fails to complete after one retry.
9067  */
9068 static void
9069 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
9070 			  struct lpfc_iocbq *iocbq)
9071 {
9072 	struct lpfc_nodelist *ndlp = NULL;
9073 	uint16_t rpi = 0, vpi = 0;
9074 	struct lpfc_vport *vport = NULL;
9075 
9076 	/* The rpi in the ulpContext is vport-sensitive. */
9077 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
9078 	rpi = iocbq->iocb.ulpContext;
9079 
9080 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9081 			"3092 Port generated ABTS async event "
9082 			"on vpi %d rpi %d status 0x%x\n",
9083 			vpi, rpi, iocbq->iocb.ulpStatus);
9084 
9085 	vport = lpfc_find_vport_by_vpid(phba, vpi);
9086 	if (!vport)
9087 		goto err_exit;
9088 	ndlp = lpfc_findnode_rpi(vport, rpi);
9089 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp))
9090 		goto err_exit;
9091 
9092 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
9093 		lpfc_sli_abts_recover_port(vport, ndlp);
9094 	return;
9095 
9096  err_exit:
9097 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9098 			"3095 Event Context not found, no "
9099 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
9100 			iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
9101 			vpi, rpi);
9102 }
9103 
9104 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
9105  * @phba: pointer to HBA context object.
9106  * @ndlp: nodelist pointer for the impacted rport.
9107  * @axri: pointer to the wcqe containing the failed exchange.
9108  *
9109  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
9110  * port.  The port generates this event when an abort exchange request to an
9111  * rport fails twice in succession with no reply.  The abort could be originated
9112  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
9113  */
9114 void
9115 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
9116 			   struct lpfc_nodelist *ndlp,
9117 			   struct sli4_wcqe_xri_aborted *axri)
9118 {
9119 	struct lpfc_vport *vport;
9120 	uint32_t ext_status = 0;
9121 
9122 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
9123 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9124 				"3115 Node Context not found, driver "
9125 				"ignoring abts err event\n");
9126 		return;
9127 	}
9128 
9129 	vport = ndlp->vport;
9130 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9131 			"3116 Port generated FCP XRI ABORT event on "
9132 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
9133 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
9134 			bf_get(lpfc_wcqe_xa_xri, axri),
9135 			bf_get(lpfc_wcqe_xa_status, axri),
9136 			axri->parameter);
9137 
9138 	/*
9139 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
9140 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
9141 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
9142 	 */
9143 	ext_status = axri->parameter & IOERR_PARAM_MASK;
9144 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
9145 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
9146 		lpfc_sli_abts_recover_port(vport, ndlp);
9147 }
9148 
9149 /**
9150  * lpfc_sli_async_event_handler - ASYNC iocb handler function
9151  * @phba: Pointer to HBA context object.
9152  * @pring: Pointer to driver SLI ring object.
9153  * @iocbq: Pointer to iocb object.
9154  *
9155  * This function is called by the slow ring event handler
9156  * function when there is an ASYNC event iocb in the ring.
9157  * This function is called with no lock held.
9158  * Currently this function handles only temperature related
9159  * ASYNC events. The function decodes the temperature sensor
9160  * event message and posts events for the management applications.
9161  **/
9162 static void
9163 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
9164 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
9165 {
9166 	IOCB_t *icmd;
9167 	uint16_t evt_code;
9168 	struct temp_event temp_event_data;
9169 	struct Scsi_Host *shost;
9170 	uint32_t *iocb_w;
9171 
9172 	icmd = &iocbq->iocb;
9173 	evt_code = icmd->un.asyncstat.evt_code;
9174 
9175 	switch (evt_code) {
9176 	case ASYNC_TEMP_WARN:
9177 	case ASYNC_TEMP_SAFE:
9178 		temp_event_data.data = (uint32_t) icmd->ulpContext;
9179 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
9180 		if (evt_code == ASYNC_TEMP_WARN) {
9181 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
9182 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
9183 				"0347 Adapter is very hot, please take "
9184 				"corrective action. temperature : %d Celsius\n",
9185 				(uint32_t) icmd->ulpContext);
9186 		} else {
9187 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
9188 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
9189 				"0340 Adapter temperature is OK now. "
9190 				"temperature : %d Celsius\n",
9191 				(uint32_t) icmd->ulpContext);
9192 		}
9193 
9194 		/* Send temperature change event to applications */
9195 		shost = lpfc_shost_from_vport(phba->pport);
9196 		fc_host_post_vendor_event(shost, fc_get_event_number(),
9197 			sizeof(temp_event_data), (char *) &temp_event_data,
9198 			LPFC_NL_VENDOR_ID);
9199 		break;
9200 	case ASYNC_STATUS_CN:
9201 		lpfc_sli_abts_err_handler(phba, iocbq);
9202 		break;
9203 	default:
9204 		iocb_w = (uint32_t *) icmd;
9205 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9206 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
9207 			" evt_code 0x%x\n"
9208 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
9209 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
9210 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
9211 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
9212 			pring->ringno, icmd->un.asyncstat.evt_code,
9213 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
9214 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
9215 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
9216 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
9217 
9218 		break;
9219 	}
9220 }
9221 
9222 
9223 /**
9224  * lpfc_sli_setup - SLI ring setup function
9225  * @phba: Pointer to HBA context object.
9226  *
9227  * lpfc_sli_setup sets up rings of the SLI interface with
9228  * number of iocbs per ring and iotags. This function is
9229  * called while driver attach to the HBA and before the
9230  * interrupts are enabled. So there is no need for locking.
9231  *
9232  * This function always returns 0.
9233  **/
9234 int
9235 lpfc_sli_setup(struct lpfc_hba *phba)
9236 {
9237 	int i, totiocbsize = 0;
9238 	struct lpfc_sli *psli = &phba->sli;
9239 	struct lpfc_sli_ring *pring;
9240 
9241 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
9242 	if (phba->sli_rev == LPFC_SLI_REV4)
9243 		psli->num_rings += phba->cfg_fcp_io_channel;
9244 	psli->sli_flag = 0;
9245 	psli->fcp_ring = LPFC_FCP_RING;
9246 	psli->next_ring = LPFC_FCP_NEXT_RING;
9247 	psli->extra_ring = LPFC_EXTRA_RING;
9248 
9249 	psli->iocbq_lookup = NULL;
9250 	psli->iocbq_lookup_len = 0;
9251 	psli->last_iotag = 0;
9252 
9253 	for (i = 0; i < psli->num_rings; i++) {
9254 		pring = &psli->ring[i];
9255 		switch (i) {
9256 		case LPFC_FCP_RING:	/* ring 0 - FCP */
9257 			/* numCiocb and numRiocb are used in config_port */
9258 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
9259 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
9260 			pring->sli.sli3.numCiocb +=
9261 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
9262 			pring->sli.sli3.numRiocb +=
9263 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
9264 			pring->sli.sli3.numCiocb +=
9265 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
9266 			pring->sli.sli3.numRiocb +=
9267 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
9268 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9269 							SLI3_IOCB_CMD_SIZE :
9270 							SLI2_IOCB_CMD_SIZE;
9271 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9272 							SLI3_IOCB_RSP_SIZE :
9273 							SLI2_IOCB_RSP_SIZE;
9274 			pring->iotag_ctr = 0;
9275 			pring->iotag_max =
9276 			    (phba->cfg_hba_queue_depth * 2);
9277 			pring->fast_iotag = pring->iotag_max;
9278 			pring->num_mask = 0;
9279 			break;
9280 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
9281 			/* numCiocb and numRiocb are used in config_port */
9282 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
9283 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
9284 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9285 							SLI3_IOCB_CMD_SIZE :
9286 							SLI2_IOCB_CMD_SIZE;
9287 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9288 							SLI3_IOCB_RSP_SIZE :
9289 							SLI2_IOCB_RSP_SIZE;
9290 			pring->iotag_max = phba->cfg_hba_queue_depth;
9291 			pring->num_mask = 0;
9292 			break;
9293 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
9294 			/* numCiocb and numRiocb are used in config_port */
9295 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
9296 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
9297 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9298 							SLI3_IOCB_CMD_SIZE :
9299 							SLI2_IOCB_CMD_SIZE;
9300 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9301 							SLI3_IOCB_RSP_SIZE :
9302 							SLI2_IOCB_RSP_SIZE;
9303 			pring->fast_iotag = 0;
9304 			pring->iotag_ctr = 0;
9305 			pring->iotag_max = 4096;
9306 			pring->lpfc_sli_rcv_async_status =
9307 				lpfc_sli_async_event_handler;
9308 			pring->num_mask = LPFC_MAX_RING_MASK;
9309 			pring->prt[0].profile = 0;	/* Mask 0 */
9310 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
9311 			pring->prt[0].type = FC_TYPE_ELS;
9312 			pring->prt[0].lpfc_sli_rcv_unsol_event =
9313 			    lpfc_els_unsol_event;
9314 			pring->prt[1].profile = 0;	/* Mask 1 */
9315 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
9316 			pring->prt[1].type = FC_TYPE_ELS;
9317 			pring->prt[1].lpfc_sli_rcv_unsol_event =
9318 			    lpfc_els_unsol_event;
9319 			pring->prt[2].profile = 0;	/* Mask 2 */
9320 			/* NameServer Inquiry */
9321 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
9322 			/* NameServer */
9323 			pring->prt[2].type = FC_TYPE_CT;
9324 			pring->prt[2].lpfc_sli_rcv_unsol_event =
9325 			    lpfc_ct_unsol_event;
9326 			pring->prt[3].profile = 0;	/* Mask 3 */
9327 			/* NameServer response */
9328 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
9329 			/* NameServer */
9330 			pring->prt[3].type = FC_TYPE_CT;
9331 			pring->prt[3].lpfc_sli_rcv_unsol_event =
9332 			    lpfc_ct_unsol_event;
9333 			break;
9334 		}
9335 		totiocbsize += (pring->sli.sli3.numCiocb *
9336 			pring->sli.sli3.sizeCiocb) +
9337 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
9338 	}
9339 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
9340 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
9341 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
9342 		       "SLI2 SLIM Data: x%x x%lx\n",
9343 		       phba->brd_no, totiocbsize,
9344 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
9345 	}
9346 	if (phba->cfg_multi_ring_support == 2)
9347 		lpfc_extra_ring_setup(phba);
9348 
9349 	return 0;
9350 }
9351 
9352 /**
9353  * lpfc_sli_queue_setup - Queue initialization function
9354  * @phba: Pointer to HBA context object.
9355  *
9356  * lpfc_sli_queue_setup sets up mailbox queues and iocb queues for each
9357  * ring. This function also initializes ring indices of each ring.
9358  * This function is called during the initialization of the SLI
9359  * interface of an HBA.
9360  * This function is called with no lock held and always returns
9361  * 1.
9362  **/
9363 int
9364 lpfc_sli_queue_setup(struct lpfc_hba *phba)
9365 {
9366 	struct lpfc_sli *psli;
9367 	struct lpfc_sli_ring *pring;
9368 	int i;
9369 
9370 	psli = &phba->sli;
9371 	spin_lock_irq(&phba->hbalock);
9372 	INIT_LIST_HEAD(&psli->mboxq);
9373 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
9374 	/* Initialize list headers for txq and txcmplq as double linked lists */
9375 	for (i = 0; i < psli->num_rings; i++) {
9376 		pring = &psli->ring[i];
9377 		pring->ringno = i;
9378 		pring->sli.sli3.next_cmdidx  = 0;
9379 		pring->sli.sli3.local_getidx = 0;
9380 		pring->sli.sli3.cmdidx = 0;
9381 		pring->flag = 0;
9382 		INIT_LIST_HEAD(&pring->txq);
9383 		INIT_LIST_HEAD(&pring->txcmplq);
9384 		INIT_LIST_HEAD(&pring->iocb_continueq);
9385 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
9386 		INIT_LIST_HEAD(&pring->postbufq);
9387 		spin_lock_init(&pring->ring_lock);
9388 	}
9389 	spin_unlock_irq(&phba->hbalock);
9390 	return 1;
9391 }
9392 
9393 /**
9394  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
9395  * @phba: Pointer to HBA context object.
9396  *
9397  * This routine flushes the mailbox command subsystem. It will unconditionally
9398  * flush all the mailbox commands in the three possible stages in the mailbox
9399  * command sub-system: pending mailbox command queue; the outstanding mailbox
9400  * command; and completed mailbox command queue. It is caller's responsibility
9401  * to make sure that the driver is in the proper state to flush the mailbox
9402  * command sub-system. Namely, the posting of mailbox commands into the
9403  * pending mailbox command queue from the various clients must be stopped;
9404  * either the HBA is in a state that it will never works on the outstanding
9405  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
9406  * mailbox command has been completed.
9407  **/
9408 static void
9409 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
9410 {
9411 	LIST_HEAD(completions);
9412 	struct lpfc_sli *psli = &phba->sli;
9413 	LPFC_MBOXQ_t *pmb;
9414 	unsigned long iflag;
9415 
9416 	/* Flush all the mailbox commands in the mbox system */
9417 	spin_lock_irqsave(&phba->hbalock, iflag);
9418 	/* The pending mailbox command queue */
9419 	list_splice_init(&phba->sli.mboxq, &completions);
9420 	/* The outstanding active mailbox command */
9421 	if (psli->mbox_active) {
9422 		list_add_tail(&psli->mbox_active->list, &completions);
9423 		psli->mbox_active = NULL;
9424 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9425 	}
9426 	/* The completed mailbox command queue */
9427 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
9428 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9429 
9430 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
9431 	while (!list_empty(&completions)) {
9432 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
9433 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
9434 		if (pmb->mbox_cmpl)
9435 			pmb->mbox_cmpl(phba, pmb);
9436 	}
9437 }
9438 
9439 /**
9440  * lpfc_sli_host_down - Vport cleanup function
9441  * @vport: Pointer to virtual port object.
9442  *
9443  * lpfc_sli_host_down is called to clean up the resources
9444  * associated with a vport before destroying virtual
9445  * port data structures.
9446  * This function does following operations:
9447  * - Free discovery resources associated with this virtual
9448  *   port.
9449  * - Free iocbs associated with this virtual port in
9450  *   the txq.
9451  * - Send abort for all iocb commands associated with this
9452  *   vport in txcmplq.
9453  *
9454  * This function is called with no lock held and always returns 1.
9455  **/
9456 int
9457 lpfc_sli_host_down(struct lpfc_vport *vport)
9458 {
9459 	LIST_HEAD(completions);
9460 	struct lpfc_hba *phba = vport->phba;
9461 	struct lpfc_sli *psli = &phba->sli;
9462 	struct lpfc_sli_ring *pring;
9463 	struct lpfc_iocbq *iocb, *next_iocb;
9464 	int i;
9465 	unsigned long flags = 0;
9466 	uint16_t prev_pring_flag;
9467 
9468 	lpfc_cleanup_discovery_resources(vport);
9469 
9470 	spin_lock_irqsave(&phba->hbalock, flags);
9471 	for (i = 0; i < psli->num_rings; i++) {
9472 		pring = &psli->ring[i];
9473 		prev_pring_flag = pring->flag;
9474 		/* Only slow rings */
9475 		if (pring->ringno == LPFC_ELS_RING) {
9476 			pring->flag |= LPFC_DEFERRED_RING_EVENT;
9477 			/* Set the lpfc data pending flag */
9478 			set_bit(LPFC_DATA_READY, &phba->data_flags);
9479 		}
9480 		/*
9481 		 * Error everything on the txq since these iocbs have not been
9482 		 * given to the FW yet.
9483 		 */
9484 		list_for_each_entry_safe(iocb, next_iocb, &pring->txq, list) {
9485 			if (iocb->vport != vport)
9486 				continue;
9487 			list_move_tail(&iocb->list, &completions);
9488 		}
9489 
9490 		/* Next issue ABTS for everything on the txcmplq */
9491 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq,
9492 									list) {
9493 			if (iocb->vport != vport)
9494 				continue;
9495 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
9496 		}
9497 
9498 		pring->flag = prev_pring_flag;
9499 	}
9500 
9501 	spin_unlock_irqrestore(&phba->hbalock, flags);
9502 
9503 	/* Cancel all the IOCBs from the completions list */
9504 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
9505 			      IOERR_SLI_DOWN);
9506 	return 1;
9507 }
9508 
9509 /**
9510  * lpfc_sli_hba_down - Resource cleanup function for the HBA
9511  * @phba: Pointer to HBA context object.
9512  *
9513  * This function cleans up all iocb, buffers, mailbox commands
9514  * while shutting down the HBA. This function is called with no
9515  * lock held and always returns 1.
9516  * This function does the following to cleanup driver resources:
9517  * - Free discovery resources for each virtual port
9518  * - Cleanup any pending fabric iocbs
9519  * - Iterate through the iocb txq and free each entry
9520  *   in the list.
9521  * - Free up any buffer posted to the HBA
9522  * - Free mailbox commands in the mailbox queue.
9523  **/
9524 int
9525 lpfc_sli_hba_down(struct lpfc_hba *phba)
9526 {
9527 	LIST_HEAD(completions);
9528 	struct lpfc_sli *psli = &phba->sli;
9529 	struct lpfc_sli_ring *pring;
9530 	struct lpfc_dmabuf *buf_ptr;
9531 	unsigned long flags = 0;
9532 	int i;
9533 
9534 	/* Shutdown the mailbox command sub-system */
9535 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
9536 
9537 	lpfc_hba_down_prep(phba);
9538 
9539 	lpfc_fabric_abort_hba(phba);
9540 
9541 	spin_lock_irqsave(&phba->hbalock, flags);
9542 	for (i = 0; i < psli->num_rings; i++) {
9543 		pring = &psli->ring[i];
9544 		/* Only slow rings */
9545 		if (pring->ringno == LPFC_ELS_RING) {
9546 			pring->flag |= LPFC_DEFERRED_RING_EVENT;
9547 			/* Set the lpfc data pending flag */
9548 			set_bit(LPFC_DATA_READY, &phba->data_flags);
9549 		}
9550 
9551 		/*
9552 		 * Error everything on the txq since these iocbs have not been
9553 		 * given to the FW yet.
9554 		 */
9555 		list_splice_init(&pring->txq, &completions);
9556 	}
9557 	spin_unlock_irqrestore(&phba->hbalock, flags);
9558 
9559 	/* Cancel all the IOCBs from the completions list */
9560 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
9561 			      IOERR_SLI_DOWN);
9562 
9563 	spin_lock_irqsave(&phba->hbalock, flags);
9564 	list_splice_init(&phba->elsbuf, &completions);
9565 	phba->elsbuf_cnt = 0;
9566 	phba->elsbuf_prev_cnt = 0;
9567 	spin_unlock_irqrestore(&phba->hbalock, flags);
9568 
9569 	while (!list_empty(&completions)) {
9570 		list_remove_head(&completions, buf_ptr,
9571 			struct lpfc_dmabuf, list);
9572 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
9573 		kfree(buf_ptr);
9574 	}
9575 
9576 	/* Return any active mbox cmds */
9577 	del_timer_sync(&psli->mbox_tmo);
9578 
9579 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
9580 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9581 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
9582 
9583 	return 1;
9584 }
9585 
9586 /**
9587  * lpfc_sli_pcimem_bcopy - SLI memory copy function
9588  * @srcp: Source memory pointer.
9589  * @destp: Destination memory pointer.
9590  * @cnt: Number of words required to be copied.
9591  *
9592  * This function is used for copying data between driver memory
9593  * and the SLI memory. This function also changes the endianness
9594  * of each word if native endianness is different from SLI
9595  * endianness. This function can be called with or without
9596  * lock.
9597  **/
9598 void
9599 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
9600 {
9601 	uint32_t *src = srcp;
9602 	uint32_t *dest = destp;
9603 	uint32_t ldata;
9604 	int i;
9605 
9606 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
9607 		ldata = *src;
9608 		ldata = le32_to_cpu(ldata);
9609 		*dest = ldata;
9610 		src++;
9611 		dest++;
9612 	}
9613 }
9614 
9615 
9616 /**
9617  * lpfc_sli_bemem_bcopy - SLI memory copy function
9618  * @srcp: Source memory pointer.
9619  * @destp: Destination memory pointer.
9620  * @cnt: Number of words required to be copied.
9621  *
9622  * This function is used for copying data between a data structure
9623  * with big endian representation to local endianness.
9624  * This function can be called with or without lock.
9625  **/
9626 void
9627 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
9628 {
9629 	uint32_t *src = srcp;
9630 	uint32_t *dest = destp;
9631 	uint32_t ldata;
9632 	int i;
9633 
9634 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
9635 		ldata = *src;
9636 		ldata = be32_to_cpu(ldata);
9637 		*dest = ldata;
9638 		src++;
9639 		dest++;
9640 	}
9641 }
9642 
9643 /**
9644  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
9645  * @phba: Pointer to HBA context object.
9646  * @pring: Pointer to driver SLI ring object.
9647  * @mp: Pointer to driver buffer object.
9648  *
9649  * This function is called with no lock held.
9650  * It always return zero after adding the buffer to the postbufq
9651  * buffer list.
9652  **/
9653 int
9654 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9655 			 struct lpfc_dmabuf *mp)
9656 {
9657 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
9658 	   later */
9659 	spin_lock_irq(&phba->hbalock);
9660 	list_add_tail(&mp->list, &pring->postbufq);
9661 	pring->postbufq_cnt++;
9662 	spin_unlock_irq(&phba->hbalock);
9663 	return 0;
9664 }
9665 
9666 /**
9667  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
9668  * @phba: Pointer to HBA context object.
9669  *
9670  * When HBQ is enabled, buffers are searched based on tags. This function
9671  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
9672  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
9673  * does not conflict with tags of buffer posted for unsolicited events.
9674  * The function returns the allocated tag. The function is called with
9675  * no locks held.
9676  **/
9677 uint32_t
9678 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
9679 {
9680 	spin_lock_irq(&phba->hbalock);
9681 	phba->buffer_tag_count++;
9682 	/*
9683 	 * Always set the QUE_BUFTAG_BIT to distiguish between
9684 	 * a tag assigned by HBQ.
9685 	 */
9686 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
9687 	spin_unlock_irq(&phba->hbalock);
9688 	return phba->buffer_tag_count;
9689 }
9690 
9691 /**
9692  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
9693  * @phba: Pointer to HBA context object.
9694  * @pring: Pointer to driver SLI ring object.
9695  * @tag: Buffer tag.
9696  *
9697  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
9698  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
9699  * iocb is posted to the response ring with the tag of the buffer.
9700  * This function searches the pring->postbufq list using the tag
9701  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
9702  * iocb. If the buffer is found then lpfc_dmabuf object of the
9703  * buffer is returned to the caller else NULL is returned.
9704  * This function is called with no lock held.
9705  **/
9706 struct lpfc_dmabuf *
9707 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9708 			uint32_t tag)
9709 {
9710 	struct lpfc_dmabuf *mp, *next_mp;
9711 	struct list_head *slp = &pring->postbufq;
9712 
9713 	/* Search postbufq, from the beginning, looking for a match on tag */
9714 	spin_lock_irq(&phba->hbalock);
9715 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
9716 		if (mp->buffer_tag == tag) {
9717 			list_del_init(&mp->list);
9718 			pring->postbufq_cnt--;
9719 			spin_unlock_irq(&phba->hbalock);
9720 			return mp;
9721 		}
9722 	}
9723 
9724 	spin_unlock_irq(&phba->hbalock);
9725 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9726 			"0402 Cannot find virtual addr for buffer tag on "
9727 			"ring %d Data x%lx x%p x%p x%x\n",
9728 			pring->ringno, (unsigned long) tag,
9729 			slp->next, slp->prev, pring->postbufq_cnt);
9730 
9731 	return NULL;
9732 }
9733 
9734 /**
9735  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
9736  * @phba: Pointer to HBA context object.
9737  * @pring: Pointer to driver SLI ring object.
9738  * @phys: DMA address of the buffer.
9739  *
9740  * This function searches the buffer list using the dma_address
9741  * of unsolicited event to find the driver's lpfc_dmabuf object
9742  * corresponding to the dma_address. The function returns the
9743  * lpfc_dmabuf object if a buffer is found else it returns NULL.
9744  * This function is called by the ct and els unsolicited event
9745  * handlers to get the buffer associated with the unsolicited
9746  * event.
9747  *
9748  * This function is called with no lock held.
9749  **/
9750 struct lpfc_dmabuf *
9751 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9752 			 dma_addr_t phys)
9753 {
9754 	struct lpfc_dmabuf *mp, *next_mp;
9755 	struct list_head *slp = &pring->postbufq;
9756 
9757 	/* Search postbufq, from the beginning, looking for a match on phys */
9758 	spin_lock_irq(&phba->hbalock);
9759 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
9760 		if (mp->phys == phys) {
9761 			list_del_init(&mp->list);
9762 			pring->postbufq_cnt--;
9763 			spin_unlock_irq(&phba->hbalock);
9764 			return mp;
9765 		}
9766 	}
9767 
9768 	spin_unlock_irq(&phba->hbalock);
9769 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9770 			"0410 Cannot find virtual addr for mapped buf on "
9771 			"ring %d Data x%llx x%p x%p x%x\n",
9772 			pring->ringno, (unsigned long long)phys,
9773 			slp->next, slp->prev, pring->postbufq_cnt);
9774 	return NULL;
9775 }
9776 
9777 /**
9778  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
9779  * @phba: Pointer to HBA context object.
9780  * @cmdiocb: Pointer to driver command iocb object.
9781  * @rspiocb: Pointer to driver response iocb object.
9782  *
9783  * This function is the completion handler for the abort iocbs for
9784  * ELS commands. This function is called from the ELS ring event
9785  * handler with no lock held. This function frees memory resources
9786  * associated with the abort iocb.
9787  **/
9788 static void
9789 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
9790 			struct lpfc_iocbq *rspiocb)
9791 {
9792 	IOCB_t *irsp = &rspiocb->iocb;
9793 	uint16_t abort_iotag, abort_context;
9794 	struct lpfc_iocbq *abort_iocb = NULL;
9795 
9796 	if (irsp->ulpStatus) {
9797 
9798 		/*
9799 		 * Assume that the port already completed and returned, or
9800 		 * will return the iocb. Just Log the message.
9801 		 */
9802 		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
9803 		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
9804 
9805 		spin_lock_irq(&phba->hbalock);
9806 		if (phba->sli_rev < LPFC_SLI_REV4) {
9807 			if (abort_iotag != 0 &&
9808 				abort_iotag <= phba->sli.last_iotag)
9809 				abort_iocb =
9810 					phba->sli.iocbq_lookup[abort_iotag];
9811 		} else
9812 			/* For sli4 the abort_tag is the XRI,
9813 			 * so the abort routine puts the iotag  of the iocb
9814 			 * being aborted in the context field of the abort
9815 			 * IOCB.
9816 			 */
9817 			abort_iocb = phba->sli.iocbq_lookup[abort_context];
9818 
9819 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
9820 				"0327 Cannot abort els iocb %p "
9821 				"with tag %x context %x, abort status %x, "
9822 				"abort code %x\n",
9823 				abort_iocb, abort_iotag, abort_context,
9824 				irsp->ulpStatus, irsp->un.ulpWord[4]);
9825 
9826 		spin_unlock_irq(&phba->hbalock);
9827 	}
9828 	lpfc_sli_release_iocbq(phba, cmdiocb);
9829 	return;
9830 }
9831 
9832 /**
9833  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
9834  * @phba: Pointer to HBA context object.
9835  * @cmdiocb: Pointer to driver command iocb object.
9836  * @rspiocb: Pointer to driver response iocb object.
9837  *
9838  * The function is called from SLI ring event handler with no
9839  * lock held. This function is the completion handler for ELS commands
9840  * which are aborted. The function frees memory resources used for
9841  * the aborted ELS commands.
9842  **/
9843 static void
9844 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
9845 		     struct lpfc_iocbq *rspiocb)
9846 {
9847 	IOCB_t *irsp = &rspiocb->iocb;
9848 
9849 	/* ELS cmd tag <ulpIoTag> completes */
9850 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
9851 			"0139 Ignoring ELS cmd tag x%x completion Data: "
9852 			"x%x x%x x%x\n",
9853 			irsp->ulpIoTag, irsp->ulpStatus,
9854 			irsp->un.ulpWord[4], irsp->ulpTimeout);
9855 	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
9856 		lpfc_ct_free_iocb(phba, cmdiocb);
9857 	else
9858 		lpfc_els_free_iocb(phba, cmdiocb);
9859 	return;
9860 }
9861 
9862 /**
9863  * lpfc_sli_abort_iotag_issue - Issue abort for a command iocb
9864  * @phba: Pointer to HBA context object.
9865  * @pring: Pointer to driver SLI ring object.
9866  * @cmdiocb: Pointer to driver command iocb object.
9867  *
9868  * This function issues an abort iocb for the provided command iocb down to
9869  * the port. Other than the case the outstanding command iocb is an abort
9870  * request, this function issues abort out unconditionally. This function is
9871  * called with hbalock held. The function returns 0 when it fails due to
9872  * memory allocation failure or when the command iocb is an abort request.
9873  **/
9874 static int
9875 lpfc_sli_abort_iotag_issue(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9876 			   struct lpfc_iocbq *cmdiocb)
9877 {
9878 	struct lpfc_vport *vport = cmdiocb->vport;
9879 	struct lpfc_iocbq *abtsiocbp;
9880 	IOCB_t *icmd = NULL;
9881 	IOCB_t *iabt = NULL;
9882 	int ring_number;
9883 	int retval;
9884 	unsigned long iflags;
9885 
9886 	lockdep_assert_held(&phba->hbalock);
9887 
9888 	/*
9889 	 * There are certain command types we don't want to abort.  And we
9890 	 * don't want to abort commands that are already in the process of
9891 	 * being aborted.
9892 	 */
9893 	icmd = &cmdiocb->iocb;
9894 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
9895 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
9896 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
9897 		return 0;
9898 
9899 	/* issue ABTS for this IOCB based on iotag */
9900 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
9901 	if (abtsiocbp == NULL)
9902 		return 0;
9903 
9904 	/* This signals the response to set the correct status
9905 	 * before calling the completion handler
9906 	 */
9907 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
9908 
9909 	iabt = &abtsiocbp->iocb;
9910 	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
9911 	iabt->un.acxri.abortContextTag = icmd->ulpContext;
9912 	if (phba->sli_rev == LPFC_SLI_REV4) {
9913 		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
9914 		iabt->un.acxri.abortContextTag = cmdiocb->iotag;
9915 	}
9916 	else
9917 		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
9918 	iabt->ulpLe = 1;
9919 	iabt->ulpClass = icmd->ulpClass;
9920 
9921 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
9922 	abtsiocbp->fcp_wqidx = cmdiocb->fcp_wqidx;
9923 	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
9924 		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
9925 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
9926 		abtsiocbp->iocb_flag |= LPFC_IO_FOF;
9927 
9928 	if (phba->link_state >= LPFC_LINK_UP)
9929 		iabt->ulpCommand = CMD_ABORT_XRI_CN;
9930 	else
9931 		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
9932 
9933 	abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
9934 
9935 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
9936 			 "0339 Abort xri x%x, original iotag x%x, "
9937 			 "abort cmd iotag x%x\n",
9938 			 iabt->un.acxri.abortIoTag,
9939 			 iabt->un.acxri.abortContextTag,
9940 			 abtsiocbp->iotag);
9941 
9942 	if (phba->sli_rev == LPFC_SLI_REV4) {
9943 		ring_number =
9944 			lpfc_sli_calc_ring(phba, pring->ringno, abtsiocbp);
9945 		if (unlikely(ring_number == LPFC_HBA_ERROR))
9946 			return 0;
9947 		pring = &phba->sli.ring[ring_number];
9948 		/* Note: both hbalock and ring_lock need to be set here */
9949 		spin_lock_irqsave(&pring->ring_lock, iflags);
9950 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
9951 			abtsiocbp, 0);
9952 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
9953 	} else {
9954 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
9955 			abtsiocbp, 0);
9956 	}
9957 
9958 	if (retval)
9959 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
9960 
9961 	/*
9962 	 * Caller to this routine should check for IOCB_ERROR
9963 	 * and handle it properly.  This routine no longer removes
9964 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
9965 	 */
9966 	return retval;
9967 }
9968 
9969 /**
9970  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
9971  * @phba: Pointer to HBA context object.
9972  * @pring: Pointer to driver SLI ring object.
9973  * @cmdiocb: Pointer to driver command iocb object.
9974  *
9975  * This function issues an abort iocb for the provided command iocb. In case
9976  * of unloading, the abort iocb will not be issued to commands on the ELS
9977  * ring. Instead, the callback function shall be changed to those commands
9978  * so that nothing happens when them finishes. This function is called with
9979  * hbalock held. The function returns 0 when the command iocb is an abort
9980  * request.
9981  **/
9982 int
9983 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9984 			   struct lpfc_iocbq *cmdiocb)
9985 {
9986 	struct lpfc_vport *vport = cmdiocb->vport;
9987 	int retval = IOCB_ERROR;
9988 	IOCB_t *icmd = NULL;
9989 
9990 	lockdep_assert_held(&phba->hbalock);
9991 
9992 	/*
9993 	 * There are certain command types we don't want to abort.  And we
9994 	 * don't want to abort commands that are already in the process of
9995 	 * being aborted.
9996 	 */
9997 	icmd = &cmdiocb->iocb;
9998 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
9999 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
10000 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
10001 		return 0;
10002 
10003 	/*
10004 	 * If we're unloading, don't abort iocb on the ELS ring, but change
10005 	 * the callback so that nothing happens when it finishes.
10006 	 */
10007 	if ((vport->load_flag & FC_UNLOADING) &&
10008 	    (pring->ringno == LPFC_ELS_RING)) {
10009 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
10010 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
10011 		else
10012 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
10013 		goto abort_iotag_exit;
10014 	}
10015 
10016 	/* Now, we try to issue the abort to the cmdiocb out */
10017 	retval = lpfc_sli_abort_iotag_issue(phba, pring, cmdiocb);
10018 
10019 abort_iotag_exit:
10020 	/*
10021 	 * Caller to this routine should check for IOCB_ERROR
10022 	 * and handle it properly.  This routine no longer removes
10023 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
10024 	 */
10025 	return retval;
10026 }
10027 
10028 /**
10029  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
10030  * @phba: pointer to lpfc HBA data structure.
10031  *
10032  * This routine will abort all pending and outstanding iocbs to an HBA.
10033  **/
10034 void
10035 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
10036 {
10037 	struct lpfc_sli *psli = &phba->sli;
10038 	struct lpfc_sli_ring *pring;
10039 	int i;
10040 
10041 	for (i = 0; i < psli->num_rings; i++) {
10042 		pring = &psli->ring[i];
10043 		lpfc_sli_abort_iocb_ring(phba, pring);
10044 	}
10045 }
10046 
10047 /**
10048  * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
10049  * @iocbq: Pointer to driver iocb object.
10050  * @vport: Pointer to driver virtual port object.
10051  * @tgt_id: SCSI ID of the target.
10052  * @lun_id: LUN ID of the scsi device.
10053  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
10054  *
10055  * This function acts as an iocb filter for functions which abort or count
10056  * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
10057  * 0 if the filtering criteria is met for the given iocb and will return
10058  * 1 if the filtering criteria is not met.
10059  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
10060  * given iocb is for the SCSI device specified by vport, tgt_id and
10061  * lun_id parameter.
10062  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
10063  * given iocb is for the SCSI target specified by vport and tgt_id
10064  * parameters.
10065  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
10066  * given iocb is for the SCSI host associated with the given vport.
10067  * This function is called with no locks held.
10068  **/
10069 static int
10070 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
10071 			   uint16_t tgt_id, uint64_t lun_id,
10072 			   lpfc_ctx_cmd ctx_cmd)
10073 {
10074 	struct lpfc_scsi_buf *lpfc_cmd;
10075 	int rc = 1;
10076 
10077 	if (!(iocbq->iocb_flag &  LPFC_IO_FCP))
10078 		return rc;
10079 
10080 	if (iocbq->vport != vport)
10081 		return rc;
10082 
10083 	lpfc_cmd = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
10084 
10085 	if (lpfc_cmd->pCmd == NULL)
10086 		return rc;
10087 
10088 	switch (ctx_cmd) {
10089 	case LPFC_CTX_LUN:
10090 		if ((lpfc_cmd->rdata->pnode) &&
10091 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
10092 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
10093 			rc = 0;
10094 		break;
10095 	case LPFC_CTX_TGT:
10096 		if ((lpfc_cmd->rdata->pnode) &&
10097 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
10098 			rc = 0;
10099 		break;
10100 	case LPFC_CTX_HOST:
10101 		rc = 0;
10102 		break;
10103 	default:
10104 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
10105 			__func__, ctx_cmd);
10106 		break;
10107 	}
10108 
10109 	return rc;
10110 }
10111 
10112 /**
10113  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
10114  * @vport: Pointer to virtual port.
10115  * @tgt_id: SCSI ID of the target.
10116  * @lun_id: LUN ID of the scsi device.
10117  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10118  *
10119  * This function returns number of FCP commands pending for the vport.
10120  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
10121  * commands pending on the vport associated with SCSI device specified
10122  * by tgt_id and lun_id parameters.
10123  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
10124  * commands pending on the vport associated with SCSI target specified
10125  * by tgt_id parameter.
10126  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
10127  * commands pending on the vport.
10128  * This function returns the number of iocbs which satisfy the filter.
10129  * This function is called without any lock held.
10130  **/
10131 int
10132 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
10133 		  lpfc_ctx_cmd ctx_cmd)
10134 {
10135 	struct lpfc_hba *phba = vport->phba;
10136 	struct lpfc_iocbq *iocbq;
10137 	int sum, i;
10138 
10139 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
10140 		iocbq = phba->sli.iocbq_lookup[i];
10141 
10142 		if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
10143 						ctx_cmd) == 0)
10144 			sum++;
10145 	}
10146 
10147 	return sum;
10148 }
10149 
10150 /**
10151  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
10152  * @phba: Pointer to HBA context object
10153  * @cmdiocb: Pointer to command iocb object.
10154  * @rspiocb: Pointer to response iocb object.
10155  *
10156  * This function is called when an aborted FCP iocb completes. This
10157  * function is called by the ring event handler with no lock held.
10158  * This function frees the iocb.
10159  **/
10160 void
10161 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
10162 			struct lpfc_iocbq *rspiocb)
10163 {
10164 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10165 			"3096 ABORT_XRI_CN completing on rpi x%x "
10166 			"original iotag x%x, abort cmd iotag x%x "
10167 			"status 0x%x, reason 0x%x\n",
10168 			cmdiocb->iocb.un.acxri.abortContextTag,
10169 			cmdiocb->iocb.un.acxri.abortIoTag,
10170 			cmdiocb->iotag, rspiocb->iocb.ulpStatus,
10171 			rspiocb->iocb.un.ulpWord[4]);
10172 	lpfc_sli_release_iocbq(phba, cmdiocb);
10173 	return;
10174 }
10175 
10176 /**
10177  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
10178  * @vport: Pointer to virtual port.
10179  * @pring: Pointer to driver SLI ring object.
10180  * @tgt_id: SCSI ID of the target.
10181  * @lun_id: LUN ID of the scsi device.
10182  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10183  *
10184  * This function sends an abort command for every SCSI command
10185  * associated with the given virtual port pending on the ring
10186  * filtered by lpfc_sli_validate_fcp_iocb function.
10187  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
10188  * FCP iocbs associated with lun specified by tgt_id and lun_id
10189  * parameters
10190  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
10191  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
10192  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
10193  * FCP iocbs associated with virtual port.
10194  * This function returns number of iocbs it failed to abort.
10195  * This function is called with no locks held.
10196  **/
10197 int
10198 lpfc_sli_abort_iocb(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
10199 		    uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd abort_cmd)
10200 {
10201 	struct lpfc_hba *phba = vport->phba;
10202 	struct lpfc_iocbq *iocbq;
10203 	struct lpfc_iocbq *abtsiocb;
10204 	IOCB_t *cmd = NULL;
10205 	int errcnt = 0, ret_val = 0;
10206 	int i;
10207 
10208 	for (i = 1; i <= phba->sli.last_iotag; i++) {
10209 		iocbq = phba->sli.iocbq_lookup[i];
10210 
10211 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
10212 					       abort_cmd) != 0)
10213 			continue;
10214 
10215 		/*
10216 		 * If the iocbq is already being aborted, don't take a second
10217 		 * action, but do count it.
10218 		 */
10219 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
10220 			continue;
10221 
10222 		/* issue ABTS for this IOCB based on iotag */
10223 		abtsiocb = lpfc_sli_get_iocbq(phba);
10224 		if (abtsiocb == NULL) {
10225 			errcnt++;
10226 			continue;
10227 		}
10228 
10229 		/* indicate the IO is being aborted by the driver. */
10230 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
10231 
10232 		cmd = &iocbq->iocb;
10233 		abtsiocb->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
10234 		abtsiocb->iocb.un.acxri.abortContextTag = cmd->ulpContext;
10235 		if (phba->sli_rev == LPFC_SLI_REV4)
10236 			abtsiocb->iocb.un.acxri.abortIoTag = iocbq->sli4_xritag;
10237 		else
10238 			abtsiocb->iocb.un.acxri.abortIoTag = cmd->ulpIoTag;
10239 		abtsiocb->iocb.ulpLe = 1;
10240 		abtsiocb->iocb.ulpClass = cmd->ulpClass;
10241 		abtsiocb->vport = vport;
10242 
10243 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
10244 		abtsiocb->fcp_wqidx = iocbq->fcp_wqidx;
10245 		if (iocbq->iocb_flag & LPFC_IO_FCP)
10246 			abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
10247 		if (iocbq->iocb_flag & LPFC_IO_FOF)
10248 			abtsiocb->iocb_flag |= LPFC_IO_FOF;
10249 
10250 		if (lpfc_is_link_up(phba))
10251 			abtsiocb->iocb.ulpCommand = CMD_ABORT_XRI_CN;
10252 		else
10253 			abtsiocb->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
10254 
10255 		/* Setup callback routine and issue the command. */
10256 		abtsiocb->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
10257 		ret_val = lpfc_sli_issue_iocb(phba, pring->ringno,
10258 					      abtsiocb, 0);
10259 		if (ret_val == IOCB_ERROR) {
10260 			lpfc_sli_release_iocbq(phba, abtsiocb);
10261 			errcnt++;
10262 			continue;
10263 		}
10264 	}
10265 
10266 	return errcnt;
10267 }
10268 
10269 /**
10270  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
10271  * @vport: Pointer to virtual port.
10272  * @pring: Pointer to driver SLI ring object.
10273  * @tgt_id: SCSI ID of the target.
10274  * @lun_id: LUN ID of the scsi device.
10275  * @taskmgmt_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10276  *
10277  * This function sends an abort command for every SCSI command
10278  * associated with the given virtual port pending on the ring
10279  * filtered by lpfc_sli_validate_fcp_iocb function.
10280  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
10281  * FCP iocbs associated with lun specified by tgt_id and lun_id
10282  * parameters
10283  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
10284  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
10285  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
10286  * FCP iocbs associated with virtual port.
10287  * This function returns number of iocbs it aborted .
10288  * This function is called with no locks held right after a taskmgmt
10289  * command is sent.
10290  **/
10291 int
10292 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
10293 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
10294 {
10295 	struct lpfc_hba *phba = vport->phba;
10296 	struct lpfc_scsi_buf *lpfc_cmd;
10297 	struct lpfc_iocbq *abtsiocbq;
10298 	struct lpfc_nodelist *ndlp;
10299 	struct lpfc_iocbq *iocbq;
10300 	IOCB_t *icmd;
10301 	int sum, i, ret_val;
10302 	unsigned long iflags;
10303 	struct lpfc_sli_ring *pring_s4;
10304 	uint32_t ring_number;
10305 
10306 	spin_lock_irq(&phba->hbalock);
10307 
10308 	/* all I/Os are in process of being flushed */
10309 	if (phba->hba_flag & HBA_FCP_IOQ_FLUSH) {
10310 		spin_unlock_irq(&phba->hbalock);
10311 		return 0;
10312 	}
10313 	sum = 0;
10314 
10315 	for (i = 1; i <= phba->sli.last_iotag; i++) {
10316 		iocbq = phba->sli.iocbq_lookup[i];
10317 
10318 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
10319 					       cmd) != 0)
10320 			continue;
10321 
10322 		/*
10323 		 * If the iocbq is already being aborted, don't take a second
10324 		 * action, but do count it.
10325 		 */
10326 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
10327 			continue;
10328 
10329 		/* issue ABTS for this IOCB based on iotag */
10330 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
10331 		if (abtsiocbq == NULL)
10332 			continue;
10333 
10334 		icmd = &iocbq->iocb;
10335 		abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
10336 		abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
10337 		if (phba->sli_rev == LPFC_SLI_REV4)
10338 			abtsiocbq->iocb.un.acxri.abortIoTag =
10339 							 iocbq->sli4_xritag;
10340 		else
10341 			abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
10342 		abtsiocbq->iocb.ulpLe = 1;
10343 		abtsiocbq->iocb.ulpClass = icmd->ulpClass;
10344 		abtsiocbq->vport = vport;
10345 
10346 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
10347 		abtsiocbq->fcp_wqidx = iocbq->fcp_wqidx;
10348 		if (iocbq->iocb_flag & LPFC_IO_FCP)
10349 			abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
10350 		if (iocbq->iocb_flag & LPFC_IO_FOF)
10351 			abtsiocbq->iocb_flag |= LPFC_IO_FOF;
10352 
10353 		lpfc_cmd = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
10354 		ndlp = lpfc_cmd->rdata->pnode;
10355 
10356 		if (lpfc_is_link_up(phba) &&
10357 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
10358 			abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
10359 		else
10360 			abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
10361 
10362 		/* Setup callback routine and issue the command. */
10363 		abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
10364 
10365 		/*
10366 		 * Indicate the IO is being aborted by the driver and set
10367 		 * the caller's flag into the aborted IO.
10368 		 */
10369 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
10370 
10371 		if (phba->sli_rev == LPFC_SLI_REV4) {
10372 			ring_number = MAX_SLI3_CONFIGURED_RINGS +
10373 					 iocbq->fcp_wqidx;
10374 			pring_s4 = &phba->sli.ring[ring_number];
10375 			/* Note: both hbalock and ring_lock must be set here */
10376 			spin_lock_irqsave(&pring_s4->ring_lock, iflags);
10377 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
10378 							abtsiocbq, 0);
10379 			spin_unlock_irqrestore(&pring_s4->ring_lock, iflags);
10380 		} else {
10381 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
10382 							abtsiocbq, 0);
10383 		}
10384 
10385 
10386 		if (ret_val == IOCB_ERROR)
10387 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
10388 		else
10389 			sum++;
10390 	}
10391 	spin_unlock_irq(&phba->hbalock);
10392 	return sum;
10393 }
10394 
10395 /**
10396  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
10397  * @phba: Pointer to HBA context object.
10398  * @cmdiocbq: Pointer to command iocb.
10399  * @rspiocbq: Pointer to response iocb.
10400  *
10401  * This function is the completion handler for iocbs issued using
10402  * lpfc_sli_issue_iocb_wait function. This function is called by the
10403  * ring event handler function without any lock held. This function
10404  * can be called from both worker thread context and interrupt
10405  * context. This function also can be called from other thread which
10406  * cleans up the SLI layer objects.
10407  * This function copy the contents of the response iocb to the
10408  * response iocb memory object provided by the caller of
10409  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
10410  * sleeps for the iocb completion.
10411  **/
10412 static void
10413 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
10414 			struct lpfc_iocbq *cmdiocbq,
10415 			struct lpfc_iocbq *rspiocbq)
10416 {
10417 	wait_queue_head_t *pdone_q;
10418 	unsigned long iflags;
10419 	struct lpfc_scsi_buf *lpfc_cmd;
10420 
10421 	spin_lock_irqsave(&phba->hbalock, iflags);
10422 	if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
10423 
10424 		/*
10425 		 * A time out has occurred for the iocb.  If a time out
10426 		 * completion handler has been supplied, call it.  Otherwise,
10427 		 * just free the iocbq.
10428 		 */
10429 
10430 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10431 		cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
10432 		cmdiocbq->wait_iocb_cmpl = NULL;
10433 		if (cmdiocbq->iocb_cmpl)
10434 			(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
10435 		else
10436 			lpfc_sli_release_iocbq(phba, cmdiocbq);
10437 		return;
10438 	}
10439 
10440 	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
10441 	if (cmdiocbq->context2 && rspiocbq)
10442 		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
10443 		       &rspiocbq->iocb, sizeof(IOCB_t));
10444 
10445 	/* Set the exchange busy flag for task management commands */
10446 	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
10447 		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
10448 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_scsi_buf,
10449 			cur_iocbq);
10450 		lpfc_cmd->exch_busy = rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY;
10451 	}
10452 
10453 	pdone_q = cmdiocbq->context_un.wait_queue;
10454 	if (pdone_q)
10455 		wake_up(pdone_q);
10456 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10457 	return;
10458 }
10459 
10460 /**
10461  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
10462  * @phba: Pointer to HBA context object..
10463  * @piocbq: Pointer to command iocb.
10464  * @flag: Flag to test.
10465  *
10466  * This routine grabs the hbalock and then test the iocb_flag to
10467  * see if the passed in flag is set.
10468  * Returns:
10469  * 1 if flag is set.
10470  * 0 if flag is not set.
10471  **/
10472 static int
10473 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
10474 		 struct lpfc_iocbq *piocbq, uint32_t flag)
10475 {
10476 	unsigned long iflags;
10477 	int ret;
10478 
10479 	spin_lock_irqsave(&phba->hbalock, iflags);
10480 	ret = piocbq->iocb_flag & flag;
10481 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10482 	return ret;
10483 
10484 }
10485 
10486 /**
10487  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
10488  * @phba: Pointer to HBA context object..
10489  * @pring: Pointer to sli ring.
10490  * @piocb: Pointer to command iocb.
10491  * @prspiocbq: Pointer to response iocb.
10492  * @timeout: Timeout in number of seconds.
10493  *
10494  * This function issues the iocb to firmware and waits for the
10495  * iocb to complete. The iocb_cmpl field of the shall be used
10496  * to handle iocbs which time out. If the field is NULL, the
10497  * function shall free the iocbq structure.  If more clean up is
10498  * needed, the caller is expected to provide a completion function
10499  * that will provide the needed clean up.  If the iocb command is
10500  * not completed within timeout seconds, the function will either
10501  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
10502  * completion function set in the iocb_cmpl field and then return
10503  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
10504  * resources if this function returns IOCB_TIMEDOUT.
10505  * The function waits for the iocb completion using an
10506  * non-interruptible wait.
10507  * This function will sleep while waiting for iocb completion.
10508  * So, this function should not be called from any context which
10509  * does not allow sleeping. Due to the same reason, this function
10510  * cannot be called with interrupt disabled.
10511  * This function assumes that the iocb completions occur while
10512  * this function sleep. So, this function cannot be called from
10513  * the thread which process iocb completion for this ring.
10514  * This function clears the iocb_flag of the iocb object before
10515  * issuing the iocb and the iocb completion handler sets this
10516  * flag and wakes this thread when the iocb completes.
10517  * The contents of the response iocb will be copied to prspiocbq
10518  * by the completion handler when the command completes.
10519  * This function returns IOCB_SUCCESS when success.
10520  * This function is called with no lock held.
10521  **/
10522 int
10523 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
10524 			 uint32_t ring_number,
10525 			 struct lpfc_iocbq *piocb,
10526 			 struct lpfc_iocbq *prspiocbq,
10527 			 uint32_t timeout)
10528 {
10529 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
10530 	long timeleft, timeout_req = 0;
10531 	int retval = IOCB_SUCCESS;
10532 	uint32_t creg_val;
10533 	struct lpfc_iocbq *iocb;
10534 	int txq_cnt = 0;
10535 	int txcmplq_cnt = 0;
10536 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
10537 	unsigned long iflags;
10538 	bool iocb_completed = true;
10539 
10540 	/*
10541 	 * If the caller has provided a response iocbq buffer, then context2
10542 	 * is NULL or its an error.
10543 	 */
10544 	if (prspiocbq) {
10545 		if (piocb->context2)
10546 			return IOCB_ERROR;
10547 		piocb->context2 = prspiocbq;
10548 	}
10549 
10550 	piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
10551 	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
10552 	piocb->context_un.wait_queue = &done_q;
10553 	piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
10554 
10555 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
10556 		if (lpfc_readl(phba->HCregaddr, &creg_val))
10557 			return IOCB_ERROR;
10558 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
10559 		writel(creg_val, phba->HCregaddr);
10560 		readl(phba->HCregaddr); /* flush */
10561 	}
10562 
10563 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
10564 				     SLI_IOCB_RET_IOCB);
10565 	if (retval == IOCB_SUCCESS) {
10566 		timeout_req = msecs_to_jiffies(timeout * 1000);
10567 		timeleft = wait_event_timeout(done_q,
10568 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
10569 				timeout_req);
10570 		spin_lock_irqsave(&phba->hbalock, iflags);
10571 		if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
10572 
10573 			/*
10574 			 * IOCB timed out.  Inform the wake iocb wait
10575 			 * completion function and set local status
10576 			 */
10577 
10578 			iocb_completed = false;
10579 			piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
10580 		}
10581 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10582 		if (iocb_completed) {
10583 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10584 					"0331 IOCB wake signaled\n");
10585 			/* Note: we are not indicating if the IOCB has a success
10586 			 * status or not - that's for the caller to check.
10587 			 * IOCB_SUCCESS means just that the command was sent and
10588 			 * completed. Not that it completed successfully.
10589 			 * */
10590 		} else if (timeleft == 0) {
10591 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10592 					"0338 IOCB wait timeout error - no "
10593 					"wake response Data x%x\n", timeout);
10594 			retval = IOCB_TIMEDOUT;
10595 		} else {
10596 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10597 					"0330 IOCB wake NOT set, "
10598 					"Data x%x x%lx\n",
10599 					timeout, (timeleft / jiffies));
10600 			retval = IOCB_TIMEDOUT;
10601 		}
10602 	} else if (retval == IOCB_BUSY) {
10603 		if (phba->cfg_log_verbose & LOG_SLI) {
10604 			list_for_each_entry(iocb, &pring->txq, list) {
10605 				txq_cnt++;
10606 			}
10607 			list_for_each_entry(iocb, &pring->txcmplq, list) {
10608 				txcmplq_cnt++;
10609 			}
10610 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10611 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
10612 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
10613 		}
10614 		return retval;
10615 	} else {
10616 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10617 				"0332 IOCB wait issue failed, Data x%x\n",
10618 				retval);
10619 		retval = IOCB_ERROR;
10620 	}
10621 
10622 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
10623 		if (lpfc_readl(phba->HCregaddr, &creg_val))
10624 			return IOCB_ERROR;
10625 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
10626 		writel(creg_val, phba->HCregaddr);
10627 		readl(phba->HCregaddr); /* flush */
10628 	}
10629 
10630 	if (prspiocbq)
10631 		piocb->context2 = NULL;
10632 
10633 	piocb->context_un.wait_queue = NULL;
10634 	piocb->iocb_cmpl = NULL;
10635 	return retval;
10636 }
10637 
10638 /**
10639  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
10640  * @phba: Pointer to HBA context object.
10641  * @pmboxq: Pointer to driver mailbox object.
10642  * @timeout: Timeout in number of seconds.
10643  *
10644  * This function issues the mailbox to firmware and waits for the
10645  * mailbox command to complete. If the mailbox command is not
10646  * completed within timeout seconds, it returns MBX_TIMEOUT.
10647  * The function waits for the mailbox completion using an
10648  * interruptible wait. If the thread is woken up due to a
10649  * signal, MBX_TIMEOUT error is returned to the caller. Caller
10650  * should not free the mailbox resources, if this function returns
10651  * MBX_TIMEOUT.
10652  * This function will sleep while waiting for mailbox completion.
10653  * So, this function should not be called from any context which
10654  * does not allow sleeping. Due to the same reason, this function
10655  * cannot be called with interrupt disabled.
10656  * This function assumes that the mailbox completion occurs while
10657  * this function sleep. So, this function cannot be called from
10658  * the worker thread which processes mailbox completion.
10659  * This function is called in the context of HBA management
10660  * applications.
10661  * This function returns MBX_SUCCESS when successful.
10662  * This function is called with no lock held.
10663  **/
10664 int
10665 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
10666 			 uint32_t timeout)
10667 {
10668 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
10669 	MAILBOX_t *mb = NULL;
10670 	int retval;
10671 	unsigned long flag;
10672 
10673 	/* The caller might set context1 for extended buffer */
10674 	if (pmboxq->context1)
10675 		mb = (MAILBOX_t *)pmboxq->context1;
10676 
10677 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
10678 	/* setup wake call as IOCB callback */
10679 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
10680 	/* setup context field to pass wait_queue pointer to wake function  */
10681 	pmboxq->context1 = &done_q;
10682 
10683 	/* now issue the command */
10684 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
10685 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
10686 		wait_event_interruptible_timeout(done_q,
10687 				pmboxq->mbox_flag & LPFC_MBX_WAKE,
10688 				msecs_to_jiffies(timeout * 1000));
10689 
10690 		spin_lock_irqsave(&phba->hbalock, flag);
10691 		/* restore the possible extended buffer for free resource */
10692 		pmboxq->context1 = (uint8_t *)mb;
10693 		/*
10694 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
10695 		 * else do not free the resources.
10696 		 */
10697 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
10698 			retval = MBX_SUCCESS;
10699 		} else {
10700 			retval = MBX_TIMEOUT;
10701 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
10702 		}
10703 		spin_unlock_irqrestore(&phba->hbalock, flag);
10704 	} else {
10705 		/* restore the possible extended buffer for free resource */
10706 		pmboxq->context1 = (uint8_t *)mb;
10707 	}
10708 
10709 	return retval;
10710 }
10711 
10712 /**
10713  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
10714  * @phba: Pointer to HBA context.
10715  *
10716  * This function is called to shutdown the driver's mailbox sub-system.
10717  * It first marks the mailbox sub-system is in a block state to prevent
10718  * the asynchronous mailbox command from issued off the pending mailbox
10719  * command queue. If the mailbox command sub-system shutdown is due to
10720  * HBA error conditions such as EEH or ERATT, this routine shall invoke
10721  * the mailbox sub-system flush routine to forcefully bring down the
10722  * mailbox sub-system. Otherwise, if it is due to normal condition (such
10723  * as with offline or HBA function reset), this routine will wait for the
10724  * outstanding mailbox command to complete before invoking the mailbox
10725  * sub-system flush routine to gracefully bring down mailbox sub-system.
10726  **/
10727 void
10728 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
10729 {
10730 	struct lpfc_sli *psli = &phba->sli;
10731 	unsigned long timeout;
10732 
10733 	if (mbx_action == LPFC_MBX_NO_WAIT) {
10734 		/* delay 100ms for port state */
10735 		msleep(100);
10736 		lpfc_sli_mbox_sys_flush(phba);
10737 		return;
10738 	}
10739 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
10740 
10741 	spin_lock_irq(&phba->hbalock);
10742 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
10743 
10744 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
10745 		/* Determine how long we might wait for the active mailbox
10746 		 * command to be gracefully completed by firmware.
10747 		 */
10748 		if (phba->sli.mbox_active)
10749 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
10750 						phba->sli.mbox_active) *
10751 						1000) + jiffies;
10752 		spin_unlock_irq(&phba->hbalock);
10753 
10754 		while (phba->sli.mbox_active) {
10755 			/* Check active mailbox complete status every 2ms */
10756 			msleep(2);
10757 			if (time_after(jiffies, timeout))
10758 				/* Timeout, let the mailbox flush routine to
10759 				 * forcefully release active mailbox command
10760 				 */
10761 				break;
10762 		}
10763 	} else
10764 		spin_unlock_irq(&phba->hbalock);
10765 
10766 	lpfc_sli_mbox_sys_flush(phba);
10767 }
10768 
10769 /**
10770  * lpfc_sli_eratt_read - read sli-3 error attention events
10771  * @phba: Pointer to HBA context.
10772  *
10773  * This function is called to read the SLI3 device error attention registers
10774  * for possible error attention events. The caller must hold the hostlock
10775  * with spin_lock_irq().
10776  *
10777  * This function returns 1 when there is Error Attention in the Host Attention
10778  * Register and returns 0 otherwise.
10779  **/
10780 static int
10781 lpfc_sli_eratt_read(struct lpfc_hba *phba)
10782 {
10783 	uint32_t ha_copy;
10784 
10785 	/* Read chip Host Attention (HA) register */
10786 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
10787 		goto unplug_err;
10788 
10789 	if (ha_copy & HA_ERATT) {
10790 		/* Read host status register to retrieve error event */
10791 		if (lpfc_sli_read_hs(phba))
10792 			goto unplug_err;
10793 
10794 		/* Check if there is a deferred error condition is active */
10795 		if ((HS_FFER1 & phba->work_hs) &&
10796 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
10797 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
10798 			phba->hba_flag |= DEFER_ERATT;
10799 			/* Clear all interrupt enable conditions */
10800 			writel(0, phba->HCregaddr);
10801 			readl(phba->HCregaddr);
10802 		}
10803 
10804 		/* Set the driver HA work bitmap */
10805 		phba->work_ha |= HA_ERATT;
10806 		/* Indicate polling handles this ERATT */
10807 		phba->hba_flag |= HBA_ERATT_HANDLED;
10808 		return 1;
10809 	}
10810 	return 0;
10811 
10812 unplug_err:
10813 	/* Set the driver HS work bitmap */
10814 	phba->work_hs |= UNPLUG_ERR;
10815 	/* Set the driver HA work bitmap */
10816 	phba->work_ha |= HA_ERATT;
10817 	/* Indicate polling handles this ERATT */
10818 	phba->hba_flag |= HBA_ERATT_HANDLED;
10819 	return 1;
10820 }
10821 
10822 /**
10823  * lpfc_sli4_eratt_read - read sli-4 error attention events
10824  * @phba: Pointer to HBA context.
10825  *
10826  * This function is called to read the SLI4 device error attention registers
10827  * for possible error attention events. The caller must hold the hostlock
10828  * with spin_lock_irq().
10829  *
10830  * This function returns 1 when there is Error Attention in the Host Attention
10831  * Register and returns 0 otherwise.
10832  **/
10833 static int
10834 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
10835 {
10836 	uint32_t uerr_sta_hi, uerr_sta_lo;
10837 	uint32_t if_type, portsmphr;
10838 	struct lpfc_register portstat_reg;
10839 
10840 	/*
10841 	 * For now, use the SLI4 device internal unrecoverable error
10842 	 * registers for error attention. This can be changed later.
10843 	 */
10844 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10845 	switch (if_type) {
10846 	case LPFC_SLI_INTF_IF_TYPE_0:
10847 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
10848 			&uerr_sta_lo) ||
10849 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
10850 			&uerr_sta_hi)) {
10851 			phba->work_hs |= UNPLUG_ERR;
10852 			phba->work_ha |= HA_ERATT;
10853 			phba->hba_flag |= HBA_ERATT_HANDLED;
10854 			return 1;
10855 		}
10856 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
10857 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
10858 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10859 					"1423 HBA Unrecoverable error: "
10860 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
10861 					"ue_mask_lo_reg=0x%x, "
10862 					"ue_mask_hi_reg=0x%x\n",
10863 					uerr_sta_lo, uerr_sta_hi,
10864 					phba->sli4_hba.ue_mask_lo,
10865 					phba->sli4_hba.ue_mask_hi);
10866 			phba->work_status[0] = uerr_sta_lo;
10867 			phba->work_status[1] = uerr_sta_hi;
10868 			phba->work_ha |= HA_ERATT;
10869 			phba->hba_flag |= HBA_ERATT_HANDLED;
10870 			return 1;
10871 		}
10872 		break;
10873 	case LPFC_SLI_INTF_IF_TYPE_2:
10874 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
10875 			&portstat_reg.word0) ||
10876 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
10877 			&portsmphr)){
10878 			phba->work_hs |= UNPLUG_ERR;
10879 			phba->work_ha |= HA_ERATT;
10880 			phba->hba_flag |= HBA_ERATT_HANDLED;
10881 			return 1;
10882 		}
10883 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
10884 			phba->work_status[0] =
10885 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
10886 			phba->work_status[1] =
10887 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
10888 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10889 					"2885 Port Status Event: "
10890 					"port status reg 0x%x, "
10891 					"port smphr reg 0x%x, "
10892 					"error 1=0x%x, error 2=0x%x\n",
10893 					portstat_reg.word0,
10894 					portsmphr,
10895 					phba->work_status[0],
10896 					phba->work_status[1]);
10897 			phba->work_ha |= HA_ERATT;
10898 			phba->hba_flag |= HBA_ERATT_HANDLED;
10899 			return 1;
10900 		}
10901 		break;
10902 	case LPFC_SLI_INTF_IF_TYPE_1:
10903 	default:
10904 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10905 				"2886 HBA Error Attention on unsupported "
10906 				"if type %d.", if_type);
10907 		return 1;
10908 	}
10909 
10910 	return 0;
10911 }
10912 
10913 /**
10914  * lpfc_sli_check_eratt - check error attention events
10915  * @phba: Pointer to HBA context.
10916  *
10917  * This function is called from timer soft interrupt context to check HBA's
10918  * error attention register bit for error attention events.
10919  *
10920  * This function returns 1 when there is Error Attention in the Host Attention
10921  * Register and returns 0 otherwise.
10922  **/
10923 int
10924 lpfc_sli_check_eratt(struct lpfc_hba *phba)
10925 {
10926 	uint32_t ha_copy;
10927 
10928 	/* If somebody is waiting to handle an eratt, don't process it
10929 	 * here. The brdkill function will do this.
10930 	 */
10931 	if (phba->link_flag & LS_IGNORE_ERATT)
10932 		return 0;
10933 
10934 	/* Check if interrupt handler handles this ERATT */
10935 	spin_lock_irq(&phba->hbalock);
10936 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
10937 		/* Interrupt handler has handled ERATT */
10938 		spin_unlock_irq(&phba->hbalock);
10939 		return 0;
10940 	}
10941 
10942 	/*
10943 	 * If there is deferred error attention, do not check for error
10944 	 * attention
10945 	 */
10946 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
10947 		spin_unlock_irq(&phba->hbalock);
10948 		return 0;
10949 	}
10950 
10951 	/* If PCI channel is offline, don't process it */
10952 	if (unlikely(pci_channel_offline(phba->pcidev))) {
10953 		spin_unlock_irq(&phba->hbalock);
10954 		return 0;
10955 	}
10956 
10957 	switch (phba->sli_rev) {
10958 	case LPFC_SLI_REV2:
10959 	case LPFC_SLI_REV3:
10960 		/* Read chip Host Attention (HA) register */
10961 		ha_copy = lpfc_sli_eratt_read(phba);
10962 		break;
10963 	case LPFC_SLI_REV4:
10964 		/* Read device Uncoverable Error (UERR) registers */
10965 		ha_copy = lpfc_sli4_eratt_read(phba);
10966 		break;
10967 	default:
10968 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10969 				"0299 Invalid SLI revision (%d)\n",
10970 				phba->sli_rev);
10971 		ha_copy = 0;
10972 		break;
10973 	}
10974 	spin_unlock_irq(&phba->hbalock);
10975 
10976 	return ha_copy;
10977 }
10978 
10979 /**
10980  * lpfc_intr_state_check - Check device state for interrupt handling
10981  * @phba: Pointer to HBA context.
10982  *
10983  * This inline routine checks whether a device or its PCI slot is in a state
10984  * that the interrupt should be handled.
10985  *
10986  * This function returns 0 if the device or the PCI slot is in a state that
10987  * interrupt should be handled, otherwise -EIO.
10988  */
10989 static inline int
10990 lpfc_intr_state_check(struct lpfc_hba *phba)
10991 {
10992 	/* If the pci channel is offline, ignore all the interrupts */
10993 	if (unlikely(pci_channel_offline(phba->pcidev)))
10994 		return -EIO;
10995 
10996 	/* Update device level interrupt statistics */
10997 	phba->sli.slistat.sli_intr++;
10998 
10999 	/* Ignore all interrupts during initialization. */
11000 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
11001 		return -EIO;
11002 
11003 	return 0;
11004 }
11005 
11006 /**
11007  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
11008  * @irq: Interrupt number.
11009  * @dev_id: The device context pointer.
11010  *
11011  * This function is directly called from the PCI layer as an interrupt
11012  * service routine when device with SLI-3 interface spec is enabled with
11013  * MSI-X multi-message interrupt mode and there are slow-path events in
11014  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
11015  * interrupt mode, this function is called as part of the device-level
11016  * interrupt handler. When the PCI slot is in error recovery or the HBA
11017  * is undergoing initialization, the interrupt handler will not process
11018  * the interrupt. The link attention and ELS ring attention events are
11019  * handled by the worker thread. The interrupt handler signals the worker
11020  * thread and returns for these events. This function is called without
11021  * any lock held. It gets the hbalock to access and update SLI data
11022  * structures.
11023  *
11024  * This function returns IRQ_HANDLED when interrupt is handled else it
11025  * returns IRQ_NONE.
11026  **/
11027 irqreturn_t
11028 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
11029 {
11030 	struct lpfc_hba  *phba;
11031 	uint32_t ha_copy, hc_copy;
11032 	uint32_t work_ha_copy;
11033 	unsigned long status;
11034 	unsigned long iflag;
11035 	uint32_t control;
11036 
11037 	MAILBOX_t *mbox, *pmbox;
11038 	struct lpfc_vport *vport;
11039 	struct lpfc_nodelist *ndlp;
11040 	struct lpfc_dmabuf *mp;
11041 	LPFC_MBOXQ_t *pmb;
11042 	int rc;
11043 
11044 	/*
11045 	 * Get the driver's phba structure from the dev_id and
11046 	 * assume the HBA is not interrupting.
11047 	 */
11048 	phba = (struct lpfc_hba *)dev_id;
11049 
11050 	if (unlikely(!phba))
11051 		return IRQ_NONE;
11052 
11053 	/*
11054 	 * Stuff needs to be attented to when this function is invoked as an
11055 	 * individual interrupt handler in MSI-X multi-message interrupt mode
11056 	 */
11057 	if (phba->intr_type == MSIX) {
11058 		/* Check device state for handling interrupt */
11059 		if (lpfc_intr_state_check(phba))
11060 			return IRQ_NONE;
11061 		/* Need to read HA REG for slow-path events */
11062 		spin_lock_irqsave(&phba->hbalock, iflag);
11063 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
11064 			goto unplug_error;
11065 		/* If somebody is waiting to handle an eratt don't process it
11066 		 * here. The brdkill function will do this.
11067 		 */
11068 		if (phba->link_flag & LS_IGNORE_ERATT)
11069 			ha_copy &= ~HA_ERATT;
11070 		/* Check the need for handling ERATT in interrupt handler */
11071 		if (ha_copy & HA_ERATT) {
11072 			if (phba->hba_flag & HBA_ERATT_HANDLED)
11073 				/* ERATT polling has handled ERATT */
11074 				ha_copy &= ~HA_ERATT;
11075 			else
11076 				/* Indicate interrupt handler handles ERATT */
11077 				phba->hba_flag |= HBA_ERATT_HANDLED;
11078 		}
11079 
11080 		/*
11081 		 * If there is deferred error attention, do not check for any
11082 		 * interrupt.
11083 		 */
11084 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11085 			spin_unlock_irqrestore(&phba->hbalock, iflag);
11086 			return IRQ_NONE;
11087 		}
11088 
11089 		/* Clear up only attention source related to slow-path */
11090 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
11091 			goto unplug_error;
11092 
11093 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
11094 			HC_LAINT_ENA | HC_ERINT_ENA),
11095 			phba->HCregaddr);
11096 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
11097 			phba->HAregaddr);
11098 		writel(hc_copy, phba->HCregaddr);
11099 		readl(phba->HAregaddr); /* flush */
11100 		spin_unlock_irqrestore(&phba->hbalock, iflag);
11101 	} else
11102 		ha_copy = phba->ha_copy;
11103 
11104 	work_ha_copy = ha_copy & phba->work_ha_mask;
11105 
11106 	if (work_ha_copy) {
11107 		if (work_ha_copy & HA_LATT) {
11108 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
11109 				/*
11110 				 * Turn off Link Attention interrupts
11111 				 * until CLEAR_LA done
11112 				 */
11113 				spin_lock_irqsave(&phba->hbalock, iflag);
11114 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
11115 				if (lpfc_readl(phba->HCregaddr, &control))
11116 					goto unplug_error;
11117 				control &= ~HC_LAINT_ENA;
11118 				writel(control, phba->HCregaddr);
11119 				readl(phba->HCregaddr); /* flush */
11120 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11121 			}
11122 			else
11123 				work_ha_copy &= ~HA_LATT;
11124 		}
11125 
11126 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
11127 			/*
11128 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
11129 			 * the only slow ring.
11130 			 */
11131 			status = (work_ha_copy &
11132 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
11133 			status >>= (4*LPFC_ELS_RING);
11134 			if (status & HA_RXMASK) {
11135 				spin_lock_irqsave(&phba->hbalock, iflag);
11136 				if (lpfc_readl(phba->HCregaddr, &control))
11137 					goto unplug_error;
11138 
11139 				lpfc_debugfs_slow_ring_trc(phba,
11140 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
11141 				control, status,
11142 				(uint32_t)phba->sli.slistat.sli_intr);
11143 
11144 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
11145 					lpfc_debugfs_slow_ring_trc(phba,
11146 						"ISR Disable ring:"
11147 						"pwork:x%x hawork:x%x wait:x%x",
11148 						phba->work_ha, work_ha_copy,
11149 						(uint32_t)((unsigned long)
11150 						&phba->work_waitq));
11151 
11152 					control &=
11153 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
11154 					writel(control, phba->HCregaddr);
11155 					readl(phba->HCregaddr); /* flush */
11156 				}
11157 				else {
11158 					lpfc_debugfs_slow_ring_trc(phba,
11159 						"ISR slow ring:   pwork:"
11160 						"x%x hawork:x%x wait:x%x",
11161 						phba->work_ha, work_ha_copy,
11162 						(uint32_t)((unsigned long)
11163 						&phba->work_waitq));
11164 				}
11165 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11166 			}
11167 		}
11168 		spin_lock_irqsave(&phba->hbalock, iflag);
11169 		if (work_ha_copy & HA_ERATT) {
11170 			if (lpfc_sli_read_hs(phba))
11171 				goto unplug_error;
11172 			/*
11173 			 * Check if there is a deferred error condition
11174 			 * is active
11175 			 */
11176 			if ((HS_FFER1 & phba->work_hs) &&
11177 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
11178 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
11179 				  phba->work_hs)) {
11180 				phba->hba_flag |= DEFER_ERATT;
11181 				/* Clear all interrupt enable conditions */
11182 				writel(0, phba->HCregaddr);
11183 				readl(phba->HCregaddr);
11184 			}
11185 		}
11186 
11187 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
11188 			pmb = phba->sli.mbox_active;
11189 			pmbox = &pmb->u.mb;
11190 			mbox = phba->mbox;
11191 			vport = pmb->vport;
11192 
11193 			/* First check out the status word */
11194 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
11195 			if (pmbox->mbxOwner != OWN_HOST) {
11196 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11197 				/*
11198 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
11199 				 * mbxStatus <status>
11200 				 */
11201 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11202 						LOG_SLI,
11203 						"(%d):0304 Stray Mailbox "
11204 						"Interrupt mbxCommand x%x "
11205 						"mbxStatus x%x\n",
11206 						(vport ? vport->vpi : 0),
11207 						pmbox->mbxCommand,
11208 						pmbox->mbxStatus);
11209 				/* clear mailbox attention bit */
11210 				work_ha_copy &= ~HA_MBATT;
11211 			} else {
11212 				phba->sli.mbox_active = NULL;
11213 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11214 				phba->last_completion_time = jiffies;
11215 				del_timer(&phba->sli.mbox_tmo);
11216 				if (pmb->mbox_cmpl) {
11217 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
11218 							MAILBOX_CMD_SIZE);
11219 					if (pmb->out_ext_byte_len &&
11220 						pmb->context2)
11221 						lpfc_sli_pcimem_bcopy(
11222 						phba->mbox_ext,
11223 						pmb->context2,
11224 						pmb->out_ext_byte_len);
11225 				}
11226 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
11227 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
11228 
11229 					lpfc_debugfs_disc_trc(vport,
11230 						LPFC_DISC_TRC_MBOX_VPORT,
11231 						"MBOX dflt rpi: : "
11232 						"status:x%x rpi:x%x",
11233 						(uint32_t)pmbox->mbxStatus,
11234 						pmbox->un.varWords[0], 0);
11235 
11236 					if (!pmbox->mbxStatus) {
11237 						mp = (struct lpfc_dmabuf *)
11238 							(pmb->context1);
11239 						ndlp = (struct lpfc_nodelist *)
11240 							pmb->context2;
11241 
11242 						/* Reg_LOGIN of dflt RPI was
11243 						 * successful. new lets get
11244 						 * rid of the RPI using the
11245 						 * same mbox buffer.
11246 						 */
11247 						lpfc_unreg_login(phba,
11248 							vport->vpi,
11249 							pmbox->un.varWords[0],
11250 							pmb);
11251 						pmb->mbox_cmpl =
11252 							lpfc_mbx_cmpl_dflt_rpi;
11253 						pmb->context1 = mp;
11254 						pmb->context2 = ndlp;
11255 						pmb->vport = vport;
11256 						rc = lpfc_sli_issue_mbox(phba,
11257 								pmb,
11258 								MBX_NOWAIT);
11259 						if (rc != MBX_BUSY)
11260 							lpfc_printf_log(phba,
11261 							KERN_ERR,
11262 							LOG_MBOX | LOG_SLI,
11263 							"0350 rc should have"
11264 							"been MBX_BUSY\n");
11265 						if (rc != MBX_NOT_FINISHED)
11266 							goto send_current_mbox;
11267 					}
11268 				}
11269 				spin_lock_irqsave(
11270 						&phba->pport->work_port_lock,
11271 						iflag);
11272 				phba->pport->work_port_events &=
11273 					~WORKER_MBOX_TMO;
11274 				spin_unlock_irqrestore(
11275 						&phba->pport->work_port_lock,
11276 						iflag);
11277 				lpfc_mbox_cmpl_put(phba, pmb);
11278 			}
11279 		} else
11280 			spin_unlock_irqrestore(&phba->hbalock, iflag);
11281 
11282 		if ((work_ha_copy & HA_MBATT) &&
11283 		    (phba->sli.mbox_active == NULL)) {
11284 send_current_mbox:
11285 			/* Process next mailbox command if there is one */
11286 			do {
11287 				rc = lpfc_sli_issue_mbox(phba, NULL,
11288 							 MBX_NOWAIT);
11289 			} while (rc == MBX_NOT_FINISHED);
11290 			if (rc != MBX_SUCCESS)
11291 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11292 						LOG_SLI, "0349 rc should be "
11293 						"MBX_SUCCESS\n");
11294 		}
11295 
11296 		spin_lock_irqsave(&phba->hbalock, iflag);
11297 		phba->work_ha |= work_ha_copy;
11298 		spin_unlock_irqrestore(&phba->hbalock, iflag);
11299 		lpfc_worker_wake_up(phba);
11300 	}
11301 	return IRQ_HANDLED;
11302 unplug_error:
11303 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11304 	return IRQ_HANDLED;
11305 
11306 } /* lpfc_sli_sp_intr_handler */
11307 
11308 /**
11309  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
11310  * @irq: Interrupt number.
11311  * @dev_id: The device context pointer.
11312  *
11313  * This function is directly called from the PCI layer as an interrupt
11314  * service routine when device with SLI-3 interface spec is enabled with
11315  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
11316  * ring event in the HBA. However, when the device is enabled with either
11317  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
11318  * device-level interrupt handler. When the PCI slot is in error recovery
11319  * or the HBA is undergoing initialization, the interrupt handler will not
11320  * process the interrupt. The SCSI FCP fast-path ring event are handled in
11321  * the intrrupt context. This function is called without any lock held.
11322  * It gets the hbalock to access and update SLI data structures.
11323  *
11324  * This function returns IRQ_HANDLED when interrupt is handled else it
11325  * returns IRQ_NONE.
11326  **/
11327 irqreturn_t
11328 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
11329 {
11330 	struct lpfc_hba  *phba;
11331 	uint32_t ha_copy;
11332 	unsigned long status;
11333 	unsigned long iflag;
11334 
11335 	/* Get the driver's phba structure from the dev_id and
11336 	 * assume the HBA is not interrupting.
11337 	 */
11338 	phba = (struct lpfc_hba *) dev_id;
11339 
11340 	if (unlikely(!phba))
11341 		return IRQ_NONE;
11342 
11343 	/*
11344 	 * Stuff needs to be attented to when this function is invoked as an
11345 	 * individual interrupt handler in MSI-X multi-message interrupt mode
11346 	 */
11347 	if (phba->intr_type == MSIX) {
11348 		/* Check device state for handling interrupt */
11349 		if (lpfc_intr_state_check(phba))
11350 			return IRQ_NONE;
11351 		/* Need to read HA REG for FCP ring and other ring events */
11352 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
11353 			return IRQ_HANDLED;
11354 		/* Clear up only attention source related to fast-path */
11355 		spin_lock_irqsave(&phba->hbalock, iflag);
11356 		/*
11357 		 * If there is deferred error attention, do not check for
11358 		 * any interrupt.
11359 		 */
11360 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11361 			spin_unlock_irqrestore(&phba->hbalock, iflag);
11362 			return IRQ_NONE;
11363 		}
11364 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
11365 			phba->HAregaddr);
11366 		readl(phba->HAregaddr); /* flush */
11367 		spin_unlock_irqrestore(&phba->hbalock, iflag);
11368 	} else
11369 		ha_copy = phba->ha_copy;
11370 
11371 	/*
11372 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
11373 	 */
11374 	ha_copy &= ~(phba->work_ha_mask);
11375 
11376 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
11377 	status >>= (4*LPFC_FCP_RING);
11378 	if (status & HA_RXMASK)
11379 		lpfc_sli_handle_fast_ring_event(phba,
11380 						&phba->sli.ring[LPFC_FCP_RING],
11381 						status);
11382 
11383 	if (phba->cfg_multi_ring_support == 2) {
11384 		/*
11385 		 * Process all events on extra ring. Take the optimized path
11386 		 * for extra ring IO.
11387 		 */
11388 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
11389 		status >>= (4*LPFC_EXTRA_RING);
11390 		if (status & HA_RXMASK) {
11391 			lpfc_sli_handle_fast_ring_event(phba,
11392 					&phba->sli.ring[LPFC_EXTRA_RING],
11393 					status);
11394 		}
11395 	}
11396 	return IRQ_HANDLED;
11397 }  /* lpfc_sli_fp_intr_handler */
11398 
11399 /**
11400  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
11401  * @irq: Interrupt number.
11402  * @dev_id: The device context pointer.
11403  *
11404  * This function is the HBA device-level interrupt handler to device with
11405  * SLI-3 interface spec, called from the PCI layer when either MSI or
11406  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
11407  * requires driver attention. This function invokes the slow-path interrupt
11408  * attention handling function and fast-path interrupt attention handling
11409  * function in turn to process the relevant HBA attention events. This
11410  * function is called without any lock held. It gets the hbalock to access
11411  * and update SLI data structures.
11412  *
11413  * This function returns IRQ_HANDLED when interrupt is handled, else it
11414  * returns IRQ_NONE.
11415  **/
11416 irqreturn_t
11417 lpfc_sli_intr_handler(int irq, void *dev_id)
11418 {
11419 	struct lpfc_hba  *phba;
11420 	irqreturn_t sp_irq_rc, fp_irq_rc;
11421 	unsigned long status1, status2;
11422 	uint32_t hc_copy;
11423 
11424 	/*
11425 	 * Get the driver's phba structure from the dev_id and
11426 	 * assume the HBA is not interrupting.
11427 	 */
11428 	phba = (struct lpfc_hba *) dev_id;
11429 
11430 	if (unlikely(!phba))
11431 		return IRQ_NONE;
11432 
11433 	/* Check device state for handling interrupt */
11434 	if (lpfc_intr_state_check(phba))
11435 		return IRQ_NONE;
11436 
11437 	spin_lock(&phba->hbalock);
11438 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
11439 		spin_unlock(&phba->hbalock);
11440 		return IRQ_HANDLED;
11441 	}
11442 
11443 	if (unlikely(!phba->ha_copy)) {
11444 		spin_unlock(&phba->hbalock);
11445 		return IRQ_NONE;
11446 	} else if (phba->ha_copy & HA_ERATT) {
11447 		if (phba->hba_flag & HBA_ERATT_HANDLED)
11448 			/* ERATT polling has handled ERATT */
11449 			phba->ha_copy &= ~HA_ERATT;
11450 		else
11451 			/* Indicate interrupt handler handles ERATT */
11452 			phba->hba_flag |= HBA_ERATT_HANDLED;
11453 	}
11454 
11455 	/*
11456 	 * If there is deferred error attention, do not check for any interrupt.
11457 	 */
11458 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11459 		spin_unlock(&phba->hbalock);
11460 		return IRQ_NONE;
11461 	}
11462 
11463 	/* Clear attention sources except link and error attentions */
11464 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
11465 		spin_unlock(&phba->hbalock);
11466 		return IRQ_HANDLED;
11467 	}
11468 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
11469 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
11470 		phba->HCregaddr);
11471 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
11472 	writel(hc_copy, phba->HCregaddr);
11473 	readl(phba->HAregaddr); /* flush */
11474 	spin_unlock(&phba->hbalock);
11475 
11476 	/*
11477 	 * Invokes slow-path host attention interrupt handling as appropriate.
11478 	 */
11479 
11480 	/* status of events with mailbox and link attention */
11481 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
11482 
11483 	/* status of events with ELS ring */
11484 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
11485 	status2 >>= (4*LPFC_ELS_RING);
11486 
11487 	if (status1 || (status2 & HA_RXMASK))
11488 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
11489 	else
11490 		sp_irq_rc = IRQ_NONE;
11491 
11492 	/*
11493 	 * Invoke fast-path host attention interrupt handling as appropriate.
11494 	 */
11495 
11496 	/* status of events with FCP ring */
11497 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
11498 	status1 >>= (4*LPFC_FCP_RING);
11499 
11500 	/* status of events with extra ring */
11501 	if (phba->cfg_multi_ring_support == 2) {
11502 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
11503 		status2 >>= (4*LPFC_EXTRA_RING);
11504 	} else
11505 		status2 = 0;
11506 
11507 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
11508 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
11509 	else
11510 		fp_irq_rc = IRQ_NONE;
11511 
11512 	/* Return device-level interrupt handling status */
11513 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
11514 }  /* lpfc_sli_intr_handler */
11515 
11516 /**
11517  * lpfc_sli4_fcp_xri_abort_event_proc - Process fcp xri abort event
11518  * @phba: pointer to lpfc hba data structure.
11519  *
11520  * This routine is invoked by the worker thread to process all the pending
11521  * SLI4 FCP abort XRI events.
11522  **/
11523 void lpfc_sli4_fcp_xri_abort_event_proc(struct lpfc_hba *phba)
11524 {
11525 	struct lpfc_cq_event *cq_event;
11526 
11527 	/* First, declare the fcp xri abort event has been handled */
11528 	spin_lock_irq(&phba->hbalock);
11529 	phba->hba_flag &= ~FCP_XRI_ABORT_EVENT;
11530 	spin_unlock_irq(&phba->hbalock);
11531 	/* Now, handle all the fcp xri abort events */
11532 	while (!list_empty(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue)) {
11533 		/* Get the first event from the head of the event queue */
11534 		spin_lock_irq(&phba->hbalock);
11535 		list_remove_head(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue,
11536 				 cq_event, struct lpfc_cq_event, list);
11537 		spin_unlock_irq(&phba->hbalock);
11538 		/* Notify aborted XRI for FCP work queue */
11539 		lpfc_sli4_fcp_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
11540 		/* Free the event processed back to the free pool */
11541 		lpfc_sli4_cq_event_release(phba, cq_event);
11542 	}
11543 }
11544 
11545 /**
11546  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
11547  * @phba: pointer to lpfc hba data structure.
11548  *
11549  * This routine is invoked by the worker thread to process all the pending
11550  * SLI4 els abort xri events.
11551  **/
11552 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
11553 {
11554 	struct lpfc_cq_event *cq_event;
11555 
11556 	/* First, declare the els xri abort event has been handled */
11557 	spin_lock_irq(&phba->hbalock);
11558 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
11559 	spin_unlock_irq(&phba->hbalock);
11560 	/* Now, handle all the els xri abort events */
11561 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
11562 		/* Get the first event from the head of the event queue */
11563 		spin_lock_irq(&phba->hbalock);
11564 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
11565 				 cq_event, struct lpfc_cq_event, list);
11566 		spin_unlock_irq(&phba->hbalock);
11567 		/* Notify aborted XRI for ELS work queue */
11568 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
11569 		/* Free the event processed back to the free pool */
11570 		lpfc_sli4_cq_event_release(phba, cq_event);
11571 	}
11572 }
11573 
11574 /**
11575  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
11576  * @phba: pointer to lpfc hba data structure
11577  * @pIocbIn: pointer to the rspiocbq
11578  * @pIocbOut: pointer to the cmdiocbq
11579  * @wcqe: pointer to the complete wcqe
11580  *
11581  * This routine transfers the fields of a command iocbq to a response iocbq
11582  * by copying all the IOCB fields from command iocbq and transferring the
11583  * completion status information from the complete wcqe.
11584  **/
11585 static void
11586 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
11587 			      struct lpfc_iocbq *pIocbIn,
11588 			      struct lpfc_iocbq *pIocbOut,
11589 			      struct lpfc_wcqe_complete *wcqe)
11590 {
11591 	int numBdes, i;
11592 	unsigned long iflags;
11593 	uint32_t status, max_response;
11594 	struct lpfc_dmabuf *dmabuf;
11595 	struct ulp_bde64 *bpl, bde;
11596 	size_t offset = offsetof(struct lpfc_iocbq, iocb);
11597 
11598 	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
11599 	       sizeof(struct lpfc_iocbq) - offset);
11600 	/* Map WCQE parameters into irspiocb parameters */
11601 	status = bf_get(lpfc_wcqe_c_status, wcqe);
11602 	pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
11603 	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
11604 		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
11605 			pIocbIn->iocb.un.fcpi.fcpi_parm =
11606 					pIocbOut->iocb.un.fcpi.fcpi_parm -
11607 					wcqe->total_data_placed;
11608 		else
11609 			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
11610 	else {
11611 		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
11612 		switch (pIocbOut->iocb.ulpCommand) {
11613 		case CMD_ELS_REQUEST64_CR:
11614 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
11615 			bpl  = (struct ulp_bde64 *)dmabuf->virt;
11616 			bde.tus.w = le32_to_cpu(bpl[1].tus.w);
11617 			max_response = bde.tus.f.bdeSize;
11618 			break;
11619 		case CMD_GEN_REQUEST64_CR:
11620 			max_response = 0;
11621 			if (!pIocbOut->context3)
11622 				break;
11623 			numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
11624 					sizeof(struct ulp_bde64);
11625 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
11626 			bpl = (struct ulp_bde64 *)dmabuf->virt;
11627 			for (i = 0; i < numBdes; i++) {
11628 				bde.tus.w = le32_to_cpu(bpl[i].tus.w);
11629 				if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
11630 					max_response += bde.tus.f.bdeSize;
11631 			}
11632 			break;
11633 		default:
11634 			max_response = wcqe->total_data_placed;
11635 			break;
11636 		}
11637 		if (max_response < wcqe->total_data_placed)
11638 			pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
11639 		else
11640 			pIocbIn->iocb.un.genreq64.bdl.bdeSize =
11641 				wcqe->total_data_placed;
11642 	}
11643 
11644 	/* Convert BG errors for completion status */
11645 	if (status == CQE_STATUS_DI_ERROR) {
11646 		pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
11647 
11648 		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
11649 			pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
11650 		else
11651 			pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
11652 
11653 		pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
11654 		if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
11655 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11656 				BGS_GUARD_ERR_MASK;
11657 		if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
11658 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11659 				BGS_APPTAG_ERR_MASK;
11660 		if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
11661 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11662 				BGS_REFTAG_ERR_MASK;
11663 
11664 		/* Check to see if there was any good data before the error */
11665 		if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
11666 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11667 				BGS_HI_WATER_MARK_PRESENT_MASK;
11668 			pIocbIn->iocb.unsli3.sli3_bg.bghm =
11669 				wcqe->total_data_placed;
11670 		}
11671 
11672 		/*
11673 		* Set ALL the error bits to indicate we don't know what
11674 		* type of error it is.
11675 		*/
11676 		if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
11677 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11678 				(BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
11679 				BGS_GUARD_ERR_MASK);
11680 	}
11681 
11682 	/* Pick up HBA exchange busy condition */
11683 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
11684 		spin_lock_irqsave(&phba->hbalock, iflags);
11685 		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
11686 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11687 	}
11688 }
11689 
11690 /**
11691  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
11692  * @phba: Pointer to HBA context object.
11693  * @wcqe: Pointer to work-queue completion queue entry.
11694  *
11695  * This routine handles an ELS work-queue completion event and construct
11696  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
11697  * discovery engine to handle.
11698  *
11699  * Return: Pointer to the receive IOCBQ, NULL otherwise.
11700  **/
11701 static struct lpfc_iocbq *
11702 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
11703 			       struct lpfc_iocbq *irspiocbq)
11704 {
11705 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
11706 	struct lpfc_iocbq *cmdiocbq;
11707 	struct lpfc_wcqe_complete *wcqe;
11708 	unsigned long iflags;
11709 
11710 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
11711 	spin_lock_irqsave(&pring->ring_lock, iflags);
11712 	pring->stats.iocb_event++;
11713 	/* Look up the ELS command IOCB and create pseudo response IOCB */
11714 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
11715 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
11716 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
11717 
11718 	if (unlikely(!cmdiocbq)) {
11719 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11720 				"0386 ELS complete with no corresponding "
11721 				"cmdiocb: iotag (%d)\n",
11722 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
11723 		lpfc_sli_release_iocbq(phba, irspiocbq);
11724 		return NULL;
11725 	}
11726 
11727 	/* Fake the irspiocbq and copy necessary response information */
11728 	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
11729 
11730 	return irspiocbq;
11731 }
11732 
11733 /**
11734  * lpfc_sli4_sp_handle_async_event - Handle an asynchroous event
11735  * @phba: Pointer to HBA context object.
11736  * @cqe: Pointer to mailbox completion queue entry.
11737  *
11738  * This routine process a mailbox completion queue entry with asynchrous
11739  * event.
11740  *
11741  * Return: true if work posted to worker thread, otherwise false.
11742  **/
11743 static bool
11744 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
11745 {
11746 	struct lpfc_cq_event *cq_event;
11747 	unsigned long iflags;
11748 
11749 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11750 			"0392 Async Event: word0:x%x, word1:x%x, "
11751 			"word2:x%x, word3:x%x\n", mcqe->word0,
11752 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
11753 
11754 	/* Allocate a new internal CQ_EVENT entry */
11755 	cq_event = lpfc_sli4_cq_event_alloc(phba);
11756 	if (!cq_event) {
11757 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11758 				"0394 Failed to allocate CQ_EVENT entry\n");
11759 		return false;
11760 	}
11761 
11762 	/* Move the CQE into an asynchronous event entry */
11763 	memcpy(&cq_event->cqe, mcqe, sizeof(struct lpfc_mcqe));
11764 	spin_lock_irqsave(&phba->hbalock, iflags);
11765 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
11766 	/* Set the async event flag */
11767 	phba->hba_flag |= ASYNC_EVENT;
11768 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11769 
11770 	return true;
11771 }
11772 
11773 /**
11774  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
11775  * @phba: Pointer to HBA context object.
11776  * @cqe: Pointer to mailbox completion queue entry.
11777  *
11778  * This routine process a mailbox completion queue entry with mailbox
11779  * completion event.
11780  *
11781  * Return: true if work posted to worker thread, otherwise false.
11782  **/
11783 static bool
11784 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
11785 {
11786 	uint32_t mcqe_status;
11787 	MAILBOX_t *mbox, *pmbox;
11788 	struct lpfc_mqe *mqe;
11789 	struct lpfc_vport *vport;
11790 	struct lpfc_nodelist *ndlp;
11791 	struct lpfc_dmabuf *mp;
11792 	unsigned long iflags;
11793 	LPFC_MBOXQ_t *pmb;
11794 	bool workposted = false;
11795 	int rc;
11796 
11797 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
11798 	if (!bf_get(lpfc_trailer_completed, mcqe))
11799 		goto out_no_mqe_complete;
11800 
11801 	/* Get the reference to the active mbox command */
11802 	spin_lock_irqsave(&phba->hbalock, iflags);
11803 	pmb = phba->sli.mbox_active;
11804 	if (unlikely(!pmb)) {
11805 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
11806 				"1832 No pending MBOX command to handle\n");
11807 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11808 		goto out_no_mqe_complete;
11809 	}
11810 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11811 	mqe = &pmb->u.mqe;
11812 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
11813 	mbox = phba->mbox;
11814 	vport = pmb->vport;
11815 
11816 	/* Reset heartbeat timer */
11817 	phba->last_completion_time = jiffies;
11818 	del_timer(&phba->sli.mbox_tmo);
11819 
11820 	/* Move mbox data to caller's mailbox region, do endian swapping */
11821 	if (pmb->mbox_cmpl && mbox)
11822 		lpfc_sli_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
11823 
11824 	/*
11825 	 * For mcqe errors, conditionally move a modified error code to
11826 	 * the mbox so that the error will not be missed.
11827 	 */
11828 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
11829 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
11830 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
11831 			bf_set(lpfc_mqe_status, mqe,
11832 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
11833 	}
11834 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
11835 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
11836 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
11837 				      "MBOX dflt rpi: status:x%x rpi:x%x",
11838 				      mcqe_status,
11839 				      pmbox->un.varWords[0], 0);
11840 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
11841 			mp = (struct lpfc_dmabuf *)(pmb->context1);
11842 			ndlp = (struct lpfc_nodelist *)pmb->context2;
11843 			/* Reg_LOGIN of dflt RPI was successful. Now lets get
11844 			 * RID of the PPI using the same mbox buffer.
11845 			 */
11846 			lpfc_unreg_login(phba, vport->vpi,
11847 					 pmbox->un.varWords[0], pmb);
11848 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
11849 			pmb->context1 = mp;
11850 			pmb->context2 = ndlp;
11851 			pmb->vport = vport;
11852 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
11853 			if (rc != MBX_BUSY)
11854 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11855 						LOG_SLI, "0385 rc should "
11856 						"have been MBX_BUSY\n");
11857 			if (rc != MBX_NOT_FINISHED)
11858 				goto send_current_mbox;
11859 		}
11860 	}
11861 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
11862 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
11863 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
11864 
11865 	/* There is mailbox completion work to do */
11866 	spin_lock_irqsave(&phba->hbalock, iflags);
11867 	__lpfc_mbox_cmpl_put(phba, pmb);
11868 	phba->work_ha |= HA_MBATT;
11869 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11870 	workposted = true;
11871 
11872 send_current_mbox:
11873 	spin_lock_irqsave(&phba->hbalock, iflags);
11874 	/* Release the mailbox command posting token */
11875 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11876 	/* Setting active mailbox pointer need to be in sync to flag clear */
11877 	phba->sli.mbox_active = NULL;
11878 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11879 	/* Wake up worker thread to post the next pending mailbox command */
11880 	lpfc_worker_wake_up(phba);
11881 out_no_mqe_complete:
11882 	if (bf_get(lpfc_trailer_consumed, mcqe))
11883 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
11884 	return workposted;
11885 }
11886 
11887 /**
11888  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
11889  * @phba: Pointer to HBA context object.
11890  * @cqe: Pointer to mailbox completion queue entry.
11891  *
11892  * This routine process a mailbox completion queue entry, it invokes the
11893  * proper mailbox complete handling or asynchrous event handling routine
11894  * according to the MCQE's async bit.
11895  *
11896  * Return: true if work posted to worker thread, otherwise false.
11897  **/
11898 static bool
11899 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_cqe *cqe)
11900 {
11901 	struct lpfc_mcqe mcqe;
11902 	bool workposted;
11903 
11904 	/* Copy the mailbox MCQE and convert endian order as needed */
11905 	lpfc_sli_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
11906 
11907 	/* Invoke the proper event handling routine */
11908 	if (!bf_get(lpfc_trailer_async, &mcqe))
11909 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
11910 	else
11911 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
11912 	return workposted;
11913 }
11914 
11915 /**
11916  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
11917  * @phba: Pointer to HBA context object.
11918  * @cq: Pointer to associated CQ
11919  * @wcqe: Pointer to work-queue completion queue entry.
11920  *
11921  * This routine handles an ELS work-queue completion event.
11922  *
11923  * Return: true if work posted to worker thread, otherwise false.
11924  **/
11925 static bool
11926 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
11927 			     struct lpfc_wcqe_complete *wcqe)
11928 {
11929 	struct lpfc_iocbq *irspiocbq;
11930 	unsigned long iflags;
11931 	struct lpfc_sli_ring *pring = cq->pring;
11932 	int txq_cnt = 0;
11933 	int txcmplq_cnt = 0;
11934 	int fcp_txcmplq_cnt = 0;
11935 
11936 	/* Get an irspiocbq for later ELS response processing use */
11937 	irspiocbq = lpfc_sli_get_iocbq(phba);
11938 	if (!irspiocbq) {
11939 		if (!list_empty(&pring->txq))
11940 			txq_cnt++;
11941 		if (!list_empty(&pring->txcmplq))
11942 			txcmplq_cnt++;
11943 		if (!list_empty(&phba->sli.ring[LPFC_FCP_RING].txcmplq))
11944 			fcp_txcmplq_cnt++;
11945 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11946 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
11947 			"fcp_txcmplq_cnt=%d, els_txcmplq_cnt=%d\n",
11948 			txq_cnt, phba->iocb_cnt,
11949 			fcp_txcmplq_cnt,
11950 			txcmplq_cnt);
11951 		return false;
11952 	}
11953 
11954 	/* Save off the slow-path queue event for work thread to process */
11955 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
11956 	spin_lock_irqsave(&phba->hbalock, iflags);
11957 	list_add_tail(&irspiocbq->cq_event.list,
11958 		      &phba->sli4_hba.sp_queue_event);
11959 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
11960 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11961 
11962 	return true;
11963 }
11964 
11965 /**
11966  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
11967  * @phba: Pointer to HBA context object.
11968  * @wcqe: Pointer to work-queue completion queue entry.
11969  *
11970  * This routine handles slow-path WQ entry comsumed event by invoking the
11971  * proper WQ release routine to the slow-path WQ.
11972  **/
11973 static void
11974 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
11975 			     struct lpfc_wcqe_release *wcqe)
11976 {
11977 	/* sanity check on queue memory */
11978 	if (unlikely(!phba->sli4_hba.els_wq))
11979 		return;
11980 	/* Check for the slow-path ELS work queue */
11981 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
11982 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
11983 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
11984 	else
11985 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11986 				"2579 Slow-path wqe consume event carries "
11987 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
11988 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
11989 				phba->sli4_hba.els_wq->queue_id);
11990 }
11991 
11992 /**
11993  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
11994  * @phba: Pointer to HBA context object.
11995  * @cq: Pointer to a WQ completion queue.
11996  * @wcqe: Pointer to work-queue completion queue entry.
11997  *
11998  * This routine handles an XRI abort event.
11999  *
12000  * Return: true if work posted to worker thread, otherwise false.
12001  **/
12002 static bool
12003 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
12004 				   struct lpfc_queue *cq,
12005 				   struct sli4_wcqe_xri_aborted *wcqe)
12006 {
12007 	bool workposted = false;
12008 	struct lpfc_cq_event *cq_event;
12009 	unsigned long iflags;
12010 
12011 	/* Allocate a new internal CQ_EVENT entry */
12012 	cq_event = lpfc_sli4_cq_event_alloc(phba);
12013 	if (!cq_event) {
12014 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12015 				"0602 Failed to allocate CQ_EVENT entry\n");
12016 		return false;
12017 	}
12018 
12019 	/* Move the CQE into the proper xri abort event list */
12020 	memcpy(&cq_event->cqe, wcqe, sizeof(struct sli4_wcqe_xri_aborted));
12021 	switch (cq->subtype) {
12022 	case LPFC_FCP:
12023 		spin_lock_irqsave(&phba->hbalock, iflags);
12024 		list_add_tail(&cq_event->list,
12025 			      &phba->sli4_hba.sp_fcp_xri_aborted_work_queue);
12026 		/* Set the fcp xri abort event flag */
12027 		phba->hba_flag |= FCP_XRI_ABORT_EVENT;
12028 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12029 		workposted = true;
12030 		break;
12031 	case LPFC_ELS:
12032 		spin_lock_irqsave(&phba->hbalock, iflags);
12033 		list_add_tail(&cq_event->list,
12034 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
12035 		/* Set the els xri abort event flag */
12036 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
12037 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12038 		workposted = true;
12039 		break;
12040 	default:
12041 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12042 				"0603 Invalid work queue CQE subtype (x%x)\n",
12043 				cq->subtype);
12044 		workposted = false;
12045 		break;
12046 	}
12047 	return workposted;
12048 }
12049 
12050 /**
12051  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
12052  * @phba: Pointer to HBA context object.
12053  * @rcqe: Pointer to receive-queue completion queue entry.
12054  *
12055  * This routine process a receive-queue completion queue entry.
12056  *
12057  * Return: true if work posted to worker thread, otherwise false.
12058  **/
12059 static bool
12060 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
12061 {
12062 	bool workposted = false;
12063 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
12064 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
12065 	struct hbq_dmabuf *dma_buf;
12066 	uint32_t status, rq_id;
12067 	unsigned long iflags;
12068 
12069 	/* sanity check on queue memory */
12070 	if (unlikely(!hrq) || unlikely(!drq))
12071 		return workposted;
12072 
12073 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
12074 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
12075 	else
12076 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
12077 	if (rq_id != hrq->queue_id)
12078 		goto out;
12079 
12080 	status = bf_get(lpfc_rcqe_status, rcqe);
12081 	switch (status) {
12082 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
12083 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12084 				"2537 Receive Frame Truncated!!\n");
12085 		hrq->RQ_buf_trunc++;
12086 	case FC_STATUS_RQ_SUCCESS:
12087 		lpfc_sli4_rq_release(hrq, drq);
12088 		spin_lock_irqsave(&phba->hbalock, iflags);
12089 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
12090 		if (!dma_buf) {
12091 			hrq->RQ_no_buf_found++;
12092 			spin_unlock_irqrestore(&phba->hbalock, iflags);
12093 			goto out;
12094 		}
12095 		hrq->RQ_rcv_buf++;
12096 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
12097 		/* save off the frame for the word thread to process */
12098 		list_add_tail(&dma_buf->cq_event.list,
12099 			      &phba->sli4_hba.sp_queue_event);
12100 		/* Frame received */
12101 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
12102 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12103 		workposted = true;
12104 		break;
12105 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
12106 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
12107 		hrq->RQ_no_posted_buf++;
12108 		/* Post more buffers if possible */
12109 		spin_lock_irqsave(&phba->hbalock, iflags);
12110 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
12111 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12112 		workposted = true;
12113 		break;
12114 	}
12115 out:
12116 	return workposted;
12117 }
12118 
12119 /**
12120  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
12121  * @phba: Pointer to HBA context object.
12122  * @cq: Pointer to the completion queue.
12123  * @wcqe: Pointer to a completion queue entry.
12124  *
12125  * This routine process a slow-path work-queue or receive queue completion queue
12126  * entry.
12127  *
12128  * Return: true if work posted to worker thread, otherwise false.
12129  **/
12130 static bool
12131 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12132 			 struct lpfc_cqe *cqe)
12133 {
12134 	struct lpfc_cqe cqevt;
12135 	bool workposted = false;
12136 
12137 	/* Copy the work queue CQE and convert endian order if needed */
12138 	lpfc_sli_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
12139 
12140 	/* Check and process for different type of WCQE and dispatch */
12141 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
12142 	case CQE_CODE_COMPL_WQE:
12143 		/* Process the WQ/RQ complete event */
12144 		phba->last_completion_time = jiffies;
12145 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
12146 				(struct lpfc_wcqe_complete *)&cqevt);
12147 		break;
12148 	case CQE_CODE_RELEASE_WQE:
12149 		/* Process the WQ release event */
12150 		lpfc_sli4_sp_handle_rel_wcqe(phba,
12151 				(struct lpfc_wcqe_release *)&cqevt);
12152 		break;
12153 	case CQE_CODE_XRI_ABORTED:
12154 		/* Process the WQ XRI abort event */
12155 		phba->last_completion_time = jiffies;
12156 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
12157 				(struct sli4_wcqe_xri_aborted *)&cqevt);
12158 		break;
12159 	case CQE_CODE_RECEIVE:
12160 	case CQE_CODE_RECEIVE_V1:
12161 		/* Process the RQ event */
12162 		phba->last_completion_time = jiffies;
12163 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
12164 				(struct lpfc_rcqe *)&cqevt);
12165 		break;
12166 	default:
12167 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12168 				"0388 Not a valid WCQE code: x%x\n",
12169 				bf_get(lpfc_cqe_code, &cqevt));
12170 		break;
12171 	}
12172 	return workposted;
12173 }
12174 
12175 /**
12176  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
12177  * @phba: Pointer to HBA context object.
12178  * @eqe: Pointer to fast-path event queue entry.
12179  *
12180  * This routine process a event queue entry from the slow-path event queue.
12181  * It will check the MajorCode and MinorCode to determine this is for a
12182  * completion event on a completion queue, if not, an error shall be logged
12183  * and just return. Otherwise, it will get to the corresponding completion
12184  * queue and process all the entries on that completion queue, rearm the
12185  * completion queue, and then return.
12186  *
12187  **/
12188 static void
12189 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
12190 	struct lpfc_queue *speq)
12191 {
12192 	struct lpfc_queue *cq = NULL, *childq;
12193 	struct lpfc_cqe *cqe;
12194 	bool workposted = false;
12195 	int ecount = 0;
12196 	uint16_t cqid;
12197 
12198 	/* Get the reference to the corresponding CQ */
12199 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
12200 
12201 	list_for_each_entry(childq, &speq->child_list, list) {
12202 		if (childq->queue_id == cqid) {
12203 			cq = childq;
12204 			break;
12205 		}
12206 	}
12207 	if (unlikely(!cq)) {
12208 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
12209 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12210 					"0365 Slow-path CQ identifier "
12211 					"(%d) does not exist\n", cqid);
12212 		return;
12213 	}
12214 
12215 	/* Process all the entries to the CQ */
12216 	switch (cq->type) {
12217 	case LPFC_MCQ:
12218 		while ((cqe = lpfc_sli4_cq_get(cq))) {
12219 			workposted |= lpfc_sli4_sp_handle_mcqe(phba, cqe);
12220 			if (!(++ecount % cq->entry_repost))
12221 				lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12222 			cq->CQ_mbox++;
12223 		}
12224 		break;
12225 	case LPFC_WCQ:
12226 		while ((cqe = lpfc_sli4_cq_get(cq))) {
12227 			if (cq->subtype == LPFC_FCP)
12228 				workposted |= lpfc_sli4_fp_handle_wcqe(phba, cq,
12229 								       cqe);
12230 			else
12231 				workposted |= lpfc_sli4_sp_handle_cqe(phba, cq,
12232 								      cqe);
12233 			if (!(++ecount % cq->entry_repost))
12234 				lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12235 		}
12236 
12237 		/* Track the max number of CQEs processed in 1 EQ */
12238 		if (ecount > cq->CQ_max_cqe)
12239 			cq->CQ_max_cqe = ecount;
12240 		break;
12241 	default:
12242 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12243 				"0370 Invalid completion queue type (%d)\n",
12244 				cq->type);
12245 		return;
12246 	}
12247 
12248 	/* Catch the no cq entry condition, log an error */
12249 	if (unlikely(ecount == 0))
12250 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12251 				"0371 No entry from the CQ: identifier "
12252 				"(x%x), type (%d)\n", cq->queue_id, cq->type);
12253 
12254 	/* In any case, flash and re-arm the RCQ */
12255 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
12256 
12257 	/* wake up worker thread if there are works to be done */
12258 	if (workposted)
12259 		lpfc_worker_wake_up(phba);
12260 }
12261 
12262 /**
12263  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
12264  * @phba: Pointer to HBA context object.
12265  * @cq: Pointer to associated CQ
12266  * @wcqe: Pointer to work-queue completion queue entry.
12267  *
12268  * This routine process a fast-path work queue completion entry from fast-path
12269  * event queue for FCP command response completion.
12270  **/
12271 static void
12272 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12273 			     struct lpfc_wcqe_complete *wcqe)
12274 {
12275 	struct lpfc_sli_ring *pring = cq->pring;
12276 	struct lpfc_iocbq *cmdiocbq;
12277 	struct lpfc_iocbq irspiocbq;
12278 	unsigned long iflags;
12279 
12280 	/* Check for response status */
12281 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
12282 		/* If resource errors reported from HBA, reduce queue
12283 		 * depth of the SCSI device.
12284 		 */
12285 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
12286 		     IOSTAT_LOCAL_REJECT)) &&
12287 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
12288 		     IOERR_NO_RESOURCES))
12289 			phba->lpfc_rampdown_queue_depth(phba);
12290 
12291 		/* Log the error status */
12292 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12293 				"0373 FCP complete error: status=x%x, "
12294 				"hw_status=x%x, total_data_specified=%d, "
12295 				"parameter=x%x, word3=x%x\n",
12296 				bf_get(lpfc_wcqe_c_status, wcqe),
12297 				bf_get(lpfc_wcqe_c_hw_status, wcqe),
12298 				wcqe->total_data_placed, wcqe->parameter,
12299 				wcqe->word3);
12300 	}
12301 
12302 	/* Look up the FCP command IOCB and create pseudo response IOCB */
12303 	spin_lock_irqsave(&pring->ring_lock, iflags);
12304 	pring->stats.iocb_event++;
12305 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
12306 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12307 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
12308 	if (unlikely(!cmdiocbq)) {
12309 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12310 				"0374 FCP complete with no corresponding "
12311 				"cmdiocb: iotag (%d)\n",
12312 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12313 		return;
12314 	}
12315 	if (unlikely(!cmdiocbq->iocb_cmpl)) {
12316 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12317 				"0375 FCP cmdiocb not callback function "
12318 				"iotag: (%d)\n",
12319 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12320 		return;
12321 	}
12322 
12323 	/* Fake the irspiocb and copy necessary response information */
12324 	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
12325 
12326 	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
12327 		spin_lock_irqsave(&phba->hbalock, iflags);
12328 		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
12329 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12330 	}
12331 
12332 	/* Pass the cmd_iocb and the rsp state to the upper layer */
12333 	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
12334 }
12335 
12336 /**
12337  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
12338  * @phba: Pointer to HBA context object.
12339  * @cq: Pointer to completion queue.
12340  * @wcqe: Pointer to work-queue completion queue entry.
12341  *
12342  * This routine handles an fast-path WQ entry comsumed event by invoking the
12343  * proper WQ release routine to the slow-path WQ.
12344  **/
12345 static void
12346 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12347 			     struct lpfc_wcqe_release *wcqe)
12348 {
12349 	struct lpfc_queue *childwq;
12350 	bool wqid_matched = false;
12351 	uint16_t fcp_wqid;
12352 
12353 	/* Check for fast-path FCP work queue release */
12354 	fcp_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
12355 	list_for_each_entry(childwq, &cq->child_list, list) {
12356 		if (childwq->queue_id == fcp_wqid) {
12357 			lpfc_sli4_wq_release(childwq,
12358 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
12359 			wqid_matched = true;
12360 			break;
12361 		}
12362 	}
12363 	/* Report warning log message if no match found */
12364 	if (wqid_matched != true)
12365 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12366 				"2580 Fast-path wqe consume event carries "
12367 				"miss-matched qid: wcqe-qid=x%x\n", fcp_wqid);
12368 }
12369 
12370 /**
12371  * lpfc_sli4_fp_handle_wcqe - Process fast-path work queue completion entry
12372  * @cq: Pointer to the completion queue.
12373  * @eqe: Pointer to fast-path completion queue entry.
12374  *
12375  * This routine process a fast-path work queue completion entry from fast-path
12376  * event queue for FCP command response completion.
12377  **/
12378 static int
12379 lpfc_sli4_fp_handle_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12380 			 struct lpfc_cqe *cqe)
12381 {
12382 	struct lpfc_wcqe_release wcqe;
12383 	bool workposted = false;
12384 
12385 	/* Copy the work queue CQE and convert endian order if needed */
12386 	lpfc_sli_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
12387 
12388 	/* Check and process for different type of WCQE and dispatch */
12389 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
12390 	case CQE_CODE_COMPL_WQE:
12391 		cq->CQ_wq++;
12392 		/* Process the WQ complete event */
12393 		phba->last_completion_time = jiffies;
12394 		lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
12395 				(struct lpfc_wcqe_complete *)&wcqe);
12396 		break;
12397 	case CQE_CODE_RELEASE_WQE:
12398 		cq->CQ_release_wqe++;
12399 		/* Process the WQ release event */
12400 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
12401 				(struct lpfc_wcqe_release *)&wcqe);
12402 		break;
12403 	case CQE_CODE_XRI_ABORTED:
12404 		cq->CQ_xri_aborted++;
12405 		/* Process the WQ XRI abort event */
12406 		phba->last_completion_time = jiffies;
12407 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
12408 				(struct sli4_wcqe_xri_aborted *)&wcqe);
12409 		break;
12410 	default:
12411 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12412 				"0144 Not a valid WCQE code: x%x\n",
12413 				bf_get(lpfc_wcqe_c_code, &wcqe));
12414 		break;
12415 	}
12416 	return workposted;
12417 }
12418 
12419 /**
12420  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
12421  * @phba: Pointer to HBA context object.
12422  * @eqe: Pointer to fast-path event queue entry.
12423  *
12424  * This routine process a event queue entry from the fast-path event queue.
12425  * It will check the MajorCode and MinorCode to determine this is for a
12426  * completion event on a completion queue, if not, an error shall be logged
12427  * and just return. Otherwise, it will get to the corresponding completion
12428  * queue and process all the entries on the completion queue, rearm the
12429  * completion queue, and then return.
12430  **/
12431 static void
12432 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
12433 			uint32_t qidx)
12434 {
12435 	struct lpfc_queue *cq;
12436 	struct lpfc_cqe *cqe;
12437 	bool workposted = false;
12438 	uint16_t cqid;
12439 	int ecount = 0;
12440 
12441 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
12442 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12443 				"0366 Not a valid completion "
12444 				"event: majorcode=x%x, minorcode=x%x\n",
12445 				bf_get_le32(lpfc_eqe_major_code, eqe),
12446 				bf_get_le32(lpfc_eqe_minor_code, eqe));
12447 		return;
12448 	}
12449 
12450 	/* Get the reference to the corresponding CQ */
12451 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
12452 
12453 	/* Check if this is a Slow path event */
12454 	if (unlikely(cqid != phba->sli4_hba.fcp_cq_map[qidx])) {
12455 		lpfc_sli4_sp_handle_eqe(phba, eqe,
12456 			phba->sli4_hba.hba_eq[qidx]);
12457 		return;
12458 	}
12459 
12460 	if (unlikely(!phba->sli4_hba.fcp_cq)) {
12461 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12462 				"3146 Fast-path completion queues "
12463 				"does not exist\n");
12464 		return;
12465 	}
12466 	cq = phba->sli4_hba.fcp_cq[qidx];
12467 	if (unlikely(!cq)) {
12468 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
12469 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12470 					"0367 Fast-path completion queue "
12471 					"(%d) does not exist\n", qidx);
12472 		return;
12473 	}
12474 
12475 	if (unlikely(cqid != cq->queue_id)) {
12476 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12477 				"0368 Miss-matched fast-path completion "
12478 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
12479 				cqid, cq->queue_id);
12480 		return;
12481 	}
12482 
12483 	/* Process all the entries to the CQ */
12484 	while ((cqe = lpfc_sli4_cq_get(cq))) {
12485 		workposted |= lpfc_sli4_fp_handle_wcqe(phba, cq, cqe);
12486 		if (!(++ecount % cq->entry_repost))
12487 			lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12488 	}
12489 
12490 	/* Track the max number of CQEs processed in 1 EQ */
12491 	if (ecount > cq->CQ_max_cqe)
12492 		cq->CQ_max_cqe = ecount;
12493 
12494 	/* Catch the no cq entry condition */
12495 	if (unlikely(ecount == 0))
12496 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12497 				"0369 No entry from fast-path completion "
12498 				"queue fcpcqid=%d\n", cq->queue_id);
12499 
12500 	/* In any case, flash and re-arm the CQ */
12501 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
12502 
12503 	/* wake up worker thread if there are works to be done */
12504 	if (workposted)
12505 		lpfc_worker_wake_up(phba);
12506 }
12507 
12508 static void
12509 lpfc_sli4_eq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
12510 {
12511 	struct lpfc_eqe *eqe;
12512 
12513 	/* walk all the EQ entries and drop on the floor */
12514 	while ((eqe = lpfc_sli4_eq_get(eq)))
12515 		;
12516 
12517 	/* Clear and re-arm the EQ */
12518 	lpfc_sli4_eq_release(eq, LPFC_QUEUE_REARM);
12519 }
12520 
12521 
12522 /**
12523  * lpfc_sli4_fof_handle_eqe - Process a Flash Optimized Fabric event queue
12524  *			     entry
12525  * @phba: Pointer to HBA context object.
12526  * @eqe: Pointer to fast-path event queue entry.
12527  *
12528  * This routine process a event queue entry from the Flash Optimized Fabric
12529  * event queue.  It will check the MajorCode and MinorCode to determine this
12530  * is for a completion event on a completion queue, if not, an error shall be
12531  * logged and just return. Otherwise, it will get to the corresponding
12532  * completion queue and process all the entries on the completion queue, rearm
12533  * the completion queue, and then return.
12534  **/
12535 static void
12536 lpfc_sli4_fof_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe)
12537 {
12538 	struct lpfc_queue *cq;
12539 	struct lpfc_cqe *cqe;
12540 	bool workposted = false;
12541 	uint16_t cqid;
12542 	int ecount = 0;
12543 
12544 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
12545 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12546 				"9147 Not a valid completion "
12547 				"event: majorcode=x%x, minorcode=x%x\n",
12548 				bf_get_le32(lpfc_eqe_major_code, eqe),
12549 				bf_get_le32(lpfc_eqe_minor_code, eqe));
12550 		return;
12551 	}
12552 
12553 	/* Get the reference to the corresponding CQ */
12554 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
12555 
12556 	/* Next check for OAS */
12557 	cq = phba->sli4_hba.oas_cq;
12558 	if (unlikely(!cq)) {
12559 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
12560 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12561 					"9148 OAS completion queue "
12562 					"does not exist\n");
12563 		return;
12564 	}
12565 
12566 	if (unlikely(cqid != cq->queue_id)) {
12567 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12568 				"9149 Miss-matched fast-path compl "
12569 				"queue id: eqcqid=%d, fcpcqid=%d\n",
12570 				cqid, cq->queue_id);
12571 		return;
12572 	}
12573 
12574 	/* Process all the entries to the OAS CQ */
12575 	while ((cqe = lpfc_sli4_cq_get(cq))) {
12576 		workposted |= lpfc_sli4_fp_handle_wcqe(phba, cq, cqe);
12577 		if (!(++ecount % cq->entry_repost))
12578 			lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12579 	}
12580 
12581 	/* Track the max number of CQEs processed in 1 EQ */
12582 	if (ecount > cq->CQ_max_cqe)
12583 		cq->CQ_max_cqe = ecount;
12584 
12585 	/* Catch the no cq entry condition */
12586 	if (unlikely(ecount == 0))
12587 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12588 				"9153 No entry from fast-path completion "
12589 				"queue fcpcqid=%d\n", cq->queue_id);
12590 
12591 	/* In any case, flash and re-arm the CQ */
12592 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
12593 
12594 	/* wake up worker thread if there are works to be done */
12595 	if (workposted)
12596 		lpfc_worker_wake_up(phba);
12597 }
12598 
12599 /**
12600  * lpfc_sli4_fof_intr_handler - HBA interrupt handler to SLI-4 device
12601  * @irq: Interrupt number.
12602  * @dev_id: The device context pointer.
12603  *
12604  * This function is directly called from the PCI layer as an interrupt
12605  * service routine when device with SLI-4 interface spec is enabled with
12606  * MSI-X multi-message interrupt mode and there is a Flash Optimized Fabric
12607  * IOCB ring event in the HBA. However, when the device is enabled with either
12608  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
12609  * device-level interrupt handler. When the PCI slot is in error recovery
12610  * or the HBA is undergoing initialization, the interrupt handler will not
12611  * process the interrupt. The Flash Optimized Fabric ring event are handled in
12612  * the intrrupt context. This function is called without any lock held.
12613  * It gets the hbalock to access and update SLI data structures. Note that,
12614  * the EQ to CQ are one-to-one map such that the EQ index is
12615  * equal to that of CQ index.
12616  *
12617  * This function returns IRQ_HANDLED when interrupt is handled else it
12618  * returns IRQ_NONE.
12619  **/
12620 irqreturn_t
12621 lpfc_sli4_fof_intr_handler(int irq, void *dev_id)
12622 {
12623 	struct lpfc_hba *phba;
12624 	struct lpfc_fcp_eq_hdl *fcp_eq_hdl;
12625 	struct lpfc_queue *eq;
12626 	struct lpfc_eqe *eqe;
12627 	unsigned long iflag;
12628 	int ecount = 0;
12629 
12630 	/* Get the driver's phba structure from the dev_id */
12631 	fcp_eq_hdl = (struct lpfc_fcp_eq_hdl *)dev_id;
12632 	phba = fcp_eq_hdl->phba;
12633 
12634 	if (unlikely(!phba))
12635 		return IRQ_NONE;
12636 
12637 	/* Get to the EQ struct associated with this vector */
12638 	eq = phba->sli4_hba.fof_eq;
12639 	if (unlikely(!eq))
12640 		return IRQ_NONE;
12641 
12642 	/* Check device state for handling interrupt */
12643 	if (unlikely(lpfc_intr_state_check(phba))) {
12644 		eq->EQ_badstate++;
12645 		/* Check again for link_state with lock held */
12646 		spin_lock_irqsave(&phba->hbalock, iflag);
12647 		if (phba->link_state < LPFC_LINK_DOWN)
12648 			/* Flush, clear interrupt, and rearm the EQ */
12649 			lpfc_sli4_eq_flush(phba, eq);
12650 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12651 		return IRQ_NONE;
12652 	}
12653 
12654 	/*
12655 	 * Process all the event on FCP fast-path EQ
12656 	 */
12657 	while ((eqe = lpfc_sli4_eq_get(eq))) {
12658 		lpfc_sli4_fof_handle_eqe(phba, eqe);
12659 		if (!(++ecount % eq->entry_repost))
12660 			lpfc_sli4_eq_release(eq, LPFC_QUEUE_NOARM);
12661 		eq->EQ_processed++;
12662 	}
12663 
12664 	/* Track the max number of EQEs processed in 1 intr */
12665 	if (ecount > eq->EQ_max_eqe)
12666 		eq->EQ_max_eqe = ecount;
12667 
12668 
12669 	if (unlikely(ecount == 0)) {
12670 		eq->EQ_no_entry++;
12671 
12672 		if (phba->intr_type == MSIX)
12673 			/* MSI-X treated interrupt served as no EQ share INT */
12674 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12675 					"9145 MSI-X interrupt with no EQE\n");
12676 		else {
12677 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12678 					"9146 ISR interrupt with no EQE\n");
12679 			/* Non MSI-X treated on interrupt as EQ share INT */
12680 			return IRQ_NONE;
12681 		}
12682 	}
12683 	/* Always clear and re-arm the fast-path EQ */
12684 	lpfc_sli4_eq_release(eq, LPFC_QUEUE_REARM);
12685 	return IRQ_HANDLED;
12686 }
12687 
12688 /**
12689  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
12690  * @irq: Interrupt number.
12691  * @dev_id: The device context pointer.
12692  *
12693  * This function is directly called from the PCI layer as an interrupt
12694  * service routine when device with SLI-4 interface spec is enabled with
12695  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
12696  * ring event in the HBA. However, when the device is enabled with either
12697  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
12698  * device-level interrupt handler. When the PCI slot is in error recovery
12699  * or the HBA is undergoing initialization, the interrupt handler will not
12700  * process the interrupt. The SCSI FCP fast-path ring event are handled in
12701  * the intrrupt context. This function is called without any lock held.
12702  * It gets the hbalock to access and update SLI data structures. Note that,
12703  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
12704  * equal to that of FCP CQ index.
12705  *
12706  * The link attention and ELS ring attention events are handled
12707  * by the worker thread. The interrupt handler signals the worker thread
12708  * and returns for these events. This function is called without any lock
12709  * held. It gets the hbalock to access and update SLI data structures.
12710  *
12711  * This function returns IRQ_HANDLED when interrupt is handled else it
12712  * returns IRQ_NONE.
12713  **/
12714 irqreturn_t
12715 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
12716 {
12717 	struct lpfc_hba *phba;
12718 	struct lpfc_fcp_eq_hdl *fcp_eq_hdl;
12719 	struct lpfc_queue *fpeq;
12720 	struct lpfc_eqe *eqe;
12721 	unsigned long iflag;
12722 	int ecount = 0;
12723 	int fcp_eqidx;
12724 
12725 	/* Get the driver's phba structure from the dev_id */
12726 	fcp_eq_hdl = (struct lpfc_fcp_eq_hdl *)dev_id;
12727 	phba = fcp_eq_hdl->phba;
12728 	fcp_eqidx = fcp_eq_hdl->idx;
12729 
12730 	if (unlikely(!phba))
12731 		return IRQ_NONE;
12732 	if (unlikely(!phba->sli4_hba.hba_eq))
12733 		return IRQ_NONE;
12734 
12735 	/* Get to the EQ struct associated with this vector */
12736 	fpeq = phba->sli4_hba.hba_eq[fcp_eqidx];
12737 	if (unlikely(!fpeq))
12738 		return IRQ_NONE;
12739 
12740 	if (lpfc_fcp_look_ahead) {
12741 		if (atomic_dec_and_test(&fcp_eq_hdl->fcp_eq_in_use))
12742 			lpfc_sli4_eq_clr_intr(fpeq);
12743 		else {
12744 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12745 			return IRQ_NONE;
12746 		}
12747 	}
12748 
12749 	/* Check device state for handling interrupt */
12750 	if (unlikely(lpfc_intr_state_check(phba))) {
12751 		fpeq->EQ_badstate++;
12752 		/* Check again for link_state with lock held */
12753 		spin_lock_irqsave(&phba->hbalock, iflag);
12754 		if (phba->link_state < LPFC_LINK_DOWN)
12755 			/* Flush, clear interrupt, and rearm the EQ */
12756 			lpfc_sli4_eq_flush(phba, fpeq);
12757 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12758 		if (lpfc_fcp_look_ahead)
12759 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12760 		return IRQ_NONE;
12761 	}
12762 
12763 	/*
12764 	 * Process all the event on FCP fast-path EQ
12765 	 */
12766 	while ((eqe = lpfc_sli4_eq_get(fpeq))) {
12767 		if (eqe == NULL)
12768 			break;
12769 
12770 		lpfc_sli4_hba_handle_eqe(phba, eqe, fcp_eqidx);
12771 		if (!(++ecount % fpeq->entry_repost))
12772 			lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_NOARM);
12773 		fpeq->EQ_processed++;
12774 	}
12775 
12776 	/* Track the max number of EQEs processed in 1 intr */
12777 	if (ecount > fpeq->EQ_max_eqe)
12778 		fpeq->EQ_max_eqe = ecount;
12779 
12780 	/* Always clear and re-arm the fast-path EQ */
12781 	lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_REARM);
12782 
12783 	if (unlikely(ecount == 0)) {
12784 		fpeq->EQ_no_entry++;
12785 
12786 		if (lpfc_fcp_look_ahead) {
12787 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12788 			return IRQ_NONE;
12789 		}
12790 
12791 		if (phba->intr_type == MSIX)
12792 			/* MSI-X treated interrupt served as no EQ share INT */
12793 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12794 					"0358 MSI-X interrupt with no EQE\n");
12795 		else
12796 			/* Non MSI-X treated on interrupt as EQ share INT */
12797 			return IRQ_NONE;
12798 	}
12799 
12800 	if (lpfc_fcp_look_ahead)
12801 		atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12802 	return IRQ_HANDLED;
12803 } /* lpfc_sli4_fp_intr_handler */
12804 
12805 /**
12806  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
12807  * @irq: Interrupt number.
12808  * @dev_id: The device context pointer.
12809  *
12810  * This function is the device-level interrupt handler to device with SLI-4
12811  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
12812  * interrupt mode is enabled and there is an event in the HBA which requires
12813  * driver attention. This function invokes the slow-path interrupt attention
12814  * handling function and fast-path interrupt attention handling function in
12815  * turn to process the relevant HBA attention events. This function is called
12816  * without any lock held. It gets the hbalock to access and update SLI data
12817  * structures.
12818  *
12819  * This function returns IRQ_HANDLED when interrupt is handled, else it
12820  * returns IRQ_NONE.
12821  **/
12822 irqreturn_t
12823 lpfc_sli4_intr_handler(int irq, void *dev_id)
12824 {
12825 	struct lpfc_hba  *phba;
12826 	irqreturn_t hba_irq_rc;
12827 	bool hba_handled = false;
12828 	int fcp_eqidx;
12829 
12830 	/* Get the driver's phba structure from the dev_id */
12831 	phba = (struct lpfc_hba *)dev_id;
12832 
12833 	if (unlikely(!phba))
12834 		return IRQ_NONE;
12835 
12836 	/*
12837 	 * Invoke fast-path host attention interrupt handling as appropriate.
12838 	 */
12839 	for (fcp_eqidx = 0; fcp_eqidx < phba->cfg_fcp_io_channel; fcp_eqidx++) {
12840 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
12841 					&phba->sli4_hba.fcp_eq_hdl[fcp_eqidx]);
12842 		if (hba_irq_rc == IRQ_HANDLED)
12843 			hba_handled |= true;
12844 	}
12845 
12846 	if (phba->cfg_fof) {
12847 		hba_irq_rc = lpfc_sli4_fof_intr_handler(irq,
12848 					&phba->sli4_hba.fcp_eq_hdl[0]);
12849 		if (hba_irq_rc == IRQ_HANDLED)
12850 			hba_handled |= true;
12851 	}
12852 
12853 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
12854 } /* lpfc_sli4_intr_handler */
12855 
12856 /**
12857  * lpfc_sli4_queue_free - free a queue structure and associated memory
12858  * @queue: The queue structure to free.
12859  *
12860  * This function frees a queue structure and the DMAable memory used for
12861  * the host resident queue. This function must be called after destroying the
12862  * queue on the HBA.
12863  **/
12864 void
12865 lpfc_sli4_queue_free(struct lpfc_queue *queue)
12866 {
12867 	struct lpfc_dmabuf *dmabuf;
12868 
12869 	if (!queue)
12870 		return;
12871 
12872 	while (!list_empty(&queue->page_list)) {
12873 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
12874 				 list);
12875 		dma_free_coherent(&queue->phba->pcidev->dev, SLI4_PAGE_SIZE,
12876 				  dmabuf->virt, dmabuf->phys);
12877 		kfree(dmabuf);
12878 	}
12879 	kfree(queue);
12880 	return;
12881 }
12882 
12883 /**
12884  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
12885  * @phba: The HBA that this queue is being created on.
12886  * @entry_size: The size of each queue entry for this queue.
12887  * @entry count: The number of entries that this queue will handle.
12888  *
12889  * This function allocates a queue structure and the DMAable memory used for
12890  * the host resident queue. This function must be called before creating the
12891  * queue on the HBA.
12892  **/
12893 struct lpfc_queue *
12894 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t entry_size,
12895 		      uint32_t entry_count)
12896 {
12897 	struct lpfc_queue *queue;
12898 	struct lpfc_dmabuf *dmabuf;
12899 	int x, total_qe_count;
12900 	void *dma_pointer;
12901 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
12902 
12903 	if (!phba->sli4_hba.pc_sli4_params.supported)
12904 		hw_page_size = SLI4_PAGE_SIZE;
12905 
12906 	queue = kzalloc(sizeof(struct lpfc_queue) +
12907 			(sizeof(union sli4_qe) * entry_count), GFP_KERNEL);
12908 	if (!queue)
12909 		return NULL;
12910 	queue->page_count = (ALIGN(entry_size * entry_count,
12911 			hw_page_size))/hw_page_size;
12912 	INIT_LIST_HEAD(&queue->list);
12913 	INIT_LIST_HEAD(&queue->page_list);
12914 	INIT_LIST_HEAD(&queue->child_list);
12915 	for (x = 0, total_qe_count = 0; x < queue->page_count; x++) {
12916 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
12917 		if (!dmabuf)
12918 			goto out_fail;
12919 		dmabuf->virt = dma_zalloc_coherent(&phba->pcidev->dev,
12920 						   hw_page_size, &dmabuf->phys,
12921 						   GFP_KERNEL);
12922 		if (!dmabuf->virt) {
12923 			kfree(dmabuf);
12924 			goto out_fail;
12925 		}
12926 		dmabuf->buffer_tag = x;
12927 		list_add_tail(&dmabuf->list, &queue->page_list);
12928 		/* initialize queue's entry array */
12929 		dma_pointer = dmabuf->virt;
12930 		for (; total_qe_count < entry_count &&
12931 		     dma_pointer < (hw_page_size + dmabuf->virt);
12932 		     total_qe_count++, dma_pointer += entry_size) {
12933 			queue->qe[total_qe_count].address = dma_pointer;
12934 		}
12935 	}
12936 	queue->entry_size = entry_size;
12937 	queue->entry_count = entry_count;
12938 
12939 	/*
12940 	 * entry_repost is calculated based on the number of entries in the
12941 	 * queue. This works out except for RQs. If buffers are NOT initially
12942 	 * posted for every RQE, entry_repost should be adjusted accordingly.
12943 	 */
12944 	queue->entry_repost = (entry_count >> 3);
12945 	if (queue->entry_repost < LPFC_QUEUE_MIN_REPOST)
12946 		queue->entry_repost = LPFC_QUEUE_MIN_REPOST;
12947 	queue->phba = phba;
12948 
12949 	return queue;
12950 out_fail:
12951 	lpfc_sli4_queue_free(queue);
12952 	return NULL;
12953 }
12954 
12955 /**
12956  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
12957  * @phba: HBA structure that indicates port to create a queue on.
12958  * @pci_barset: PCI BAR set flag.
12959  *
12960  * This function shall perform iomap of the specified PCI BAR address to host
12961  * memory address if not already done so and return it. The returned host
12962  * memory address can be NULL.
12963  */
12964 static void __iomem *
12965 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
12966 {
12967 	if (!phba->pcidev)
12968 		return NULL;
12969 
12970 	switch (pci_barset) {
12971 	case WQ_PCI_BAR_0_AND_1:
12972 		return phba->pci_bar0_memmap_p;
12973 	case WQ_PCI_BAR_2_AND_3:
12974 		return phba->pci_bar2_memmap_p;
12975 	case WQ_PCI_BAR_4_AND_5:
12976 		return phba->pci_bar4_memmap_p;
12977 	default:
12978 		break;
12979 	}
12980 	return NULL;
12981 }
12982 
12983 /**
12984  * lpfc_modify_fcp_eq_delay - Modify Delay Multiplier on FCP EQs
12985  * @phba: HBA structure that indicates port to create a queue on.
12986  * @startq: The starting FCP EQ to modify
12987  *
12988  * This function sends an MODIFY_EQ_DELAY mailbox command to the HBA.
12989  *
12990  * The @phba struct is used to send mailbox command to HBA. The @startq
12991  * is used to get the starting FCP EQ to change.
12992  * This function is asynchronous and will wait for the mailbox
12993  * command to finish before continuing.
12994  *
12995  * On success this function will return a zero. If unable to allocate enough
12996  * memory this function will return -ENOMEM. If the queue create mailbox command
12997  * fails this function will return -ENXIO.
12998  **/
12999 int
13000 lpfc_modify_fcp_eq_delay(struct lpfc_hba *phba, uint32_t startq)
13001 {
13002 	struct lpfc_mbx_modify_eq_delay *eq_delay;
13003 	LPFC_MBOXQ_t *mbox;
13004 	struct lpfc_queue *eq;
13005 	int cnt, rc, length, status = 0;
13006 	uint32_t shdr_status, shdr_add_status;
13007 	uint32_t result;
13008 	int fcp_eqidx;
13009 	union lpfc_sli4_cfg_shdr *shdr;
13010 	uint16_t dmult;
13011 
13012 	if (startq >= phba->cfg_fcp_io_channel)
13013 		return 0;
13014 
13015 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13016 	if (!mbox)
13017 		return -ENOMEM;
13018 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
13019 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13020 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13021 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
13022 			 length, LPFC_SLI4_MBX_EMBED);
13023 	eq_delay = &mbox->u.mqe.un.eq_delay;
13024 
13025 	/* Calculate delay multiper from maximum interrupt per second */
13026 	result = phba->cfg_fcp_imax / phba->cfg_fcp_io_channel;
13027 	if (result > LPFC_DMULT_CONST)
13028 		dmult = 0;
13029 	else
13030 		dmult = LPFC_DMULT_CONST/result - 1;
13031 
13032 	cnt = 0;
13033 	for (fcp_eqidx = startq; fcp_eqidx < phba->cfg_fcp_io_channel;
13034 	    fcp_eqidx++) {
13035 		eq = phba->sli4_hba.hba_eq[fcp_eqidx];
13036 		if (!eq)
13037 			continue;
13038 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
13039 		eq_delay->u.request.eq[cnt].phase = 0;
13040 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
13041 		cnt++;
13042 		if (cnt >= LPFC_MAX_EQ_DELAY)
13043 			break;
13044 	}
13045 	eq_delay->u.request.num_eq = cnt;
13046 
13047 	mbox->vport = phba->pport;
13048 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13049 	mbox->context1 = NULL;
13050 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13051 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
13052 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13053 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13054 	if (shdr_status || shdr_add_status || rc) {
13055 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13056 				"2512 MODIFY_EQ_DELAY mailbox failed with "
13057 				"status x%x add_status x%x, mbx status x%x\n",
13058 				shdr_status, shdr_add_status, rc);
13059 		status = -ENXIO;
13060 	}
13061 	mempool_free(mbox, phba->mbox_mem_pool);
13062 	return status;
13063 }
13064 
13065 /**
13066  * lpfc_eq_create - Create an Event Queue on the HBA
13067  * @phba: HBA structure that indicates port to create a queue on.
13068  * @eq: The queue structure to use to create the event queue.
13069  * @imax: The maximum interrupt per second limit.
13070  *
13071  * This function creates an event queue, as detailed in @eq, on a port,
13072  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
13073  *
13074  * The @phba struct is used to send mailbox command to HBA. The @eq struct
13075  * is used to get the entry count and entry size that are necessary to
13076  * determine the number of pages to allocate and use for this queue. This
13077  * function will send the EQ_CREATE mailbox command to the HBA to setup the
13078  * event queue. This function is asynchronous and will wait for the mailbox
13079  * command to finish before continuing.
13080  *
13081  * On success this function will return a zero. If unable to allocate enough
13082  * memory this function will return -ENOMEM. If the queue create mailbox command
13083  * fails this function will return -ENXIO.
13084  **/
13085 int
13086 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
13087 {
13088 	struct lpfc_mbx_eq_create *eq_create;
13089 	LPFC_MBOXQ_t *mbox;
13090 	int rc, length, status = 0;
13091 	struct lpfc_dmabuf *dmabuf;
13092 	uint32_t shdr_status, shdr_add_status;
13093 	union lpfc_sli4_cfg_shdr *shdr;
13094 	uint16_t dmult;
13095 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13096 
13097 	/* sanity check on queue memory */
13098 	if (!eq)
13099 		return -ENODEV;
13100 	if (!phba->sli4_hba.pc_sli4_params.supported)
13101 		hw_page_size = SLI4_PAGE_SIZE;
13102 
13103 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13104 	if (!mbox)
13105 		return -ENOMEM;
13106 	length = (sizeof(struct lpfc_mbx_eq_create) -
13107 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13108 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13109 			 LPFC_MBOX_OPCODE_EQ_CREATE,
13110 			 length, LPFC_SLI4_MBX_EMBED);
13111 	eq_create = &mbox->u.mqe.un.eq_create;
13112 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
13113 	       eq->page_count);
13114 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
13115 	       LPFC_EQE_SIZE);
13116 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
13117 	/* don't setup delay multiplier using EQ_CREATE */
13118 	dmult = 0;
13119 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
13120 	       dmult);
13121 	switch (eq->entry_count) {
13122 	default:
13123 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13124 				"0360 Unsupported EQ count. (%d)\n",
13125 				eq->entry_count);
13126 		if (eq->entry_count < 256)
13127 			return -EINVAL;
13128 		/* otherwise default to smallest count (drop through) */
13129 	case 256:
13130 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13131 		       LPFC_EQ_CNT_256);
13132 		break;
13133 	case 512:
13134 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13135 		       LPFC_EQ_CNT_512);
13136 		break;
13137 	case 1024:
13138 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13139 		       LPFC_EQ_CNT_1024);
13140 		break;
13141 	case 2048:
13142 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13143 		       LPFC_EQ_CNT_2048);
13144 		break;
13145 	case 4096:
13146 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13147 		       LPFC_EQ_CNT_4096);
13148 		break;
13149 	}
13150 	list_for_each_entry(dmabuf, &eq->page_list, list) {
13151 		memset(dmabuf->virt, 0, hw_page_size);
13152 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13153 					putPaddrLow(dmabuf->phys);
13154 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13155 					putPaddrHigh(dmabuf->phys);
13156 	}
13157 	mbox->vport = phba->pport;
13158 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13159 	mbox->context1 = NULL;
13160 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13161 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
13162 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13163 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13164 	if (shdr_status || shdr_add_status || rc) {
13165 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13166 				"2500 EQ_CREATE mailbox failed with "
13167 				"status x%x add_status x%x, mbx status x%x\n",
13168 				shdr_status, shdr_add_status, rc);
13169 		status = -ENXIO;
13170 	}
13171 	eq->type = LPFC_EQ;
13172 	eq->subtype = LPFC_NONE;
13173 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
13174 	if (eq->queue_id == 0xFFFF)
13175 		status = -ENXIO;
13176 	eq->host_index = 0;
13177 	eq->hba_index = 0;
13178 
13179 	mempool_free(mbox, phba->mbox_mem_pool);
13180 	return status;
13181 }
13182 
13183 /**
13184  * lpfc_cq_create - Create a Completion Queue on the HBA
13185  * @phba: HBA structure that indicates port to create a queue on.
13186  * @cq: The queue structure to use to create the completion queue.
13187  * @eq: The event queue to bind this completion queue to.
13188  *
13189  * This function creates a completion queue, as detailed in @wq, on a port,
13190  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
13191  *
13192  * The @phba struct is used to send mailbox command to HBA. The @cq struct
13193  * is used to get the entry count and entry size that are necessary to
13194  * determine the number of pages to allocate and use for this queue. The @eq
13195  * is used to indicate which event queue to bind this completion queue to. This
13196  * function will send the CQ_CREATE mailbox command to the HBA to setup the
13197  * completion queue. This function is asynchronous and will wait for the mailbox
13198  * command to finish before continuing.
13199  *
13200  * On success this function will return a zero. If unable to allocate enough
13201  * memory this function will return -ENOMEM. If the queue create mailbox command
13202  * fails this function will return -ENXIO.
13203  **/
13204 int
13205 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
13206 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
13207 {
13208 	struct lpfc_mbx_cq_create *cq_create;
13209 	struct lpfc_dmabuf *dmabuf;
13210 	LPFC_MBOXQ_t *mbox;
13211 	int rc, length, status = 0;
13212 	uint32_t shdr_status, shdr_add_status;
13213 	union lpfc_sli4_cfg_shdr *shdr;
13214 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13215 
13216 	/* sanity check on queue memory */
13217 	if (!cq || !eq)
13218 		return -ENODEV;
13219 	if (!phba->sli4_hba.pc_sli4_params.supported)
13220 		hw_page_size = SLI4_PAGE_SIZE;
13221 
13222 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13223 	if (!mbox)
13224 		return -ENOMEM;
13225 	length = (sizeof(struct lpfc_mbx_cq_create) -
13226 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13227 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13228 			 LPFC_MBOX_OPCODE_CQ_CREATE,
13229 			 length, LPFC_SLI4_MBX_EMBED);
13230 	cq_create = &mbox->u.mqe.un.cq_create;
13231 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
13232 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
13233 		    cq->page_count);
13234 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
13235 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
13236 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13237 	       phba->sli4_hba.pc_sli4_params.cqv);
13238 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
13239 		/* FW only supports 1. Should be PAGE_SIZE/SLI4_PAGE_SIZE */
13240 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request, 1);
13241 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
13242 		       eq->queue_id);
13243 	} else {
13244 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
13245 		       eq->queue_id);
13246 	}
13247 	switch (cq->entry_count) {
13248 	default:
13249 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13250 				"0361 Unsupported CQ count. (%d)\n",
13251 				cq->entry_count);
13252 		if (cq->entry_count < 256) {
13253 			status = -EINVAL;
13254 			goto out;
13255 		}
13256 		/* otherwise default to smallest count (drop through) */
13257 	case 256:
13258 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
13259 		       LPFC_CQ_CNT_256);
13260 		break;
13261 	case 512:
13262 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
13263 		       LPFC_CQ_CNT_512);
13264 		break;
13265 	case 1024:
13266 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
13267 		       LPFC_CQ_CNT_1024);
13268 		break;
13269 	}
13270 	list_for_each_entry(dmabuf, &cq->page_list, list) {
13271 		memset(dmabuf->virt, 0, hw_page_size);
13272 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13273 					putPaddrLow(dmabuf->phys);
13274 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13275 					putPaddrHigh(dmabuf->phys);
13276 	}
13277 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13278 
13279 	/* The IOCTL status is embedded in the mailbox subheader. */
13280 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13281 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13282 	if (shdr_status || shdr_add_status || rc) {
13283 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13284 				"2501 CQ_CREATE mailbox failed with "
13285 				"status x%x add_status x%x, mbx status x%x\n",
13286 				shdr_status, shdr_add_status, rc);
13287 		status = -ENXIO;
13288 		goto out;
13289 	}
13290 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
13291 	if (cq->queue_id == 0xFFFF) {
13292 		status = -ENXIO;
13293 		goto out;
13294 	}
13295 	/* link the cq onto the parent eq child list */
13296 	list_add_tail(&cq->list, &eq->child_list);
13297 	/* Set up completion queue's type and subtype */
13298 	cq->type = type;
13299 	cq->subtype = subtype;
13300 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
13301 	cq->assoc_qid = eq->queue_id;
13302 	cq->host_index = 0;
13303 	cq->hba_index = 0;
13304 
13305 out:
13306 	mempool_free(mbox, phba->mbox_mem_pool);
13307 	return status;
13308 }
13309 
13310 /**
13311  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
13312  * @phba: HBA structure that indicates port to create a queue on.
13313  * @mq: The queue structure to use to create the mailbox queue.
13314  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
13315  * @cq: The completion queue to associate with this cq.
13316  *
13317  * This function provides failback (fb) functionality when the
13318  * mq_create_ext fails on older FW generations.  It's purpose is identical
13319  * to mq_create_ext otherwise.
13320  *
13321  * This routine cannot fail as all attributes were previously accessed and
13322  * initialized in mq_create_ext.
13323  **/
13324 static void
13325 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
13326 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
13327 {
13328 	struct lpfc_mbx_mq_create *mq_create;
13329 	struct lpfc_dmabuf *dmabuf;
13330 	int length;
13331 
13332 	length = (sizeof(struct lpfc_mbx_mq_create) -
13333 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13334 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13335 			 LPFC_MBOX_OPCODE_MQ_CREATE,
13336 			 length, LPFC_SLI4_MBX_EMBED);
13337 	mq_create = &mbox->u.mqe.un.mq_create;
13338 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
13339 	       mq->page_count);
13340 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
13341 	       cq->queue_id);
13342 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
13343 	switch (mq->entry_count) {
13344 	case 16:
13345 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13346 		       LPFC_MQ_RING_SIZE_16);
13347 		break;
13348 	case 32:
13349 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13350 		       LPFC_MQ_RING_SIZE_32);
13351 		break;
13352 	case 64:
13353 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13354 		       LPFC_MQ_RING_SIZE_64);
13355 		break;
13356 	case 128:
13357 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13358 		       LPFC_MQ_RING_SIZE_128);
13359 		break;
13360 	}
13361 	list_for_each_entry(dmabuf, &mq->page_list, list) {
13362 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13363 			putPaddrLow(dmabuf->phys);
13364 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13365 			putPaddrHigh(dmabuf->phys);
13366 	}
13367 }
13368 
13369 /**
13370  * lpfc_mq_create - Create a mailbox Queue on the HBA
13371  * @phba: HBA structure that indicates port to create a queue on.
13372  * @mq: The queue structure to use to create the mailbox queue.
13373  * @cq: The completion queue to associate with this cq.
13374  * @subtype: The queue's subtype.
13375  *
13376  * This function creates a mailbox queue, as detailed in @mq, on a port,
13377  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
13378  *
13379  * The @phba struct is used to send mailbox command to HBA. The @cq struct
13380  * is used to get the entry count and entry size that are necessary to
13381  * determine the number of pages to allocate and use for this queue. This
13382  * function will send the MQ_CREATE mailbox command to the HBA to setup the
13383  * mailbox queue. This function is asynchronous and will wait for the mailbox
13384  * command to finish before continuing.
13385  *
13386  * On success this function will return a zero. If unable to allocate enough
13387  * memory this function will return -ENOMEM. If the queue create mailbox command
13388  * fails this function will return -ENXIO.
13389  **/
13390 int32_t
13391 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
13392 	       struct lpfc_queue *cq, uint32_t subtype)
13393 {
13394 	struct lpfc_mbx_mq_create *mq_create;
13395 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
13396 	struct lpfc_dmabuf *dmabuf;
13397 	LPFC_MBOXQ_t *mbox;
13398 	int rc, length, status = 0;
13399 	uint32_t shdr_status, shdr_add_status;
13400 	union lpfc_sli4_cfg_shdr *shdr;
13401 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13402 
13403 	/* sanity check on queue memory */
13404 	if (!mq || !cq)
13405 		return -ENODEV;
13406 	if (!phba->sli4_hba.pc_sli4_params.supported)
13407 		hw_page_size = SLI4_PAGE_SIZE;
13408 
13409 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13410 	if (!mbox)
13411 		return -ENOMEM;
13412 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
13413 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13414 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13415 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
13416 			 length, LPFC_SLI4_MBX_EMBED);
13417 
13418 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
13419 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
13420 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
13421 	       &mq_create_ext->u.request, mq->page_count);
13422 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
13423 	       &mq_create_ext->u.request, 1);
13424 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
13425 	       &mq_create_ext->u.request, 1);
13426 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
13427 	       &mq_create_ext->u.request, 1);
13428 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
13429 	       &mq_create_ext->u.request, 1);
13430 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
13431 	       &mq_create_ext->u.request, 1);
13432 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
13433 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13434 	       phba->sli4_hba.pc_sli4_params.mqv);
13435 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
13436 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
13437 		       cq->queue_id);
13438 	else
13439 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
13440 		       cq->queue_id);
13441 	switch (mq->entry_count) {
13442 	default:
13443 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13444 				"0362 Unsupported MQ count. (%d)\n",
13445 				mq->entry_count);
13446 		if (mq->entry_count < 16) {
13447 			status = -EINVAL;
13448 			goto out;
13449 		}
13450 		/* otherwise default to smallest count (drop through) */
13451 	case 16:
13452 		bf_set(lpfc_mq_context_ring_size,
13453 		       &mq_create_ext->u.request.context,
13454 		       LPFC_MQ_RING_SIZE_16);
13455 		break;
13456 	case 32:
13457 		bf_set(lpfc_mq_context_ring_size,
13458 		       &mq_create_ext->u.request.context,
13459 		       LPFC_MQ_RING_SIZE_32);
13460 		break;
13461 	case 64:
13462 		bf_set(lpfc_mq_context_ring_size,
13463 		       &mq_create_ext->u.request.context,
13464 		       LPFC_MQ_RING_SIZE_64);
13465 		break;
13466 	case 128:
13467 		bf_set(lpfc_mq_context_ring_size,
13468 		       &mq_create_ext->u.request.context,
13469 		       LPFC_MQ_RING_SIZE_128);
13470 		break;
13471 	}
13472 	list_for_each_entry(dmabuf, &mq->page_list, list) {
13473 		memset(dmabuf->virt, 0, hw_page_size);
13474 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
13475 					putPaddrLow(dmabuf->phys);
13476 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
13477 					putPaddrHigh(dmabuf->phys);
13478 	}
13479 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13480 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
13481 			      &mq_create_ext->u.response);
13482 	if (rc != MBX_SUCCESS) {
13483 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13484 				"2795 MQ_CREATE_EXT failed with "
13485 				"status x%x. Failback to MQ_CREATE.\n",
13486 				rc);
13487 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
13488 		mq_create = &mbox->u.mqe.un.mq_create;
13489 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13490 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
13491 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
13492 				      &mq_create->u.response);
13493 	}
13494 
13495 	/* The IOCTL status is embedded in the mailbox subheader. */
13496 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13497 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13498 	if (shdr_status || shdr_add_status || rc) {
13499 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13500 				"2502 MQ_CREATE mailbox failed with "
13501 				"status x%x add_status x%x, mbx status x%x\n",
13502 				shdr_status, shdr_add_status, rc);
13503 		status = -ENXIO;
13504 		goto out;
13505 	}
13506 	if (mq->queue_id == 0xFFFF) {
13507 		status = -ENXIO;
13508 		goto out;
13509 	}
13510 	mq->type = LPFC_MQ;
13511 	mq->assoc_qid = cq->queue_id;
13512 	mq->subtype = subtype;
13513 	mq->host_index = 0;
13514 	mq->hba_index = 0;
13515 
13516 	/* link the mq onto the parent cq child list */
13517 	list_add_tail(&mq->list, &cq->child_list);
13518 out:
13519 	mempool_free(mbox, phba->mbox_mem_pool);
13520 	return status;
13521 }
13522 
13523 /**
13524  * lpfc_wq_create - Create a Work Queue on the HBA
13525  * @phba: HBA structure that indicates port to create a queue on.
13526  * @wq: The queue structure to use to create the work queue.
13527  * @cq: The completion queue to bind this work queue to.
13528  * @subtype: The subtype of the work queue indicating its functionality.
13529  *
13530  * This function creates a work queue, as detailed in @wq, on a port, described
13531  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
13532  *
13533  * The @phba struct is used to send mailbox command to HBA. The @wq struct
13534  * is used to get the entry count and entry size that are necessary to
13535  * determine the number of pages to allocate and use for this queue. The @cq
13536  * is used to indicate which completion queue to bind this work queue to. This
13537  * function will send the WQ_CREATE mailbox command to the HBA to setup the
13538  * work queue. This function is asynchronous and will wait for the mailbox
13539  * command to finish before continuing.
13540  *
13541  * On success this function will return a zero. If unable to allocate enough
13542  * memory this function will return -ENOMEM. If the queue create mailbox command
13543  * fails this function will return -ENXIO.
13544  **/
13545 int
13546 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
13547 	       struct lpfc_queue *cq, uint32_t subtype)
13548 {
13549 	struct lpfc_mbx_wq_create *wq_create;
13550 	struct lpfc_dmabuf *dmabuf;
13551 	LPFC_MBOXQ_t *mbox;
13552 	int rc, length, status = 0;
13553 	uint32_t shdr_status, shdr_add_status;
13554 	union lpfc_sli4_cfg_shdr *shdr;
13555 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13556 	struct dma_address *page;
13557 	void __iomem *bar_memmap_p;
13558 	uint32_t db_offset;
13559 	uint16_t pci_barset;
13560 
13561 	/* sanity check on queue memory */
13562 	if (!wq || !cq)
13563 		return -ENODEV;
13564 	if (!phba->sli4_hba.pc_sli4_params.supported)
13565 		hw_page_size = SLI4_PAGE_SIZE;
13566 
13567 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13568 	if (!mbox)
13569 		return -ENOMEM;
13570 	length = (sizeof(struct lpfc_mbx_wq_create) -
13571 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13572 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
13573 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
13574 			 length, LPFC_SLI4_MBX_EMBED);
13575 	wq_create = &mbox->u.mqe.un.wq_create;
13576 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
13577 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
13578 		    wq->page_count);
13579 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
13580 		    cq->queue_id);
13581 
13582 	/* wqv is the earliest version supported, NOT the latest */
13583 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13584 	       phba->sli4_hba.pc_sli4_params.wqv);
13585 
13586 	switch (phba->sli4_hba.pc_sli4_params.wqv) {
13587 	case LPFC_Q_CREATE_VERSION_0:
13588 		switch (wq->entry_size) {
13589 		default:
13590 		case 64:
13591 			/* Nothing to do, version 0 ONLY supports 64 byte */
13592 			page = wq_create->u.request.page;
13593 			break;
13594 		case 128:
13595 			if (!(phba->sli4_hba.pc_sli4_params.wqsize &
13596 			    LPFC_WQ_SZ128_SUPPORT)) {
13597 				status = -ERANGE;
13598 				goto out;
13599 			}
13600 			/* If we get here the HBA MUST also support V1 and
13601 			 * we MUST use it
13602 			 */
13603 			bf_set(lpfc_mbox_hdr_version, &shdr->request,
13604 			       LPFC_Q_CREATE_VERSION_1);
13605 
13606 			bf_set(lpfc_mbx_wq_create_wqe_count,
13607 			       &wq_create->u.request_1, wq->entry_count);
13608 			bf_set(lpfc_mbx_wq_create_wqe_size,
13609 			       &wq_create->u.request_1,
13610 			       LPFC_WQ_WQE_SIZE_128);
13611 			bf_set(lpfc_mbx_wq_create_page_size,
13612 			       &wq_create->u.request_1,
13613 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
13614 			page = wq_create->u.request_1.page;
13615 			break;
13616 		}
13617 		break;
13618 	case LPFC_Q_CREATE_VERSION_1:
13619 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
13620 		       wq->entry_count);
13621 		switch (wq->entry_size) {
13622 		default:
13623 		case 64:
13624 			bf_set(lpfc_mbx_wq_create_wqe_size,
13625 			       &wq_create->u.request_1,
13626 			       LPFC_WQ_WQE_SIZE_64);
13627 			break;
13628 		case 128:
13629 			if (!(phba->sli4_hba.pc_sli4_params.wqsize &
13630 				LPFC_WQ_SZ128_SUPPORT)) {
13631 				status = -ERANGE;
13632 				goto out;
13633 			}
13634 			bf_set(lpfc_mbx_wq_create_wqe_size,
13635 			       &wq_create->u.request_1,
13636 			       LPFC_WQ_WQE_SIZE_128);
13637 			break;
13638 		}
13639 		bf_set(lpfc_mbx_wq_create_page_size, &wq_create->u.request_1,
13640 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
13641 		page = wq_create->u.request_1.page;
13642 		break;
13643 	default:
13644 		status = -ERANGE;
13645 		goto out;
13646 	}
13647 
13648 	list_for_each_entry(dmabuf, &wq->page_list, list) {
13649 		memset(dmabuf->virt, 0, hw_page_size);
13650 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
13651 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
13652 	}
13653 
13654 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
13655 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
13656 
13657 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13658 	/* The IOCTL status is embedded in the mailbox subheader. */
13659 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13660 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13661 	if (shdr_status || shdr_add_status || rc) {
13662 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13663 				"2503 WQ_CREATE mailbox failed with "
13664 				"status x%x add_status x%x, mbx status x%x\n",
13665 				shdr_status, shdr_add_status, rc);
13666 		status = -ENXIO;
13667 		goto out;
13668 	}
13669 	wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id, &wq_create->u.response);
13670 	if (wq->queue_id == 0xFFFF) {
13671 		status = -ENXIO;
13672 		goto out;
13673 	}
13674 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
13675 		wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
13676 				       &wq_create->u.response);
13677 		if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
13678 		    (wq->db_format != LPFC_DB_RING_FORMAT)) {
13679 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13680 					"3265 WQ[%d] doorbell format not "
13681 					"supported: x%x\n", wq->queue_id,
13682 					wq->db_format);
13683 			status = -EINVAL;
13684 			goto out;
13685 		}
13686 		pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
13687 				    &wq_create->u.response);
13688 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
13689 		if (!bar_memmap_p) {
13690 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13691 					"3263 WQ[%d] failed to memmap pci "
13692 					"barset:x%x\n", wq->queue_id,
13693 					pci_barset);
13694 			status = -ENOMEM;
13695 			goto out;
13696 		}
13697 		db_offset = wq_create->u.response.doorbell_offset;
13698 		if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
13699 		    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
13700 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13701 					"3252 WQ[%d] doorbell offset not "
13702 					"supported: x%x\n", wq->queue_id,
13703 					db_offset);
13704 			status = -EINVAL;
13705 			goto out;
13706 		}
13707 		wq->db_regaddr = bar_memmap_p + db_offset;
13708 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13709 				"3264 WQ[%d]: barset:x%x, offset:x%x, "
13710 				"format:x%x\n", wq->queue_id, pci_barset,
13711 				db_offset, wq->db_format);
13712 	} else {
13713 		wq->db_format = LPFC_DB_LIST_FORMAT;
13714 		wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
13715 	}
13716 	wq->type = LPFC_WQ;
13717 	wq->assoc_qid = cq->queue_id;
13718 	wq->subtype = subtype;
13719 	wq->host_index = 0;
13720 	wq->hba_index = 0;
13721 	wq->entry_repost = LPFC_RELEASE_NOTIFICATION_INTERVAL;
13722 
13723 	/* link the wq onto the parent cq child list */
13724 	list_add_tail(&wq->list, &cq->child_list);
13725 out:
13726 	mempool_free(mbox, phba->mbox_mem_pool);
13727 	return status;
13728 }
13729 
13730 /**
13731  * lpfc_rq_adjust_repost - Adjust entry_repost for an RQ
13732  * @phba: HBA structure that indicates port to create a queue on.
13733  * @rq:   The queue structure to use for the receive queue.
13734  * @qno:  The associated HBQ number
13735  *
13736  *
13737  * For SLI4 we need to adjust the RQ repost value based on
13738  * the number of buffers that are initially posted to the RQ.
13739  */
13740 void
13741 lpfc_rq_adjust_repost(struct lpfc_hba *phba, struct lpfc_queue *rq, int qno)
13742 {
13743 	uint32_t cnt;
13744 
13745 	/* sanity check on queue memory */
13746 	if (!rq)
13747 		return;
13748 	cnt = lpfc_hbq_defs[qno]->entry_count;
13749 
13750 	/* Recalc repost for RQs based on buffers initially posted */
13751 	cnt = (cnt >> 3);
13752 	if (cnt < LPFC_QUEUE_MIN_REPOST)
13753 		cnt = LPFC_QUEUE_MIN_REPOST;
13754 
13755 	rq->entry_repost = cnt;
13756 }
13757 
13758 /**
13759  * lpfc_rq_create - Create a Receive Queue on the HBA
13760  * @phba: HBA structure that indicates port to create a queue on.
13761  * @hrq: The queue structure to use to create the header receive queue.
13762  * @drq: The queue structure to use to create the data receive queue.
13763  * @cq: The completion queue to bind this work queue to.
13764  *
13765  * This function creates a receive buffer queue pair , as detailed in @hrq and
13766  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
13767  * to the HBA.
13768  *
13769  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
13770  * struct is used to get the entry count that is necessary to determine the
13771  * number of pages to use for this queue. The @cq is used to indicate which
13772  * completion queue to bind received buffers that are posted to these queues to.
13773  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
13774  * receive queue pair. This function is asynchronous and will wait for the
13775  * mailbox command to finish before continuing.
13776  *
13777  * On success this function will return a zero. If unable to allocate enough
13778  * memory this function will return -ENOMEM. If the queue create mailbox command
13779  * fails this function will return -ENXIO.
13780  **/
13781 int
13782 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
13783 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
13784 {
13785 	struct lpfc_mbx_rq_create *rq_create;
13786 	struct lpfc_dmabuf *dmabuf;
13787 	LPFC_MBOXQ_t *mbox;
13788 	int rc, length, status = 0;
13789 	uint32_t shdr_status, shdr_add_status;
13790 	union lpfc_sli4_cfg_shdr *shdr;
13791 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13792 	void __iomem *bar_memmap_p;
13793 	uint32_t db_offset;
13794 	uint16_t pci_barset;
13795 
13796 	/* sanity check on queue memory */
13797 	if (!hrq || !drq || !cq)
13798 		return -ENODEV;
13799 	if (!phba->sli4_hba.pc_sli4_params.supported)
13800 		hw_page_size = SLI4_PAGE_SIZE;
13801 
13802 	if (hrq->entry_count != drq->entry_count)
13803 		return -EINVAL;
13804 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13805 	if (!mbox)
13806 		return -ENOMEM;
13807 	length = (sizeof(struct lpfc_mbx_rq_create) -
13808 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13809 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
13810 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
13811 			 length, LPFC_SLI4_MBX_EMBED);
13812 	rq_create = &mbox->u.mqe.un.rq_create;
13813 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
13814 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13815 	       phba->sli4_hba.pc_sli4_params.rqv);
13816 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
13817 		bf_set(lpfc_rq_context_rqe_count_1,
13818 		       &rq_create->u.request.context,
13819 		       hrq->entry_count);
13820 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
13821 		bf_set(lpfc_rq_context_rqe_size,
13822 		       &rq_create->u.request.context,
13823 		       LPFC_RQE_SIZE_8);
13824 		bf_set(lpfc_rq_context_page_size,
13825 		       &rq_create->u.request.context,
13826 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
13827 	} else {
13828 		switch (hrq->entry_count) {
13829 		default:
13830 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13831 					"2535 Unsupported RQ count. (%d)\n",
13832 					hrq->entry_count);
13833 			if (hrq->entry_count < 512) {
13834 				status = -EINVAL;
13835 				goto out;
13836 			}
13837 			/* otherwise default to smallest count (drop through) */
13838 		case 512:
13839 			bf_set(lpfc_rq_context_rqe_count,
13840 			       &rq_create->u.request.context,
13841 			       LPFC_RQ_RING_SIZE_512);
13842 			break;
13843 		case 1024:
13844 			bf_set(lpfc_rq_context_rqe_count,
13845 			       &rq_create->u.request.context,
13846 			       LPFC_RQ_RING_SIZE_1024);
13847 			break;
13848 		case 2048:
13849 			bf_set(lpfc_rq_context_rqe_count,
13850 			       &rq_create->u.request.context,
13851 			       LPFC_RQ_RING_SIZE_2048);
13852 			break;
13853 		case 4096:
13854 			bf_set(lpfc_rq_context_rqe_count,
13855 			       &rq_create->u.request.context,
13856 			       LPFC_RQ_RING_SIZE_4096);
13857 			break;
13858 		}
13859 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
13860 		       LPFC_HDR_BUF_SIZE);
13861 	}
13862 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
13863 	       cq->queue_id);
13864 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
13865 	       hrq->page_count);
13866 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
13867 		memset(dmabuf->virt, 0, hw_page_size);
13868 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13869 					putPaddrLow(dmabuf->phys);
13870 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13871 					putPaddrHigh(dmabuf->phys);
13872 	}
13873 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
13874 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
13875 
13876 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13877 	/* The IOCTL status is embedded in the mailbox subheader. */
13878 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13879 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13880 	if (shdr_status || shdr_add_status || rc) {
13881 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13882 				"2504 RQ_CREATE mailbox failed with "
13883 				"status x%x add_status x%x, mbx status x%x\n",
13884 				shdr_status, shdr_add_status, rc);
13885 		status = -ENXIO;
13886 		goto out;
13887 	}
13888 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
13889 	if (hrq->queue_id == 0xFFFF) {
13890 		status = -ENXIO;
13891 		goto out;
13892 	}
13893 
13894 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
13895 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
13896 					&rq_create->u.response);
13897 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
13898 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
13899 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13900 					"3262 RQ [%d] doorbell format not "
13901 					"supported: x%x\n", hrq->queue_id,
13902 					hrq->db_format);
13903 			status = -EINVAL;
13904 			goto out;
13905 		}
13906 
13907 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
13908 				    &rq_create->u.response);
13909 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
13910 		if (!bar_memmap_p) {
13911 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13912 					"3269 RQ[%d] failed to memmap pci "
13913 					"barset:x%x\n", hrq->queue_id,
13914 					pci_barset);
13915 			status = -ENOMEM;
13916 			goto out;
13917 		}
13918 
13919 		db_offset = rq_create->u.response.doorbell_offset;
13920 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
13921 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
13922 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13923 					"3270 RQ[%d] doorbell offset not "
13924 					"supported: x%x\n", hrq->queue_id,
13925 					db_offset);
13926 			status = -EINVAL;
13927 			goto out;
13928 		}
13929 		hrq->db_regaddr = bar_memmap_p + db_offset;
13930 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13931 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
13932 				"format:x%x\n", hrq->queue_id, pci_barset,
13933 				db_offset, hrq->db_format);
13934 	} else {
13935 		hrq->db_format = LPFC_DB_RING_FORMAT;
13936 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
13937 	}
13938 	hrq->type = LPFC_HRQ;
13939 	hrq->assoc_qid = cq->queue_id;
13940 	hrq->subtype = subtype;
13941 	hrq->host_index = 0;
13942 	hrq->hba_index = 0;
13943 
13944 	/* now create the data queue */
13945 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
13946 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
13947 			 length, LPFC_SLI4_MBX_EMBED);
13948 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13949 	       phba->sli4_hba.pc_sli4_params.rqv);
13950 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
13951 		bf_set(lpfc_rq_context_rqe_count_1,
13952 		       &rq_create->u.request.context, hrq->entry_count);
13953 		rq_create->u.request.context.buffer_size = LPFC_DATA_BUF_SIZE;
13954 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
13955 		       LPFC_RQE_SIZE_8);
13956 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
13957 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
13958 	} else {
13959 		switch (drq->entry_count) {
13960 		default:
13961 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13962 					"2536 Unsupported RQ count. (%d)\n",
13963 					drq->entry_count);
13964 			if (drq->entry_count < 512) {
13965 				status = -EINVAL;
13966 				goto out;
13967 			}
13968 			/* otherwise default to smallest count (drop through) */
13969 		case 512:
13970 			bf_set(lpfc_rq_context_rqe_count,
13971 			       &rq_create->u.request.context,
13972 			       LPFC_RQ_RING_SIZE_512);
13973 			break;
13974 		case 1024:
13975 			bf_set(lpfc_rq_context_rqe_count,
13976 			       &rq_create->u.request.context,
13977 			       LPFC_RQ_RING_SIZE_1024);
13978 			break;
13979 		case 2048:
13980 			bf_set(lpfc_rq_context_rqe_count,
13981 			       &rq_create->u.request.context,
13982 			       LPFC_RQ_RING_SIZE_2048);
13983 			break;
13984 		case 4096:
13985 			bf_set(lpfc_rq_context_rqe_count,
13986 			       &rq_create->u.request.context,
13987 			       LPFC_RQ_RING_SIZE_4096);
13988 			break;
13989 		}
13990 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
13991 		       LPFC_DATA_BUF_SIZE);
13992 	}
13993 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
13994 	       cq->queue_id);
13995 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
13996 	       drq->page_count);
13997 	list_for_each_entry(dmabuf, &drq->page_list, list) {
13998 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13999 					putPaddrLow(dmabuf->phys);
14000 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
14001 					putPaddrHigh(dmabuf->phys);
14002 	}
14003 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
14004 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
14005 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14006 	/* The IOCTL status is embedded in the mailbox subheader. */
14007 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
14008 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14009 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14010 	if (shdr_status || shdr_add_status || rc) {
14011 		status = -ENXIO;
14012 		goto out;
14013 	}
14014 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
14015 	if (drq->queue_id == 0xFFFF) {
14016 		status = -ENXIO;
14017 		goto out;
14018 	}
14019 	drq->type = LPFC_DRQ;
14020 	drq->assoc_qid = cq->queue_id;
14021 	drq->subtype = subtype;
14022 	drq->host_index = 0;
14023 	drq->hba_index = 0;
14024 
14025 	/* link the header and data RQs onto the parent cq child list */
14026 	list_add_tail(&hrq->list, &cq->child_list);
14027 	list_add_tail(&drq->list, &cq->child_list);
14028 
14029 out:
14030 	mempool_free(mbox, phba->mbox_mem_pool);
14031 	return status;
14032 }
14033 
14034 /**
14035  * lpfc_eq_destroy - Destroy an event Queue on the HBA
14036  * @eq: The queue structure associated with the queue to destroy.
14037  *
14038  * This function destroys a queue, as detailed in @eq by sending an mailbox
14039  * command, specific to the type of queue, to the HBA.
14040  *
14041  * The @eq struct is used to get the queue ID of the queue to destroy.
14042  *
14043  * On success this function will return a zero. If the queue destroy mailbox
14044  * command fails this function will return -ENXIO.
14045  **/
14046 int
14047 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
14048 {
14049 	LPFC_MBOXQ_t *mbox;
14050 	int rc, length, status = 0;
14051 	uint32_t shdr_status, shdr_add_status;
14052 	union lpfc_sli4_cfg_shdr *shdr;
14053 
14054 	/* sanity check on queue memory */
14055 	if (!eq)
14056 		return -ENODEV;
14057 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
14058 	if (!mbox)
14059 		return -ENOMEM;
14060 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
14061 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14062 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14063 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
14064 			 length, LPFC_SLI4_MBX_EMBED);
14065 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
14066 	       eq->queue_id);
14067 	mbox->vport = eq->phba->pport;
14068 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14069 
14070 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
14071 	/* The IOCTL status is embedded in the mailbox subheader. */
14072 	shdr = (union lpfc_sli4_cfg_shdr *)
14073 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
14074 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14075 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14076 	if (shdr_status || shdr_add_status || rc) {
14077 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14078 				"2505 EQ_DESTROY mailbox failed with "
14079 				"status x%x add_status x%x, mbx status x%x\n",
14080 				shdr_status, shdr_add_status, rc);
14081 		status = -ENXIO;
14082 	}
14083 
14084 	/* Remove eq from any list */
14085 	list_del_init(&eq->list);
14086 	mempool_free(mbox, eq->phba->mbox_mem_pool);
14087 	return status;
14088 }
14089 
14090 /**
14091  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
14092  * @cq: The queue structure associated with the queue to destroy.
14093  *
14094  * This function destroys a queue, as detailed in @cq by sending an mailbox
14095  * command, specific to the type of queue, to the HBA.
14096  *
14097  * The @cq struct is used to get the queue ID of the queue to destroy.
14098  *
14099  * On success this function will return a zero. If the queue destroy mailbox
14100  * command fails this function will return -ENXIO.
14101  **/
14102 int
14103 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
14104 {
14105 	LPFC_MBOXQ_t *mbox;
14106 	int rc, length, status = 0;
14107 	uint32_t shdr_status, shdr_add_status;
14108 	union lpfc_sli4_cfg_shdr *shdr;
14109 
14110 	/* sanity check on queue memory */
14111 	if (!cq)
14112 		return -ENODEV;
14113 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
14114 	if (!mbox)
14115 		return -ENOMEM;
14116 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
14117 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14118 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14119 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
14120 			 length, LPFC_SLI4_MBX_EMBED);
14121 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
14122 	       cq->queue_id);
14123 	mbox->vport = cq->phba->pport;
14124 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14125 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
14126 	/* The IOCTL status is embedded in the mailbox subheader. */
14127 	shdr = (union lpfc_sli4_cfg_shdr *)
14128 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
14129 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14130 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14131 	if (shdr_status || shdr_add_status || rc) {
14132 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14133 				"2506 CQ_DESTROY mailbox failed with "
14134 				"status x%x add_status x%x, mbx status x%x\n",
14135 				shdr_status, shdr_add_status, rc);
14136 		status = -ENXIO;
14137 	}
14138 	/* Remove cq from any list */
14139 	list_del_init(&cq->list);
14140 	mempool_free(mbox, cq->phba->mbox_mem_pool);
14141 	return status;
14142 }
14143 
14144 /**
14145  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
14146  * @qm: The queue structure associated with the queue to destroy.
14147  *
14148  * This function destroys a queue, as detailed in @mq by sending an mailbox
14149  * command, specific to the type of queue, to the HBA.
14150  *
14151  * The @mq struct is used to get the queue ID of the queue to destroy.
14152  *
14153  * On success this function will return a zero. If the queue destroy mailbox
14154  * command fails this function will return -ENXIO.
14155  **/
14156 int
14157 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
14158 {
14159 	LPFC_MBOXQ_t *mbox;
14160 	int rc, length, status = 0;
14161 	uint32_t shdr_status, shdr_add_status;
14162 	union lpfc_sli4_cfg_shdr *shdr;
14163 
14164 	/* sanity check on queue memory */
14165 	if (!mq)
14166 		return -ENODEV;
14167 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
14168 	if (!mbox)
14169 		return -ENOMEM;
14170 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
14171 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14172 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14173 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
14174 			 length, LPFC_SLI4_MBX_EMBED);
14175 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
14176 	       mq->queue_id);
14177 	mbox->vport = mq->phba->pport;
14178 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14179 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
14180 	/* The IOCTL status is embedded in the mailbox subheader. */
14181 	shdr = (union lpfc_sli4_cfg_shdr *)
14182 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
14183 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14184 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14185 	if (shdr_status || shdr_add_status || rc) {
14186 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14187 				"2507 MQ_DESTROY mailbox failed with "
14188 				"status x%x add_status x%x, mbx status x%x\n",
14189 				shdr_status, shdr_add_status, rc);
14190 		status = -ENXIO;
14191 	}
14192 	/* Remove mq from any list */
14193 	list_del_init(&mq->list);
14194 	mempool_free(mbox, mq->phba->mbox_mem_pool);
14195 	return status;
14196 }
14197 
14198 /**
14199  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
14200  * @wq: The queue structure associated with the queue to destroy.
14201  *
14202  * This function destroys a queue, as detailed in @wq by sending an mailbox
14203  * command, specific to the type of queue, to the HBA.
14204  *
14205  * The @wq struct is used to get the queue ID of the queue to destroy.
14206  *
14207  * On success this function will return a zero. If the queue destroy mailbox
14208  * command fails this function will return -ENXIO.
14209  **/
14210 int
14211 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
14212 {
14213 	LPFC_MBOXQ_t *mbox;
14214 	int rc, length, status = 0;
14215 	uint32_t shdr_status, shdr_add_status;
14216 	union lpfc_sli4_cfg_shdr *shdr;
14217 
14218 	/* sanity check on queue memory */
14219 	if (!wq)
14220 		return -ENODEV;
14221 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
14222 	if (!mbox)
14223 		return -ENOMEM;
14224 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
14225 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14226 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14227 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
14228 			 length, LPFC_SLI4_MBX_EMBED);
14229 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
14230 	       wq->queue_id);
14231 	mbox->vport = wq->phba->pport;
14232 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14233 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
14234 	shdr = (union lpfc_sli4_cfg_shdr *)
14235 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
14236 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14237 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14238 	if (shdr_status || shdr_add_status || rc) {
14239 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14240 				"2508 WQ_DESTROY mailbox failed with "
14241 				"status x%x add_status x%x, mbx status x%x\n",
14242 				shdr_status, shdr_add_status, rc);
14243 		status = -ENXIO;
14244 	}
14245 	/* Remove wq from any list */
14246 	list_del_init(&wq->list);
14247 	mempool_free(mbox, wq->phba->mbox_mem_pool);
14248 	return status;
14249 }
14250 
14251 /**
14252  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
14253  * @rq: The queue structure associated with the queue to destroy.
14254  *
14255  * This function destroys a queue, as detailed in @rq by sending an mailbox
14256  * command, specific to the type of queue, to the HBA.
14257  *
14258  * The @rq struct is used to get the queue ID of the queue to destroy.
14259  *
14260  * On success this function will return a zero. If the queue destroy mailbox
14261  * command fails this function will return -ENXIO.
14262  **/
14263 int
14264 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
14265 		struct lpfc_queue *drq)
14266 {
14267 	LPFC_MBOXQ_t *mbox;
14268 	int rc, length, status = 0;
14269 	uint32_t shdr_status, shdr_add_status;
14270 	union lpfc_sli4_cfg_shdr *shdr;
14271 
14272 	/* sanity check on queue memory */
14273 	if (!hrq || !drq)
14274 		return -ENODEV;
14275 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
14276 	if (!mbox)
14277 		return -ENOMEM;
14278 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
14279 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14280 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14281 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
14282 			 length, LPFC_SLI4_MBX_EMBED);
14283 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
14284 	       hrq->queue_id);
14285 	mbox->vport = hrq->phba->pport;
14286 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14287 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
14288 	/* The IOCTL status is embedded in the mailbox subheader. */
14289 	shdr = (union lpfc_sli4_cfg_shdr *)
14290 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
14291 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14292 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14293 	if (shdr_status || shdr_add_status || rc) {
14294 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14295 				"2509 RQ_DESTROY mailbox failed with "
14296 				"status x%x add_status x%x, mbx status x%x\n",
14297 				shdr_status, shdr_add_status, rc);
14298 		if (rc != MBX_TIMEOUT)
14299 			mempool_free(mbox, hrq->phba->mbox_mem_pool);
14300 		return -ENXIO;
14301 	}
14302 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
14303 	       drq->queue_id);
14304 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
14305 	shdr = (union lpfc_sli4_cfg_shdr *)
14306 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
14307 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14308 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14309 	if (shdr_status || shdr_add_status || rc) {
14310 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14311 				"2510 RQ_DESTROY mailbox failed with "
14312 				"status x%x add_status x%x, mbx status x%x\n",
14313 				shdr_status, shdr_add_status, rc);
14314 		status = -ENXIO;
14315 	}
14316 	list_del_init(&hrq->list);
14317 	list_del_init(&drq->list);
14318 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
14319 	return status;
14320 }
14321 
14322 /**
14323  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
14324  * @phba: The virtual port for which this call being executed.
14325  * @pdma_phys_addr0: Physical address of the 1st SGL page.
14326  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
14327  * @xritag: the xritag that ties this io to the SGL pages.
14328  *
14329  * This routine will post the sgl pages for the IO that has the xritag
14330  * that is in the iocbq structure. The xritag is assigned during iocbq
14331  * creation and persists for as long as the driver is loaded.
14332  * if the caller has fewer than 256 scatter gather segments to map then
14333  * pdma_phys_addr1 should be 0.
14334  * If the caller needs to map more than 256 scatter gather segment then
14335  * pdma_phys_addr1 should be a valid physical address.
14336  * physical address for SGLs must be 64 byte aligned.
14337  * If you are going to map 2 SGL's then the first one must have 256 entries
14338  * the second sgl can have between 1 and 256 entries.
14339  *
14340  * Return codes:
14341  * 	0 - Success
14342  * 	-ENXIO, -ENOMEM - Failure
14343  **/
14344 int
14345 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
14346 		dma_addr_t pdma_phys_addr0,
14347 		dma_addr_t pdma_phys_addr1,
14348 		uint16_t xritag)
14349 {
14350 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
14351 	LPFC_MBOXQ_t *mbox;
14352 	int rc;
14353 	uint32_t shdr_status, shdr_add_status;
14354 	uint32_t mbox_tmo;
14355 	union lpfc_sli4_cfg_shdr *shdr;
14356 
14357 	if (xritag == NO_XRI) {
14358 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14359 				"0364 Invalid param:\n");
14360 		return -EINVAL;
14361 	}
14362 
14363 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14364 	if (!mbox)
14365 		return -ENOMEM;
14366 
14367 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14368 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
14369 			sizeof(struct lpfc_mbx_post_sgl_pages) -
14370 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
14371 
14372 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
14373 				&mbox->u.mqe.un.post_sgl_pages;
14374 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
14375 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
14376 
14377 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
14378 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
14379 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
14380 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
14381 
14382 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
14383 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
14384 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
14385 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
14386 	if (!phba->sli4_hba.intr_enable)
14387 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14388 	else {
14389 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
14390 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
14391 	}
14392 	/* The IOCTL status is embedded in the mailbox subheader. */
14393 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
14394 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14395 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14396 	if (rc != MBX_TIMEOUT)
14397 		mempool_free(mbox, phba->mbox_mem_pool);
14398 	if (shdr_status || shdr_add_status || rc) {
14399 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14400 				"2511 POST_SGL mailbox failed with "
14401 				"status x%x add_status x%x, mbx status x%x\n",
14402 				shdr_status, shdr_add_status, rc);
14403 	}
14404 	return 0;
14405 }
14406 
14407 /**
14408  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
14409  * @phba: pointer to lpfc hba data structure.
14410  *
14411  * This routine is invoked to post rpi header templates to the
14412  * HBA consistent with the SLI-4 interface spec.  This routine
14413  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
14414  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
14415  *
14416  * Returns
14417  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
14418  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
14419  **/
14420 static uint16_t
14421 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
14422 {
14423 	unsigned long xri;
14424 
14425 	/*
14426 	 * Fetch the next logical xri.  Because this index is logical,
14427 	 * the driver starts at 0 each time.
14428 	 */
14429 	spin_lock_irq(&phba->hbalock);
14430 	xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
14431 				 phba->sli4_hba.max_cfg_param.max_xri, 0);
14432 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
14433 		spin_unlock_irq(&phba->hbalock);
14434 		return NO_XRI;
14435 	} else {
14436 		set_bit(xri, phba->sli4_hba.xri_bmask);
14437 		phba->sli4_hba.max_cfg_param.xri_used++;
14438 	}
14439 	spin_unlock_irq(&phba->hbalock);
14440 	return xri;
14441 }
14442 
14443 /**
14444  * lpfc_sli4_free_xri - Release an xri for reuse.
14445  * @phba: pointer to lpfc hba data structure.
14446  *
14447  * This routine is invoked to release an xri to the pool of
14448  * available rpis maintained by the driver.
14449  **/
14450 static void
14451 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
14452 {
14453 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
14454 		phba->sli4_hba.max_cfg_param.xri_used--;
14455 	}
14456 }
14457 
14458 /**
14459  * lpfc_sli4_free_xri - Release an xri for reuse.
14460  * @phba: pointer to lpfc hba data structure.
14461  *
14462  * This routine is invoked to release an xri to the pool of
14463  * available rpis maintained by the driver.
14464  **/
14465 void
14466 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
14467 {
14468 	spin_lock_irq(&phba->hbalock);
14469 	__lpfc_sli4_free_xri(phba, xri);
14470 	spin_unlock_irq(&phba->hbalock);
14471 }
14472 
14473 /**
14474  * lpfc_sli4_next_xritag - Get an xritag for the io
14475  * @phba: Pointer to HBA context object.
14476  *
14477  * This function gets an xritag for the iocb. If there is no unused xritag
14478  * it will return 0xffff.
14479  * The function returns the allocated xritag if successful, else returns zero.
14480  * Zero is not a valid xritag.
14481  * The caller is not required to hold any lock.
14482  **/
14483 uint16_t
14484 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
14485 {
14486 	uint16_t xri_index;
14487 
14488 	xri_index = lpfc_sli4_alloc_xri(phba);
14489 	if (xri_index == NO_XRI)
14490 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14491 				"2004 Failed to allocate XRI.last XRITAG is %d"
14492 				" Max XRI is %d, Used XRI is %d\n",
14493 				xri_index,
14494 				phba->sli4_hba.max_cfg_param.max_xri,
14495 				phba->sli4_hba.max_cfg_param.xri_used);
14496 	return xri_index;
14497 }
14498 
14499 /**
14500  * lpfc_sli4_post_els_sgl_list - post a block of ELS sgls to the port.
14501  * @phba: pointer to lpfc hba data structure.
14502  * @post_sgl_list: pointer to els sgl entry list.
14503  * @count: number of els sgl entries on the list.
14504  *
14505  * This routine is invoked to post a block of driver's sgl pages to the
14506  * HBA using non-embedded mailbox command. No Lock is held. This routine
14507  * is only called when the driver is loading and after all IO has been
14508  * stopped.
14509  **/
14510 static int
14511 lpfc_sli4_post_els_sgl_list(struct lpfc_hba *phba,
14512 			    struct list_head *post_sgl_list,
14513 			    int post_cnt)
14514 {
14515 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
14516 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
14517 	struct sgl_page_pairs *sgl_pg_pairs;
14518 	void *viraddr;
14519 	LPFC_MBOXQ_t *mbox;
14520 	uint32_t reqlen, alloclen, pg_pairs;
14521 	uint32_t mbox_tmo;
14522 	uint16_t xritag_start = 0;
14523 	int rc = 0;
14524 	uint32_t shdr_status, shdr_add_status;
14525 	union lpfc_sli4_cfg_shdr *shdr;
14526 
14527 	reqlen = phba->sli4_hba.els_xri_cnt * sizeof(struct sgl_page_pairs) +
14528 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
14529 	if (reqlen > SLI4_PAGE_SIZE) {
14530 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
14531 				"2559 Block sgl registration required DMA "
14532 				"size (%d) great than a page\n", reqlen);
14533 		return -ENOMEM;
14534 	}
14535 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14536 	if (!mbox)
14537 		return -ENOMEM;
14538 
14539 	/* Allocate DMA memory and set up the non-embedded mailbox command */
14540 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14541 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
14542 			 LPFC_SLI4_MBX_NEMBED);
14543 
14544 	if (alloclen < reqlen) {
14545 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14546 				"0285 Allocated DMA memory size (%d) is "
14547 				"less than the requested DMA memory "
14548 				"size (%d)\n", alloclen, reqlen);
14549 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14550 		return -ENOMEM;
14551 	}
14552 	/* Set up the SGL pages in the non-embedded DMA pages */
14553 	viraddr = mbox->sge_array->addr[0];
14554 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
14555 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
14556 
14557 	pg_pairs = 0;
14558 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
14559 		/* Set up the sge entry */
14560 		sgl_pg_pairs->sgl_pg0_addr_lo =
14561 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
14562 		sgl_pg_pairs->sgl_pg0_addr_hi =
14563 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
14564 		sgl_pg_pairs->sgl_pg1_addr_lo =
14565 				cpu_to_le32(putPaddrLow(0));
14566 		sgl_pg_pairs->sgl_pg1_addr_hi =
14567 				cpu_to_le32(putPaddrHigh(0));
14568 
14569 		/* Keep the first xritag on the list */
14570 		if (pg_pairs == 0)
14571 			xritag_start = sglq_entry->sli4_xritag;
14572 		sgl_pg_pairs++;
14573 		pg_pairs++;
14574 	}
14575 
14576 	/* Complete initialization and perform endian conversion. */
14577 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
14578 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, phba->sli4_hba.els_xri_cnt);
14579 	sgl->word0 = cpu_to_le32(sgl->word0);
14580 	if (!phba->sli4_hba.intr_enable)
14581 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14582 	else {
14583 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
14584 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
14585 	}
14586 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
14587 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14588 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14589 	if (rc != MBX_TIMEOUT)
14590 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14591 	if (shdr_status || shdr_add_status || rc) {
14592 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14593 				"2513 POST_SGL_BLOCK mailbox command failed "
14594 				"status x%x add_status x%x mbx status x%x\n",
14595 				shdr_status, shdr_add_status, rc);
14596 		rc = -ENXIO;
14597 	}
14598 	return rc;
14599 }
14600 
14601 /**
14602  * lpfc_sli4_post_scsi_sgl_block - post a block of scsi sgl list to firmware
14603  * @phba: pointer to lpfc hba data structure.
14604  * @sblist: pointer to scsi buffer list.
14605  * @count: number of scsi buffers on the list.
14606  *
14607  * This routine is invoked to post a block of @count scsi sgl pages from a
14608  * SCSI buffer list @sblist to the HBA using non-embedded mailbox command.
14609  * No Lock is held.
14610  *
14611  **/
14612 int
14613 lpfc_sli4_post_scsi_sgl_block(struct lpfc_hba *phba,
14614 			      struct list_head *sblist,
14615 			      int count)
14616 {
14617 	struct lpfc_scsi_buf *psb;
14618 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
14619 	struct sgl_page_pairs *sgl_pg_pairs;
14620 	void *viraddr;
14621 	LPFC_MBOXQ_t *mbox;
14622 	uint32_t reqlen, alloclen, pg_pairs;
14623 	uint32_t mbox_tmo;
14624 	uint16_t xritag_start = 0;
14625 	int rc = 0;
14626 	uint32_t shdr_status, shdr_add_status;
14627 	dma_addr_t pdma_phys_bpl1;
14628 	union lpfc_sli4_cfg_shdr *shdr;
14629 
14630 	/* Calculate the requested length of the dma memory */
14631 	reqlen = count * sizeof(struct sgl_page_pairs) +
14632 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
14633 	if (reqlen > SLI4_PAGE_SIZE) {
14634 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
14635 				"0217 Block sgl registration required DMA "
14636 				"size (%d) great than a page\n", reqlen);
14637 		return -ENOMEM;
14638 	}
14639 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14640 	if (!mbox) {
14641 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14642 				"0283 Failed to allocate mbox cmd memory\n");
14643 		return -ENOMEM;
14644 	}
14645 
14646 	/* Allocate DMA memory and set up the non-embedded mailbox command */
14647 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14648 				LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
14649 				LPFC_SLI4_MBX_NEMBED);
14650 
14651 	if (alloclen < reqlen) {
14652 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14653 				"2561 Allocated DMA memory size (%d) is "
14654 				"less than the requested DMA memory "
14655 				"size (%d)\n", alloclen, reqlen);
14656 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14657 		return -ENOMEM;
14658 	}
14659 
14660 	/* Get the first SGE entry from the non-embedded DMA memory */
14661 	viraddr = mbox->sge_array->addr[0];
14662 
14663 	/* Set up the SGL pages in the non-embedded DMA pages */
14664 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
14665 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
14666 
14667 	pg_pairs = 0;
14668 	list_for_each_entry(psb, sblist, list) {
14669 		/* Set up the sge entry */
14670 		sgl_pg_pairs->sgl_pg0_addr_lo =
14671 			cpu_to_le32(putPaddrLow(psb->dma_phys_bpl));
14672 		sgl_pg_pairs->sgl_pg0_addr_hi =
14673 			cpu_to_le32(putPaddrHigh(psb->dma_phys_bpl));
14674 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
14675 			pdma_phys_bpl1 = psb->dma_phys_bpl + SGL_PAGE_SIZE;
14676 		else
14677 			pdma_phys_bpl1 = 0;
14678 		sgl_pg_pairs->sgl_pg1_addr_lo =
14679 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
14680 		sgl_pg_pairs->sgl_pg1_addr_hi =
14681 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
14682 		/* Keep the first xritag on the list */
14683 		if (pg_pairs == 0)
14684 			xritag_start = psb->cur_iocbq.sli4_xritag;
14685 		sgl_pg_pairs++;
14686 		pg_pairs++;
14687 	}
14688 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
14689 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
14690 	/* Perform endian conversion if necessary */
14691 	sgl->word0 = cpu_to_le32(sgl->word0);
14692 
14693 	if (!phba->sli4_hba.intr_enable)
14694 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14695 	else {
14696 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
14697 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
14698 	}
14699 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
14700 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14701 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14702 	if (rc != MBX_TIMEOUT)
14703 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14704 	if (shdr_status || shdr_add_status || rc) {
14705 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14706 				"2564 POST_SGL_BLOCK mailbox command failed "
14707 				"status x%x add_status x%x mbx status x%x\n",
14708 				shdr_status, shdr_add_status, rc);
14709 		rc = -ENXIO;
14710 	}
14711 	return rc;
14712 }
14713 
14714 /**
14715  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
14716  * @phba: pointer to lpfc_hba struct that the frame was received on
14717  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
14718  *
14719  * This function checks the fields in the @fc_hdr to see if the FC frame is a
14720  * valid type of frame that the LPFC driver will handle. This function will
14721  * return a zero if the frame is a valid frame or a non zero value when the
14722  * frame does not pass the check.
14723  **/
14724 static int
14725 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
14726 {
14727 	/*  make rctl_names static to save stack space */
14728 	static char *rctl_names[] = FC_RCTL_NAMES_INIT;
14729 	char *type_names[] = FC_TYPE_NAMES_INIT;
14730 	struct fc_vft_header *fc_vft_hdr;
14731 	uint32_t *header = (uint32_t *) fc_hdr;
14732 
14733 	switch (fc_hdr->fh_r_ctl) {
14734 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
14735 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
14736 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
14737 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
14738 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
14739 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
14740 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
14741 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
14742 	case FC_RCTL_ELS_REQ:	/* extended link services request */
14743 	case FC_RCTL_ELS_REP:	/* extended link services reply */
14744 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
14745 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
14746 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
14747 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
14748 	case FC_RCTL_BA_RMC: 	/* remove connection */
14749 	case FC_RCTL_BA_ACC:	/* basic accept */
14750 	case FC_RCTL_BA_RJT:	/* basic reject */
14751 	case FC_RCTL_BA_PRMT:
14752 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
14753 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
14754 	case FC_RCTL_P_RJT:	/* port reject */
14755 	case FC_RCTL_F_RJT:	/* fabric reject */
14756 	case FC_RCTL_P_BSY:	/* port busy */
14757 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
14758 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
14759 	case FC_RCTL_LCR:	/* link credit reset */
14760 	case FC_RCTL_END:	/* end */
14761 		break;
14762 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
14763 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
14764 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
14765 		return lpfc_fc_frame_check(phba, fc_hdr);
14766 	default:
14767 		goto drop;
14768 	}
14769 	switch (fc_hdr->fh_type) {
14770 	case FC_TYPE_BLS:
14771 	case FC_TYPE_ELS:
14772 	case FC_TYPE_FCP:
14773 	case FC_TYPE_CT:
14774 		break;
14775 	case FC_TYPE_IP:
14776 	case FC_TYPE_ILS:
14777 	default:
14778 		goto drop;
14779 	}
14780 
14781 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
14782 			"2538 Received frame rctl:%s (x%x), type:%s (x%x), "
14783 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
14784 			rctl_names[fc_hdr->fh_r_ctl], fc_hdr->fh_r_ctl,
14785 			type_names[fc_hdr->fh_type], fc_hdr->fh_type,
14786 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
14787 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
14788 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
14789 			be32_to_cpu(header[6]));
14790 	return 0;
14791 drop:
14792 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
14793 			"2539 Dropped frame rctl:%s type:%s\n",
14794 			rctl_names[fc_hdr->fh_r_ctl],
14795 			type_names[fc_hdr->fh_type]);
14796 	return 1;
14797 }
14798 
14799 /**
14800  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
14801  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
14802  *
14803  * This function processes the FC header to retrieve the VFI from the VF
14804  * header, if one exists. This function will return the VFI if one exists
14805  * or 0 if no VSAN Header exists.
14806  **/
14807 static uint32_t
14808 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
14809 {
14810 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
14811 
14812 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
14813 		return 0;
14814 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
14815 }
14816 
14817 /**
14818  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
14819  * @phba: Pointer to the HBA structure to search for the vport on
14820  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
14821  * @fcfi: The FC Fabric ID that the frame came from
14822  *
14823  * This function searches the @phba for a vport that matches the content of the
14824  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
14825  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
14826  * returns the matching vport pointer or NULL if unable to match frame to a
14827  * vport.
14828  **/
14829 static struct lpfc_vport *
14830 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
14831 		       uint16_t fcfi)
14832 {
14833 	struct lpfc_vport **vports;
14834 	struct lpfc_vport *vport = NULL;
14835 	int i;
14836 	uint32_t did = (fc_hdr->fh_d_id[0] << 16 |
14837 			fc_hdr->fh_d_id[1] << 8 |
14838 			fc_hdr->fh_d_id[2]);
14839 
14840 	if (did == Fabric_DID)
14841 		return phba->pport;
14842 	if ((phba->pport->fc_flag & FC_PT2PT) &&
14843 		!(phba->link_state == LPFC_HBA_READY))
14844 		return phba->pport;
14845 
14846 	vports = lpfc_create_vport_work_array(phba);
14847 	if (vports != NULL)
14848 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
14849 			if (phba->fcf.fcfi == fcfi &&
14850 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
14851 			    vports[i]->fc_myDID == did) {
14852 				vport = vports[i];
14853 				break;
14854 			}
14855 		}
14856 	lpfc_destroy_vport_work_array(phba, vports);
14857 	return vport;
14858 }
14859 
14860 /**
14861  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
14862  * @vport: The vport to work on.
14863  *
14864  * This function updates the receive sequence time stamp for this vport. The
14865  * receive sequence time stamp indicates the time that the last frame of the
14866  * the sequence that has been idle for the longest amount of time was received.
14867  * the driver uses this time stamp to indicate if any received sequences have
14868  * timed out.
14869  **/
14870 static void
14871 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
14872 {
14873 	struct lpfc_dmabuf *h_buf;
14874 	struct hbq_dmabuf *dmabuf = NULL;
14875 
14876 	/* get the oldest sequence on the rcv list */
14877 	h_buf = list_get_first(&vport->rcv_buffer_list,
14878 			       struct lpfc_dmabuf, list);
14879 	if (!h_buf)
14880 		return;
14881 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
14882 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
14883 }
14884 
14885 /**
14886  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
14887  * @vport: The vport that the received sequences were sent to.
14888  *
14889  * This function cleans up all outstanding received sequences. This is called
14890  * by the driver when a link event or user action invalidates all the received
14891  * sequences.
14892  **/
14893 void
14894 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
14895 {
14896 	struct lpfc_dmabuf *h_buf, *hnext;
14897 	struct lpfc_dmabuf *d_buf, *dnext;
14898 	struct hbq_dmabuf *dmabuf = NULL;
14899 
14900 	/* start with the oldest sequence on the rcv list */
14901 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
14902 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
14903 		list_del_init(&dmabuf->hbuf.list);
14904 		list_for_each_entry_safe(d_buf, dnext,
14905 					 &dmabuf->dbuf.list, list) {
14906 			list_del_init(&d_buf->list);
14907 			lpfc_in_buf_free(vport->phba, d_buf);
14908 		}
14909 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
14910 	}
14911 }
14912 
14913 /**
14914  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
14915  * @vport: The vport that the received sequences were sent to.
14916  *
14917  * This function determines whether any received sequences have timed out by
14918  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
14919  * indicates that there is at least one timed out sequence this routine will
14920  * go through the received sequences one at a time from most inactive to most
14921  * active to determine which ones need to be cleaned up. Once it has determined
14922  * that a sequence needs to be cleaned up it will simply free up the resources
14923  * without sending an abort.
14924  **/
14925 void
14926 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
14927 {
14928 	struct lpfc_dmabuf *h_buf, *hnext;
14929 	struct lpfc_dmabuf *d_buf, *dnext;
14930 	struct hbq_dmabuf *dmabuf = NULL;
14931 	unsigned long timeout;
14932 	int abort_count = 0;
14933 
14934 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
14935 		   vport->rcv_buffer_time_stamp);
14936 	if (list_empty(&vport->rcv_buffer_list) ||
14937 	    time_before(jiffies, timeout))
14938 		return;
14939 	/* start with the oldest sequence on the rcv list */
14940 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
14941 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
14942 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
14943 			   dmabuf->time_stamp);
14944 		if (time_before(jiffies, timeout))
14945 			break;
14946 		abort_count++;
14947 		list_del_init(&dmabuf->hbuf.list);
14948 		list_for_each_entry_safe(d_buf, dnext,
14949 					 &dmabuf->dbuf.list, list) {
14950 			list_del_init(&d_buf->list);
14951 			lpfc_in_buf_free(vport->phba, d_buf);
14952 		}
14953 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
14954 	}
14955 	if (abort_count)
14956 		lpfc_update_rcv_time_stamp(vport);
14957 }
14958 
14959 /**
14960  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
14961  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
14962  *
14963  * This function searches through the existing incomplete sequences that have
14964  * been sent to this @vport. If the frame matches one of the incomplete
14965  * sequences then the dbuf in the @dmabuf is added to the list of frames that
14966  * make up that sequence. If no sequence is found that matches this frame then
14967  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
14968  * This function returns a pointer to the first dmabuf in the sequence list that
14969  * the frame was linked to.
14970  **/
14971 static struct hbq_dmabuf *
14972 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
14973 {
14974 	struct fc_frame_header *new_hdr;
14975 	struct fc_frame_header *temp_hdr;
14976 	struct lpfc_dmabuf *d_buf;
14977 	struct lpfc_dmabuf *h_buf;
14978 	struct hbq_dmabuf *seq_dmabuf = NULL;
14979 	struct hbq_dmabuf *temp_dmabuf = NULL;
14980 	uint8_t	found = 0;
14981 
14982 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
14983 	dmabuf->time_stamp = jiffies;
14984 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
14985 
14986 	/* Use the hdr_buf to find the sequence that this frame belongs to */
14987 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
14988 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
14989 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
14990 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
14991 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
14992 			continue;
14993 		/* found a pending sequence that matches this frame */
14994 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
14995 		break;
14996 	}
14997 	if (!seq_dmabuf) {
14998 		/*
14999 		 * This indicates first frame received for this sequence.
15000 		 * Queue the buffer on the vport's rcv_buffer_list.
15001 		 */
15002 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
15003 		lpfc_update_rcv_time_stamp(vport);
15004 		return dmabuf;
15005 	}
15006 	temp_hdr = seq_dmabuf->hbuf.virt;
15007 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
15008 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
15009 		list_del_init(&seq_dmabuf->hbuf.list);
15010 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
15011 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
15012 		lpfc_update_rcv_time_stamp(vport);
15013 		return dmabuf;
15014 	}
15015 	/* move this sequence to the tail to indicate a young sequence */
15016 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
15017 	seq_dmabuf->time_stamp = jiffies;
15018 	lpfc_update_rcv_time_stamp(vport);
15019 	if (list_empty(&seq_dmabuf->dbuf.list)) {
15020 		temp_hdr = dmabuf->hbuf.virt;
15021 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
15022 		return seq_dmabuf;
15023 	}
15024 	/* find the correct place in the sequence to insert this frame */
15025 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
15026 	while (!found) {
15027 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15028 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
15029 		/*
15030 		 * If the frame's sequence count is greater than the frame on
15031 		 * the list then insert the frame right after this frame
15032 		 */
15033 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
15034 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
15035 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
15036 			found = 1;
15037 			break;
15038 		}
15039 
15040 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
15041 			break;
15042 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
15043 	}
15044 
15045 	if (found)
15046 		return seq_dmabuf;
15047 	return NULL;
15048 }
15049 
15050 /**
15051  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
15052  * @vport: pointer to a vitural port
15053  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15054  *
15055  * This function tries to abort from the partially assembed sequence, described
15056  * by the information from basic abbort @dmabuf. It checks to see whether such
15057  * partially assembled sequence held by the driver. If so, it shall free up all
15058  * the frames from the partially assembled sequence.
15059  *
15060  * Return
15061  * true  -- if there is matching partially assembled sequence present and all
15062  *          the frames freed with the sequence;
15063  * false -- if there is no matching partially assembled sequence present so
15064  *          nothing got aborted in the lower layer driver
15065  **/
15066 static bool
15067 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
15068 			    struct hbq_dmabuf *dmabuf)
15069 {
15070 	struct fc_frame_header *new_hdr;
15071 	struct fc_frame_header *temp_hdr;
15072 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
15073 	struct hbq_dmabuf *seq_dmabuf = NULL;
15074 
15075 	/* Use the hdr_buf to find the sequence that matches this frame */
15076 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
15077 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
15078 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
15079 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
15080 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
15081 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
15082 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
15083 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
15084 			continue;
15085 		/* found a pending sequence that matches this frame */
15086 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
15087 		break;
15088 	}
15089 
15090 	/* Free up all the frames from the partially assembled sequence */
15091 	if (seq_dmabuf) {
15092 		list_for_each_entry_safe(d_buf, n_buf,
15093 					 &seq_dmabuf->dbuf.list, list) {
15094 			list_del_init(&d_buf->list);
15095 			lpfc_in_buf_free(vport->phba, d_buf);
15096 		}
15097 		return true;
15098 	}
15099 	return false;
15100 }
15101 
15102 /**
15103  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
15104  * @vport: pointer to a vitural port
15105  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15106  *
15107  * This function tries to abort from the assembed sequence from upper level
15108  * protocol, described by the information from basic abbort @dmabuf. It
15109  * checks to see whether such pending context exists at upper level protocol.
15110  * If so, it shall clean up the pending context.
15111  *
15112  * Return
15113  * true  -- if there is matching pending context of the sequence cleaned
15114  *          at ulp;
15115  * false -- if there is no matching pending context of the sequence present
15116  *          at ulp.
15117  **/
15118 static bool
15119 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
15120 {
15121 	struct lpfc_hba *phba = vport->phba;
15122 	int handled;
15123 
15124 	/* Accepting abort at ulp with SLI4 only */
15125 	if (phba->sli_rev < LPFC_SLI_REV4)
15126 		return false;
15127 
15128 	/* Register all caring upper level protocols to attend abort */
15129 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
15130 	if (handled)
15131 		return true;
15132 
15133 	return false;
15134 }
15135 
15136 /**
15137  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
15138  * @phba: Pointer to HBA context object.
15139  * @cmd_iocbq: pointer to the command iocbq structure.
15140  * @rsp_iocbq: pointer to the response iocbq structure.
15141  *
15142  * This function handles the sequence abort response iocb command complete
15143  * event. It properly releases the memory allocated to the sequence abort
15144  * accept iocb.
15145  **/
15146 static void
15147 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
15148 			     struct lpfc_iocbq *cmd_iocbq,
15149 			     struct lpfc_iocbq *rsp_iocbq)
15150 {
15151 	struct lpfc_nodelist *ndlp;
15152 
15153 	if (cmd_iocbq) {
15154 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
15155 		lpfc_nlp_put(ndlp);
15156 		lpfc_nlp_not_used(ndlp);
15157 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
15158 	}
15159 
15160 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
15161 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
15162 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15163 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
15164 			rsp_iocbq->iocb.ulpStatus,
15165 			rsp_iocbq->iocb.un.ulpWord[4]);
15166 }
15167 
15168 /**
15169  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
15170  * @phba: Pointer to HBA context object.
15171  * @xri: xri id in transaction.
15172  *
15173  * This function validates the xri maps to the known range of XRIs allocated an
15174  * used by the driver.
15175  **/
15176 uint16_t
15177 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
15178 		      uint16_t xri)
15179 {
15180 	uint16_t i;
15181 
15182 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
15183 		if (xri == phba->sli4_hba.xri_ids[i])
15184 			return i;
15185 	}
15186 	return NO_XRI;
15187 }
15188 
15189 /**
15190  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
15191  * @phba: Pointer to HBA context object.
15192  * @fc_hdr: pointer to a FC frame header.
15193  *
15194  * This function sends a basic response to a previous unsol sequence abort
15195  * event after aborting the sequence handling.
15196  **/
15197 static void
15198 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
15199 			struct fc_frame_header *fc_hdr, bool aborted)
15200 {
15201 	struct lpfc_hba *phba = vport->phba;
15202 	struct lpfc_iocbq *ctiocb = NULL;
15203 	struct lpfc_nodelist *ndlp;
15204 	uint16_t oxid, rxid, xri, lxri;
15205 	uint32_t sid, fctl;
15206 	IOCB_t *icmd;
15207 	int rc;
15208 
15209 	if (!lpfc_is_link_up(phba))
15210 		return;
15211 
15212 	sid = sli4_sid_from_fc_hdr(fc_hdr);
15213 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
15214 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
15215 
15216 	ndlp = lpfc_findnode_did(vport, sid);
15217 	if (!ndlp) {
15218 		ndlp = mempool_alloc(phba->nlp_mem_pool, GFP_KERNEL);
15219 		if (!ndlp) {
15220 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
15221 					 "1268 Failed to allocate ndlp for "
15222 					 "oxid:x%x SID:x%x\n", oxid, sid);
15223 			return;
15224 		}
15225 		lpfc_nlp_init(vport, ndlp, sid);
15226 		/* Put ndlp onto pport node list */
15227 		lpfc_enqueue_node(vport, ndlp);
15228 	} else if (!NLP_CHK_NODE_ACT(ndlp)) {
15229 		/* re-setup ndlp without removing from node list */
15230 		ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
15231 		if (!ndlp) {
15232 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
15233 					 "3275 Failed to active ndlp found "
15234 					 "for oxid:x%x SID:x%x\n", oxid, sid);
15235 			return;
15236 		}
15237 	}
15238 
15239 	/* Allocate buffer for rsp iocb */
15240 	ctiocb = lpfc_sli_get_iocbq(phba);
15241 	if (!ctiocb)
15242 		return;
15243 
15244 	/* Extract the F_CTL field from FC_HDR */
15245 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
15246 
15247 	icmd = &ctiocb->iocb;
15248 	icmd->un.xseq64.bdl.bdeSize = 0;
15249 	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
15250 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
15251 	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
15252 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
15253 
15254 	/* Fill in the rest of iocb fields */
15255 	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
15256 	icmd->ulpBdeCount = 0;
15257 	icmd->ulpLe = 1;
15258 	icmd->ulpClass = CLASS3;
15259 	icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
15260 	ctiocb->context1 = lpfc_nlp_get(ndlp);
15261 
15262 	ctiocb->iocb_cmpl = NULL;
15263 	ctiocb->vport = phba->pport;
15264 	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
15265 	ctiocb->sli4_lxritag = NO_XRI;
15266 	ctiocb->sli4_xritag = NO_XRI;
15267 
15268 	if (fctl & FC_FC_EX_CTX)
15269 		/* Exchange responder sent the abort so we
15270 		 * own the oxid.
15271 		 */
15272 		xri = oxid;
15273 	else
15274 		xri = rxid;
15275 	lxri = lpfc_sli4_xri_inrange(phba, xri);
15276 	if (lxri != NO_XRI)
15277 		lpfc_set_rrq_active(phba, ndlp, lxri,
15278 			(xri == oxid) ? rxid : oxid, 0);
15279 	/* For BA_ABTS from exchange responder, if the logical xri with
15280 	 * the oxid maps to the FCP XRI range, the port no longer has
15281 	 * that exchange context, send a BLS_RJT. Override the IOCB for
15282 	 * a BA_RJT.
15283 	 */
15284 	if ((fctl & FC_FC_EX_CTX) &&
15285 	    (lxri > lpfc_sli4_get_els_iocb_cnt(phba))) {
15286 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
15287 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
15288 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
15289 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
15290 	}
15291 
15292 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
15293 	 * the driver no longer has that exchange, send a BLS_RJT. Override
15294 	 * the IOCB for a BA_RJT.
15295 	 */
15296 	if (aborted == false) {
15297 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
15298 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
15299 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
15300 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
15301 	}
15302 
15303 	if (fctl & FC_FC_EX_CTX) {
15304 		/* ABTS sent by responder to CT exchange, construction
15305 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
15306 		 * field and RX_ID from ABTS for RX_ID field.
15307 		 */
15308 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
15309 	} else {
15310 		/* ABTS sent by initiator to CT exchange, construction
15311 		 * of BA_ACC will need to allocate a new XRI as for the
15312 		 * XRI_TAG field.
15313 		 */
15314 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
15315 	}
15316 	bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
15317 	bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
15318 
15319 	/* Xmit CT abts response on exchange <xid> */
15320 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
15321 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
15322 			 icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
15323 
15324 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
15325 	if (rc == IOCB_ERROR) {
15326 		lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
15327 				 "2925 Failed to issue CT ABTS RSP x%x on "
15328 				 "xri x%x, Data x%x\n",
15329 				 icmd->un.xseq64.w5.hcsw.Rctl, oxid,
15330 				 phba->link_state);
15331 		lpfc_nlp_put(ndlp);
15332 		ctiocb->context1 = NULL;
15333 		lpfc_sli_release_iocbq(phba, ctiocb);
15334 	}
15335 }
15336 
15337 /**
15338  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
15339  * @vport: Pointer to the vport on which this sequence was received
15340  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15341  *
15342  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
15343  * receive sequence is only partially assembed by the driver, it shall abort
15344  * the partially assembled frames for the sequence. Otherwise, if the
15345  * unsolicited receive sequence has been completely assembled and passed to
15346  * the Upper Layer Protocol (UPL), it then mark the per oxid status for the
15347  * unsolicited sequence has been aborted. After that, it will issue a basic
15348  * accept to accept the abort.
15349  **/
15350 static void
15351 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
15352 			     struct hbq_dmabuf *dmabuf)
15353 {
15354 	struct lpfc_hba *phba = vport->phba;
15355 	struct fc_frame_header fc_hdr;
15356 	uint32_t fctl;
15357 	bool aborted;
15358 
15359 	/* Make a copy of fc_hdr before the dmabuf being released */
15360 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
15361 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
15362 
15363 	if (fctl & FC_FC_EX_CTX) {
15364 		/* ABTS by responder to exchange, no cleanup needed */
15365 		aborted = true;
15366 	} else {
15367 		/* ABTS by initiator to exchange, need to do cleanup */
15368 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
15369 		if (aborted == false)
15370 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
15371 	}
15372 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
15373 
15374 	/* Respond with BA_ACC or BA_RJT accordingly */
15375 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
15376 }
15377 
15378 /**
15379  * lpfc_seq_complete - Indicates if a sequence is complete
15380  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15381  *
15382  * This function checks the sequence, starting with the frame described by
15383  * @dmabuf, to see if all the frames associated with this sequence are present.
15384  * the frames associated with this sequence are linked to the @dmabuf using the
15385  * dbuf list. This function looks for two major things. 1) That the first frame
15386  * has a sequence count of zero. 2) There is a frame with last frame of sequence
15387  * set. 3) That there are no holes in the sequence count. The function will
15388  * return 1 when the sequence is complete, otherwise it will return 0.
15389  **/
15390 static int
15391 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
15392 {
15393 	struct fc_frame_header *hdr;
15394 	struct lpfc_dmabuf *d_buf;
15395 	struct hbq_dmabuf *seq_dmabuf;
15396 	uint32_t fctl;
15397 	int seq_count = 0;
15398 
15399 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
15400 	/* make sure first fame of sequence has a sequence count of zero */
15401 	if (hdr->fh_seq_cnt != seq_count)
15402 		return 0;
15403 	fctl = (hdr->fh_f_ctl[0] << 16 |
15404 		hdr->fh_f_ctl[1] << 8 |
15405 		hdr->fh_f_ctl[2]);
15406 	/* If last frame of sequence we can return success. */
15407 	if (fctl & FC_FC_END_SEQ)
15408 		return 1;
15409 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
15410 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15411 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
15412 		/* If there is a hole in the sequence count then fail. */
15413 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
15414 			return 0;
15415 		fctl = (hdr->fh_f_ctl[0] << 16 |
15416 			hdr->fh_f_ctl[1] << 8 |
15417 			hdr->fh_f_ctl[2]);
15418 		/* If last frame of sequence we can return success. */
15419 		if (fctl & FC_FC_END_SEQ)
15420 			return 1;
15421 	}
15422 	return 0;
15423 }
15424 
15425 /**
15426  * lpfc_prep_seq - Prep sequence for ULP processing
15427  * @vport: Pointer to the vport on which this sequence was received
15428  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15429  *
15430  * This function takes a sequence, described by a list of frames, and creates
15431  * a list of iocbq structures to describe the sequence. This iocbq list will be
15432  * used to issue to the generic unsolicited sequence handler. This routine
15433  * returns a pointer to the first iocbq in the list. If the function is unable
15434  * to allocate an iocbq then it throw out the received frames that were not
15435  * able to be described and return a pointer to the first iocbq. If unable to
15436  * allocate any iocbqs (including the first) this function will return NULL.
15437  **/
15438 static struct lpfc_iocbq *
15439 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
15440 {
15441 	struct hbq_dmabuf *hbq_buf;
15442 	struct lpfc_dmabuf *d_buf, *n_buf;
15443 	struct lpfc_iocbq *first_iocbq, *iocbq;
15444 	struct fc_frame_header *fc_hdr;
15445 	uint32_t sid;
15446 	uint32_t len, tot_len;
15447 	struct ulp_bde64 *pbde;
15448 
15449 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
15450 	/* remove from receive buffer list */
15451 	list_del_init(&seq_dmabuf->hbuf.list);
15452 	lpfc_update_rcv_time_stamp(vport);
15453 	/* get the Remote Port's SID */
15454 	sid = sli4_sid_from_fc_hdr(fc_hdr);
15455 	tot_len = 0;
15456 	/* Get an iocbq struct to fill in. */
15457 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
15458 	if (first_iocbq) {
15459 		/* Initialize the first IOCB. */
15460 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
15461 		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
15462 
15463 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
15464 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
15465 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
15466 			first_iocbq->iocb.un.rcvels.parmRo =
15467 				sli4_did_from_fc_hdr(fc_hdr);
15468 			first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
15469 		} else
15470 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
15471 		first_iocbq->iocb.ulpContext = NO_XRI;
15472 		first_iocbq->iocb.unsli3.rcvsli3.ox_id =
15473 			be16_to_cpu(fc_hdr->fh_ox_id);
15474 		/* iocbq is prepped for internal consumption.  Physical vpi. */
15475 		first_iocbq->iocb.unsli3.rcvsli3.vpi =
15476 			vport->phba->vpi_ids[vport->vpi];
15477 		/* put the first buffer into the first IOCBq */
15478 		tot_len = bf_get(lpfc_rcqe_length,
15479 				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
15480 
15481 		first_iocbq->context2 = &seq_dmabuf->dbuf;
15482 		first_iocbq->context3 = NULL;
15483 		first_iocbq->iocb.ulpBdeCount = 1;
15484 		if (tot_len > LPFC_DATA_BUF_SIZE)
15485 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
15486 							LPFC_DATA_BUF_SIZE;
15487 		else
15488 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
15489 
15490 		first_iocbq->iocb.un.rcvels.remoteID = sid;
15491 
15492 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
15493 	}
15494 	iocbq = first_iocbq;
15495 	/*
15496 	 * Each IOCBq can have two Buffers assigned, so go through the list
15497 	 * of buffers for this sequence and save two buffers in each IOCBq
15498 	 */
15499 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
15500 		if (!iocbq) {
15501 			lpfc_in_buf_free(vport->phba, d_buf);
15502 			continue;
15503 		}
15504 		if (!iocbq->context3) {
15505 			iocbq->context3 = d_buf;
15506 			iocbq->iocb.ulpBdeCount++;
15507 			/* We need to get the size out of the right CQE */
15508 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15509 			len = bf_get(lpfc_rcqe_length,
15510 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
15511 			pbde = (struct ulp_bde64 *)
15512 					&iocbq->iocb.unsli3.sli3Words[4];
15513 			if (len > LPFC_DATA_BUF_SIZE)
15514 				pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
15515 			else
15516 				pbde->tus.f.bdeSize = len;
15517 
15518 			iocbq->iocb.unsli3.rcvsli3.acc_len += len;
15519 			tot_len += len;
15520 		} else {
15521 			iocbq = lpfc_sli_get_iocbq(vport->phba);
15522 			if (!iocbq) {
15523 				if (first_iocbq) {
15524 					first_iocbq->iocb.ulpStatus =
15525 							IOSTAT_FCP_RSP_ERROR;
15526 					first_iocbq->iocb.un.ulpWord[4] =
15527 							IOERR_NO_RESOURCES;
15528 				}
15529 				lpfc_in_buf_free(vport->phba, d_buf);
15530 				continue;
15531 			}
15532 			/* We need to get the size out of the right CQE */
15533 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15534 			len = bf_get(lpfc_rcqe_length,
15535 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
15536 			iocbq->context2 = d_buf;
15537 			iocbq->context3 = NULL;
15538 			iocbq->iocb.ulpBdeCount = 1;
15539 			if (len > LPFC_DATA_BUF_SIZE)
15540 				iocbq->iocb.un.cont64[0].tus.f.bdeSize =
15541 							LPFC_DATA_BUF_SIZE;
15542 			else
15543 				iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
15544 
15545 			tot_len += len;
15546 			iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
15547 
15548 			iocbq->iocb.un.rcvels.remoteID = sid;
15549 			list_add_tail(&iocbq->list, &first_iocbq->list);
15550 		}
15551 	}
15552 	return first_iocbq;
15553 }
15554 
15555 static void
15556 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
15557 			  struct hbq_dmabuf *seq_dmabuf)
15558 {
15559 	struct fc_frame_header *fc_hdr;
15560 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
15561 	struct lpfc_hba *phba = vport->phba;
15562 
15563 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
15564 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
15565 	if (!iocbq) {
15566 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15567 				"2707 Ring %d handler: Failed to allocate "
15568 				"iocb Rctl x%x Type x%x received\n",
15569 				LPFC_ELS_RING,
15570 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
15571 		return;
15572 	}
15573 	if (!lpfc_complete_unsol_iocb(phba,
15574 				      &phba->sli.ring[LPFC_ELS_RING],
15575 				      iocbq, fc_hdr->fh_r_ctl,
15576 				      fc_hdr->fh_type))
15577 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15578 				"2540 Ring %d handler: unexpected Rctl "
15579 				"x%x Type x%x received\n",
15580 				LPFC_ELS_RING,
15581 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
15582 
15583 	/* Free iocb created in lpfc_prep_seq */
15584 	list_for_each_entry_safe(curr_iocb, next_iocb,
15585 		&iocbq->list, list) {
15586 		list_del_init(&curr_iocb->list);
15587 		lpfc_sli_release_iocbq(phba, curr_iocb);
15588 	}
15589 	lpfc_sli_release_iocbq(phba, iocbq);
15590 }
15591 
15592 /**
15593  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
15594  * @phba: Pointer to HBA context object.
15595  *
15596  * This function is called with no lock held. This function processes all
15597  * the received buffers and gives it to upper layers when a received buffer
15598  * indicates that it is the final frame in the sequence. The interrupt
15599  * service routine processes received buffers at interrupt contexts and adds
15600  * received dma buffers to the rb_pend_list queue and signals the worker thread.
15601  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
15602  * appropriate receive function when the final frame in a sequence is received.
15603  **/
15604 void
15605 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
15606 				 struct hbq_dmabuf *dmabuf)
15607 {
15608 	struct hbq_dmabuf *seq_dmabuf;
15609 	struct fc_frame_header *fc_hdr;
15610 	struct lpfc_vport *vport;
15611 	uint32_t fcfi;
15612 	uint32_t did;
15613 
15614 	/* Process each received buffer */
15615 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
15616 	/* check to see if this a valid type of frame */
15617 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
15618 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
15619 		return;
15620 	}
15621 	if ((bf_get(lpfc_cqe_code,
15622 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
15623 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
15624 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
15625 	else
15626 		fcfi = bf_get(lpfc_rcqe_fcf_id,
15627 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
15628 
15629 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi);
15630 	if (!vport) {
15631 		/* throw out the frame */
15632 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
15633 		return;
15634 	}
15635 
15636 	/* d_id this frame is directed to */
15637 	did = sli4_did_from_fc_hdr(fc_hdr);
15638 
15639 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
15640 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
15641 		(did != Fabric_DID)) {
15642 		/*
15643 		 * Throw out the frame if we are not pt2pt.
15644 		 * The pt2pt protocol allows for discovery frames
15645 		 * to be received without a registered VPI.
15646 		 */
15647 		if (!(vport->fc_flag & FC_PT2PT) ||
15648 			(phba->link_state == LPFC_HBA_READY)) {
15649 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
15650 			return;
15651 		}
15652 	}
15653 
15654 	/* Handle the basic abort sequence (BA_ABTS) event */
15655 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
15656 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
15657 		return;
15658 	}
15659 
15660 	/* Link this frame */
15661 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
15662 	if (!seq_dmabuf) {
15663 		/* unable to add frame to vport - throw it out */
15664 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
15665 		return;
15666 	}
15667 	/* If not last frame in sequence continue processing frames. */
15668 	if (!lpfc_seq_complete(seq_dmabuf))
15669 		return;
15670 
15671 	/* Send the complete sequence to the upper layer protocol */
15672 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
15673 }
15674 
15675 /**
15676  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
15677  * @phba: pointer to lpfc hba data structure.
15678  *
15679  * This routine is invoked to post rpi header templates to the
15680  * HBA consistent with the SLI-4 interface spec.  This routine
15681  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
15682  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
15683  *
15684  * This routine does not require any locks.  It's usage is expected
15685  * to be driver load or reset recovery when the driver is
15686  * sequential.
15687  *
15688  * Return codes
15689  * 	0 - successful
15690  *      -EIO - The mailbox failed to complete successfully.
15691  * 	When this error occurs, the driver is not guaranteed
15692  *	to have any rpi regions posted to the device and
15693  *	must either attempt to repost the regions or take a
15694  *	fatal error.
15695  **/
15696 int
15697 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
15698 {
15699 	struct lpfc_rpi_hdr *rpi_page;
15700 	uint32_t rc = 0;
15701 	uint16_t lrpi = 0;
15702 
15703 	/* SLI4 ports that support extents do not require RPI headers. */
15704 	if (!phba->sli4_hba.rpi_hdrs_in_use)
15705 		goto exit;
15706 	if (phba->sli4_hba.extents_in_use)
15707 		return -EIO;
15708 
15709 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
15710 		/*
15711 		 * Assign the rpi headers a physical rpi only if the driver
15712 		 * has not initialized those resources.  A port reset only
15713 		 * needs the headers posted.
15714 		 */
15715 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
15716 		    LPFC_RPI_RSRC_RDY)
15717 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
15718 
15719 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
15720 		if (rc != MBX_SUCCESS) {
15721 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15722 					"2008 Error %d posting all rpi "
15723 					"headers\n", rc);
15724 			rc = -EIO;
15725 			break;
15726 		}
15727 	}
15728 
15729  exit:
15730 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
15731 	       LPFC_RPI_RSRC_RDY);
15732 	return rc;
15733 }
15734 
15735 /**
15736  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
15737  * @phba: pointer to lpfc hba data structure.
15738  * @rpi_page:  pointer to the rpi memory region.
15739  *
15740  * This routine is invoked to post a single rpi header to the
15741  * HBA consistent with the SLI-4 interface spec.  This memory region
15742  * maps up to 64 rpi context regions.
15743  *
15744  * Return codes
15745  * 	0 - successful
15746  * 	-ENOMEM - No available memory
15747  *      -EIO - The mailbox failed to complete successfully.
15748  **/
15749 int
15750 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
15751 {
15752 	LPFC_MBOXQ_t *mboxq;
15753 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
15754 	uint32_t rc = 0;
15755 	uint32_t shdr_status, shdr_add_status;
15756 	union lpfc_sli4_cfg_shdr *shdr;
15757 
15758 	/* SLI4 ports that support extents do not require RPI headers. */
15759 	if (!phba->sli4_hba.rpi_hdrs_in_use)
15760 		return rc;
15761 	if (phba->sli4_hba.extents_in_use)
15762 		return -EIO;
15763 
15764 	/* The port is notified of the header region via a mailbox command. */
15765 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15766 	if (!mboxq) {
15767 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15768 				"2001 Unable to allocate memory for issuing "
15769 				"SLI_CONFIG_SPECIAL mailbox command\n");
15770 		return -ENOMEM;
15771 	}
15772 
15773 	/* Post all rpi memory regions to the port. */
15774 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
15775 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
15776 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
15777 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
15778 			 sizeof(struct lpfc_sli4_cfg_mhdr),
15779 			 LPFC_SLI4_MBX_EMBED);
15780 
15781 
15782 	/* Post the physical rpi to the port for this rpi header. */
15783 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
15784 	       rpi_page->start_rpi);
15785 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
15786 	       hdr_tmpl, rpi_page->page_count);
15787 
15788 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
15789 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
15790 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
15791 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
15792 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15793 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15794 	if (rc != MBX_TIMEOUT)
15795 		mempool_free(mboxq, phba->mbox_mem_pool);
15796 	if (shdr_status || shdr_add_status || rc) {
15797 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15798 				"2514 POST_RPI_HDR mailbox failed with "
15799 				"status x%x add_status x%x, mbx status x%x\n",
15800 				shdr_status, shdr_add_status, rc);
15801 		rc = -ENXIO;
15802 	}
15803 	return rc;
15804 }
15805 
15806 /**
15807  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
15808  * @phba: pointer to lpfc hba data structure.
15809  *
15810  * This routine is invoked to post rpi header templates to the
15811  * HBA consistent with the SLI-4 interface spec.  This routine
15812  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
15813  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
15814  *
15815  * Returns
15816  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
15817  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
15818  **/
15819 int
15820 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
15821 {
15822 	unsigned long rpi;
15823 	uint16_t max_rpi, rpi_limit;
15824 	uint16_t rpi_remaining, lrpi = 0;
15825 	struct lpfc_rpi_hdr *rpi_hdr;
15826 	unsigned long iflag;
15827 
15828 	/*
15829 	 * Fetch the next logical rpi.  Because this index is logical,
15830 	 * the  driver starts at 0 each time.
15831 	 */
15832 	spin_lock_irqsave(&phba->hbalock, iflag);
15833 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
15834 	rpi_limit = phba->sli4_hba.next_rpi;
15835 
15836 	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
15837 	if (rpi >= rpi_limit)
15838 		rpi = LPFC_RPI_ALLOC_ERROR;
15839 	else {
15840 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
15841 		phba->sli4_hba.max_cfg_param.rpi_used++;
15842 		phba->sli4_hba.rpi_count++;
15843 	}
15844 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15845 			"0001 rpi:%x max:%x lim:%x\n",
15846 			(int) rpi, max_rpi, rpi_limit);
15847 
15848 	/*
15849 	 * Don't try to allocate more rpi header regions if the device limit
15850 	 * has been exhausted.
15851 	 */
15852 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
15853 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
15854 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15855 		return rpi;
15856 	}
15857 
15858 	/*
15859 	 * RPI header postings are not required for SLI4 ports capable of
15860 	 * extents.
15861 	 */
15862 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
15863 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15864 		return rpi;
15865 	}
15866 
15867 	/*
15868 	 * If the driver is running low on rpi resources, allocate another
15869 	 * page now.  Note that the next_rpi value is used because
15870 	 * it represents how many are actually in use whereas max_rpi notes
15871 	 * how many are supported max by the device.
15872 	 */
15873 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
15874 	spin_unlock_irqrestore(&phba->hbalock, iflag);
15875 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
15876 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
15877 		if (!rpi_hdr) {
15878 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15879 					"2002 Error Could not grow rpi "
15880 					"count\n");
15881 		} else {
15882 			lrpi = rpi_hdr->start_rpi;
15883 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
15884 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
15885 		}
15886 	}
15887 
15888 	return rpi;
15889 }
15890 
15891 /**
15892  * lpfc_sli4_free_rpi - Release an rpi for reuse.
15893  * @phba: pointer to lpfc hba data structure.
15894  *
15895  * This routine is invoked to release an rpi to the pool of
15896  * available rpis maintained by the driver.
15897  **/
15898 static void
15899 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
15900 {
15901 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
15902 		phba->sli4_hba.rpi_count--;
15903 		phba->sli4_hba.max_cfg_param.rpi_used--;
15904 	}
15905 }
15906 
15907 /**
15908  * lpfc_sli4_free_rpi - Release an rpi for reuse.
15909  * @phba: pointer to lpfc hba data structure.
15910  *
15911  * This routine is invoked to release an rpi to the pool of
15912  * available rpis maintained by the driver.
15913  **/
15914 void
15915 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
15916 {
15917 	spin_lock_irq(&phba->hbalock);
15918 	__lpfc_sli4_free_rpi(phba, rpi);
15919 	spin_unlock_irq(&phba->hbalock);
15920 }
15921 
15922 /**
15923  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
15924  * @phba: pointer to lpfc hba data structure.
15925  *
15926  * This routine is invoked to remove the memory region that
15927  * provided rpi via a bitmask.
15928  **/
15929 void
15930 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
15931 {
15932 	kfree(phba->sli4_hba.rpi_bmask);
15933 	kfree(phba->sli4_hba.rpi_ids);
15934 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
15935 }
15936 
15937 /**
15938  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
15939  * @phba: pointer to lpfc hba data structure.
15940  *
15941  * This routine is invoked to remove the memory region that
15942  * provided rpi via a bitmask.
15943  **/
15944 int
15945 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
15946 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
15947 {
15948 	LPFC_MBOXQ_t *mboxq;
15949 	struct lpfc_hba *phba = ndlp->phba;
15950 	int rc;
15951 
15952 	/* The port is notified of the header region via a mailbox command. */
15953 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15954 	if (!mboxq)
15955 		return -ENOMEM;
15956 
15957 	/* Post all rpi memory regions to the port. */
15958 	lpfc_resume_rpi(mboxq, ndlp);
15959 	if (cmpl) {
15960 		mboxq->mbox_cmpl = cmpl;
15961 		mboxq->context1 = arg;
15962 		mboxq->context2 = ndlp;
15963 	} else
15964 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15965 	mboxq->vport = ndlp->vport;
15966 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
15967 	if (rc == MBX_NOT_FINISHED) {
15968 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15969 				"2010 Resume RPI Mailbox failed "
15970 				"status %d, mbxStatus x%x\n", rc,
15971 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
15972 		mempool_free(mboxq, phba->mbox_mem_pool);
15973 		return -EIO;
15974 	}
15975 	return 0;
15976 }
15977 
15978 /**
15979  * lpfc_sli4_init_vpi - Initialize a vpi with the port
15980  * @vport: Pointer to the vport for which the vpi is being initialized
15981  *
15982  * This routine is invoked to activate a vpi with the port.
15983  *
15984  * Returns:
15985  *    0 success
15986  *    -Evalue otherwise
15987  **/
15988 int
15989 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
15990 {
15991 	LPFC_MBOXQ_t *mboxq;
15992 	int rc = 0;
15993 	int retval = MBX_SUCCESS;
15994 	uint32_t mbox_tmo;
15995 	struct lpfc_hba *phba = vport->phba;
15996 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15997 	if (!mboxq)
15998 		return -ENOMEM;
15999 	lpfc_init_vpi(phba, mboxq, vport->vpi);
16000 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
16001 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
16002 	if (rc != MBX_SUCCESS) {
16003 		lpfc_printf_vlog(vport, KERN_ERR, LOG_SLI,
16004 				"2022 INIT VPI Mailbox failed "
16005 				"status %d, mbxStatus x%x\n", rc,
16006 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
16007 		retval = -EIO;
16008 	}
16009 	if (rc != MBX_TIMEOUT)
16010 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
16011 
16012 	return retval;
16013 }
16014 
16015 /**
16016  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
16017  * @phba: pointer to lpfc hba data structure.
16018  * @mboxq: Pointer to mailbox object.
16019  *
16020  * This routine is invoked to manually add a single FCF record. The caller
16021  * must pass a completely initialized FCF_Record.  This routine takes
16022  * care of the nonembedded mailbox operations.
16023  **/
16024 static void
16025 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
16026 {
16027 	void *virt_addr;
16028 	union lpfc_sli4_cfg_shdr *shdr;
16029 	uint32_t shdr_status, shdr_add_status;
16030 
16031 	virt_addr = mboxq->sge_array->addr[0];
16032 	/* The IOCTL status is embedded in the mailbox subheader. */
16033 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
16034 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16035 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16036 
16037 	if ((shdr_status || shdr_add_status) &&
16038 		(shdr_status != STATUS_FCF_IN_USE))
16039 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16040 			"2558 ADD_FCF_RECORD mailbox failed with "
16041 			"status x%x add_status x%x\n",
16042 			shdr_status, shdr_add_status);
16043 
16044 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
16045 }
16046 
16047 /**
16048  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
16049  * @phba: pointer to lpfc hba data structure.
16050  * @fcf_record:  pointer to the initialized fcf record to add.
16051  *
16052  * This routine is invoked to manually add a single FCF record. The caller
16053  * must pass a completely initialized FCF_Record.  This routine takes
16054  * care of the nonembedded mailbox operations.
16055  **/
16056 int
16057 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
16058 {
16059 	int rc = 0;
16060 	LPFC_MBOXQ_t *mboxq;
16061 	uint8_t *bytep;
16062 	void *virt_addr;
16063 	struct lpfc_mbx_sge sge;
16064 	uint32_t alloc_len, req_len;
16065 	uint32_t fcfindex;
16066 
16067 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16068 	if (!mboxq) {
16069 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16070 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
16071 		return -ENOMEM;
16072 	}
16073 
16074 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
16075 		  sizeof(uint32_t);
16076 
16077 	/* Allocate DMA memory and set up the non-embedded mailbox command */
16078 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
16079 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
16080 				     req_len, LPFC_SLI4_MBX_NEMBED);
16081 	if (alloc_len < req_len) {
16082 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16083 			"2523 Allocated DMA memory size (x%x) is "
16084 			"less than the requested DMA memory "
16085 			"size (x%x)\n", alloc_len, req_len);
16086 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16087 		return -ENOMEM;
16088 	}
16089 
16090 	/*
16091 	 * Get the first SGE entry from the non-embedded DMA memory.  This
16092 	 * routine only uses a single SGE.
16093 	 */
16094 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
16095 	virt_addr = mboxq->sge_array->addr[0];
16096 	/*
16097 	 * Configure the FCF record for FCFI 0.  This is the driver's
16098 	 * hardcoded default and gets used in nonFIP mode.
16099 	 */
16100 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
16101 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
16102 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
16103 
16104 	/*
16105 	 * Copy the fcf_index and the FCF Record Data. The data starts after
16106 	 * the FCoE header plus word10. The data copy needs to be endian
16107 	 * correct.
16108 	 */
16109 	bytep += sizeof(uint32_t);
16110 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
16111 	mboxq->vport = phba->pport;
16112 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
16113 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16114 	if (rc == MBX_NOT_FINISHED) {
16115 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16116 			"2515 ADD_FCF_RECORD mailbox failed with "
16117 			"status 0x%x\n", rc);
16118 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16119 		rc = -EIO;
16120 	} else
16121 		rc = 0;
16122 
16123 	return rc;
16124 }
16125 
16126 /**
16127  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
16128  * @phba: pointer to lpfc hba data structure.
16129  * @fcf_record:  pointer to the fcf record to write the default data.
16130  * @fcf_index: FCF table entry index.
16131  *
16132  * This routine is invoked to build the driver's default FCF record.  The
16133  * values used are hardcoded.  This routine handles memory initialization.
16134  *
16135  **/
16136 void
16137 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
16138 				struct fcf_record *fcf_record,
16139 				uint16_t fcf_index)
16140 {
16141 	memset(fcf_record, 0, sizeof(struct fcf_record));
16142 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
16143 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
16144 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
16145 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
16146 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
16147 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
16148 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
16149 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
16150 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
16151 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
16152 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
16153 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
16154 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
16155 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
16156 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
16157 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
16158 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
16159 	/* Set the VLAN bit map */
16160 	if (phba->valid_vlan) {
16161 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
16162 			= 1 << (phba->vlan_id % 8);
16163 	}
16164 }
16165 
16166 /**
16167  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
16168  * @phba: pointer to lpfc hba data structure.
16169  * @fcf_index: FCF table entry offset.
16170  *
16171  * This routine is invoked to scan the entire FCF table by reading FCF
16172  * record and processing it one at a time starting from the @fcf_index
16173  * for initial FCF discovery or fast FCF failover rediscovery.
16174  *
16175  * Return 0 if the mailbox command is submitted successfully, none 0
16176  * otherwise.
16177  **/
16178 int
16179 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
16180 {
16181 	int rc = 0, error;
16182 	LPFC_MBOXQ_t *mboxq;
16183 
16184 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
16185 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
16186 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16187 	if (!mboxq) {
16188 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16189 				"2000 Failed to allocate mbox for "
16190 				"READ_FCF cmd\n");
16191 		error = -ENOMEM;
16192 		goto fail_fcf_scan;
16193 	}
16194 	/* Construct the read FCF record mailbox command */
16195 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
16196 	if (rc) {
16197 		error = -EINVAL;
16198 		goto fail_fcf_scan;
16199 	}
16200 	/* Issue the mailbox command asynchronously */
16201 	mboxq->vport = phba->pport;
16202 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
16203 
16204 	spin_lock_irq(&phba->hbalock);
16205 	phba->hba_flag |= FCF_TS_INPROG;
16206 	spin_unlock_irq(&phba->hbalock);
16207 
16208 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16209 	if (rc == MBX_NOT_FINISHED)
16210 		error = -EIO;
16211 	else {
16212 		/* Reset eligible FCF count for new scan */
16213 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
16214 			phba->fcf.eligible_fcf_cnt = 0;
16215 		error = 0;
16216 	}
16217 fail_fcf_scan:
16218 	if (error) {
16219 		if (mboxq)
16220 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
16221 		/* FCF scan failed, clear FCF_TS_INPROG flag */
16222 		spin_lock_irq(&phba->hbalock);
16223 		phba->hba_flag &= ~FCF_TS_INPROG;
16224 		spin_unlock_irq(&phba->hbalock);
16225 	}
16226 	return error;
16227 }
16228 
16229 /**
16230  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
16231  * @phba: pointer to lpfc hba data structure.
16232  * @fcf_index: FCF table entry offset.
16233  *
16234  * This routine is invoked to read an FCF record indicated by @fcf_index
16235  * and to use it for FLOGI roundrobin FCF failover.
16236  *
16237  * Return 0 if the mailbox command is submitted successfully, none 0
16238  * otherwise.
16239  **/
16240 int
16241 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
16242 {
16243 	int rc = 0, error;
16244 	LPFC_MBOXQ_t *mboxq;
16245 
16246 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16247 	if (!mboxq) {
16248 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
16249 				"2763 Failed to allocate mbox for "
16250 				"READ_FCF cmd\n");
16251 		error = -ENOMEM;
16252 		goto fail_fcf_read;
16253 	}
16254 	/* Construct the read FCF record mailbox command */
16255 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
16256 	if (rc) {
16257 		error = -EINVAL;
16258 		goto fail_fcf_read;
16259 	}
16260 	/* Issue the mailbox command asynchronously */
16261 	mboxq->vport = phba->pport;
16262 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
16263 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16264 	if (rc == MBX_NOT_FINISHED)
16265 		error = -EIO;
16266 	else
16267 		error = 0;
16268 
16269 fail_fcf_read:
16270 	if (error && mboxq)
16271 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16272 	return error;
16273 }
16274 
16275 /**
16276  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
16277  * @phba: pointer to lpfc hba data structure.
16278  * @fcf_index: FCF table entry offset.
16279  *
16280  * This routine is invoked to read an FCF record indicated by @fcf_index to
16281  * determine whether it's eligible for FLOGI roundrobin failover list.
16282  *
16283  * Return 0 if the mailbox command is submitted successfully, none 0
16284  * otherwise.
16285  **/
16286 int
16287 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
16288 {
16289 	int rc = 0, error;
16290 	LPFC_MBOXQ_t *mboxq;
16291 
16292 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16293 	if (!mboxq) {
16294 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
16295 				"2758 Failed to allocate mbox for "
16296 				"READ_FCF cmd\n");
16297 				error = -ENOMEM;
16298 				goto fail_fcf_read;
16299 	}
16300 	/* Construct the read FCF record mailbox command */
16301 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
16302 	if (rc) {
16303 		error = -EINVAL;
16304 		goto fail_fcf_read;
16305 	}
16306 	/* Issue the mailbox command asynchronously */
16307 	mboxq->vport = phba->pport;
16308 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
16309 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16310 	if (rc == MBX_NOT_FINISHED)
16311 		error = -EIO;
16312 	else
16313 		error = 0;
16314 
16315 fail_fcf_read:
16316 	if (error && mboxq)
16317 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16318 	return error;
16319 }
16320 
16321 /**
16322  * lpfc_check_next_fcf_pri_level
16323  * phba pointer to the lpfc_hba struct for this port.
16324  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
16325  * routine when the rr_bmask is empty. The FCF indecies are put into the
16326  * rr_bmask based on their priority level. Starting from the highest priority
16327  * to the lowest. The most likely FCF candidate will be in the highest
16328  * priority group. When this routine is called it searches the fcf_pri list for
16329  * next lowest priority group and repopulates the rr_bmask with only those
16330  * fcf_indexes.
16331  * returns:
16332  * 1=success 0=failure
16333  **/
16334 static int
16335 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
16336 {
16337 	uint16_t next_fcf_pri;
16338 	uint16_t last_index;
16339 	struct lpfc_fcf_pri *fcf_pri;
16340 	int rc;
16341 	int ret = 0;
16342 
16343 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
16344 			LPFC_SLI4_FCF_TBL_INDX_MAX);
16345 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16346 			"3060 Last IDX %d\n", last_index);
16347 
16348 	/* Verify the priority list has 2 or more entries */
16349 	spin_lock_irq(&phba->hbalock);
16350 	if (list_empty(&phba->fcf.fcf_pri_list) ||
16351 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
16352 		spin_unlock_irq(&phba->hbalock);
16353 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16354 			"3061 Last IDX %d\n", last_index);
16355 		return 0; /* Empty rr list */
16356 	}
16357 	spin_unlock_irq(&phba->hbalock);
16358 
16359 	next_fcf_pri = 0;
16360 	/*
16361 	 * Clear the rr_bmask and set all of the bits that are at this
16362 	 * priority.
16363 	 */
16364 	memset(phba->fcf.fcf_rr_bmask, 0,
16365 			sizeof(*phba->fcf.fcf_rr_bmask));
16366 	spin_lock_irq(&phba->hbalock);
16367 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
16368 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
16369 			continue;
16370 		/*
16371 		 * the 1st priority that has not FLOGI failed
16372 		 * will be the highest.
16373 		 */
16374 		if (!next_fcf_pri)
16375 			next_fcf_pri = fcf_pri->fcf_rec.priority;
16376 		spin_unlock_irq(&phba->hbalock);
16377 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
16378 			rc = lpfc_sli4_fcf_rr_index_set(phba,
16379 						fcf_pri->fcf_rec.fcf_index);
16380 			if (rc)
16381 				return 0;
16382 		}
16383 		spin_lock_irq(&phba->hbalock);
16384 	}
16385 	/*
16386 	 * if next_fcf_pri was not set above and the list is not empty then
16387 	 * we have failed flogis on all of them. So reset flogi failed
16388 	 * and start at the beginning.
16389 	 */
16390 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
16391 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
16392 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
16393 			/*
16394 			 * the 1st priority that has not FLOGI failed
16395 			 * will be the highest.
16396 			 */
16397 			if (!next_fcf_pri)
16398 				next_fcf_pri = fcf_pri->fcf_rec.priority;
16399 			spin_unlock_irq(&phba->hbalock);
16400 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
16401 				rc = lpfc_sli4_fcf_rr_index_set(phba,
16402 						fcf_pri->fcf_rec.fcf_index);
16403 				if (rc)
16404 					return 0;
16405 			}
16406 			spin_lock_irq(&phba->hbalock);
16407 		}
16408 	} else
16409 		ret = 1;
16410 	spin_unlock_irq(&phba->hbalock);
16411 
16412 	return ret;
16413 }
16414 /**
16415  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
16416  * @phba: pointer to lpfc hba data structure.
16417  *
16418  * This routine is to get the next eligible FCF record index in a round
16419  * robin fashion. If the next eligible FCF record index equals to the
16420  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
16421  * shall be returned, otherwise, the next eligible FCF record's index
16422  * shall be returned.
16423  **/
16424 uint16_t
16425 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
16426 {
16427 	uint16_t next_fcf_index;
16428 
16429 initial_priority:
16430 	/* Search start from next bit of currently registered FCF index */
16431 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
16432 
16433 next_priority:
16434 	/* Determine the next fcf index to check */
16435 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
16436 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
16437 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
16438 				       next_fcf_index);
16439 
16440 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
16441 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
16442 		/*
16443 		 * If we have wrapped then we need to clear the bits that
16444 		 * have been tested so that we can detect when we should
16445 		 * change the priority level.
16446 		 */
16447 		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
16448 					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
16449 	}
16450 
16451 
16452 	/* Check roundrobin failover list empty condition */
16453 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
16454 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
16455 		/*
16456 		 * If next fcf index is not found check if there are lower
16457 		 * Priority level fcf's in the fcf_priority list.
16458 		 * Set up the rr_bmask with all of the avaiable fcf bits
16459 		 * at that level and continue the selection process.
16460 		 */
16461 		if (lpfc_check_next_fcf_pri_level(phba))
16462 			goto initial_priority;
16463 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
16464 				"2844 No roundrobin failover FCF available\n");
16465 		if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX)
16466 			return LPFC_FCOE_FCF_NEXT_NONE;
16467 		else {
16468 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
16469 				"3063 Only FCF available idx %d, flag %x\n",
16470 				next_fcf_index,
16471 			phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag);
16472 			return next_fcf_index;
16473 		}
16474 	}
16475 
16476 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
16477 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
16478 		LPFC_FCF_FLOGI_FAILED) {
16479 		if (list_is_singular(&phba->fcf.fcf_pri_list))
16480 			return LPFC_FCOE_FCF_NEXT_NONE;
16481 
16482 		goto next_priority;
16483 	}
16484 
16485 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16486 			"2845 Get next roundrobin failover FCF (x%x)\n",
16487 			next_fcf_index);
16488 
16489 	return next_fcf_index;
16490 }
16491 
16492 /**
16493  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
16494  * @phba: pointer to lpfc hba data structure.
16495  *
16496  * This routine sets the FCF record index in to the eligible bmask for
16497  * roundrobin failover search. It checks to make sure that the index
16498  * does not go beyond the range of the driver allocated bmask dimension
16499  * before setting the bit.
16500  *
16501  * Returns 0 if the index bit successfully set, otherwise, it returns
16502  * -EINVAL.
16503  **/
16504 int
16505 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
16506 {
16507 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
16508 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16509 				"2610 FCF (x%x) reached driver's book "
16510 				"keeping dimension:x%x\n",
16511 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
16512 		return -EINVAL;
16513 	}
16514 	/* Set the eligible FCF record index bmask */
16515 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
16516 
16517 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16518 			"2790 Set FCF (x%x) to roundrobin FCF failover "
16519 			"bmask\n", fcf_index);
16520 
16521 	return 0;
16522 }
16523 
16524 /**
16525  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
16526  * @phba: pointer to lpfc hba data structure.
16527  *
16528  * This routine clears the FCF record index from the eligible bmask for
16529  * roundrobin failover search. It checks to make sure that the index
16530  * does not go beyond the range of the driver allocated bmask dimension
16531  * before clearing the bit.
16532  **/
16533 void
16534 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
16535 {
16536 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
16537 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
16538 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16539 				"2762 FCF (x%x) reached driver's book "
16540 				"keeping dimension:x%x\n",
16541 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
16542 		return;
16543 	}
16544 	/* Clear the eligible FCF record index bmask */
16545 	spin_lock_irq(&phba->hbalock);
16546 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
16547 				 list) {
16548 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
16549 			list_del_init(&fcf_pri->list);
16550 			break;
16551 		}
16552 	}
16553 	spin_unlock_irq(&phba->hbalock);
16554 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
16555 
16556 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16557 			"2791 Clear FCF (x%x) from roundrobin failover "
16558 			"bmask\n", fcf_index);
16559 }
16560 
16561 /**
16562  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
16563  * @phba: pointer to lpfc hba data structure.
16564  *
16565  * This routine is the completion routine for the rediscover FCF table mailbox
16566  * command. If the mailbox command returned failure, it will try to stop the
16567  * FCF rediscover wait timer.
16568  **/
16569 static void
16570 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
16571 {
16572 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
16573 	uint32_t shdr_status, shdr_add_status;
16574 
16575 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
16576 
16577 	shdr_status = bf_get(lpfc_mbox_hdr_status,
16578 			     &redisc_fcf->header.cfg_shdr.response);
16579 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
16580 			     &redisc_fcf->header.cfg_shdr.response);
16581 	if (shdr_status || shdr_add_status) {
16582 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16583 				"2746 Requesting for FCF rediscovery failed "
16584 				"status x%x add_status x%x\n",
16585 				shdr_status, shdr_add_status);
16586 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
16587 			spin_lock_irq(&phba->hbalock);
16588 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
16589 			spin_unlock_irq(&phba->hbalock);
16590 			/*
16591 			 * CVL event triggered FCF rediscover request failed,
16592 			 * last resort to re-try current registered FCF entry.
16593 			 */
16594 			lpfc_retry_pport_discovery(phba);
16595 		} else {
16596 			spin_lock_irq(&phba->hbalock);
16597 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
16598 			spin_unlock_irq(&phba->hbalock);
16599 			/*
16600 			 * DEAD FCF event triggered FCF rediscover request
16601 			 * failed, last resort to fail over as a link down
16602 			 * to FCF registration.
16603 			 */
16604 			lpfc_sli4_fcf_dead_failthrough(phba);
16605 		}
16606 	} else {
16607 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16608 				"2775 Start FCF rediscover quiescent timer\n");
16609 		/*
16610 		 * Start FCF rediscovery wait timer for pending FCF
16611 		 * before rescan FCF record table.
16612 		 */
16613 		lpfc_fcf_redisc_wait_start_timer(phba);
16614 	}
16615 
16616 	mempool_free(mbox, phba->mbox_mem_pool);
16617 }
16618 
16619 /**
16620  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
16621  * @phba: pointer to lpfc hba data structure.
16622  *
16623  * This routine is invoked to request for rediscovery of the entire FCF table
16624  * by the port.
16625  **/
16626 int
16627 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
16628 {
16629 	LPFC_MBOXQ_t *mbox;
16630 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
16631 	int rc, length;
16632 
16633 	/* Cancel retry delay timers to all vports before FCF rediscover */
16634 	lpfc_cancel_all_vport_retry_delay_timer(phba);
16635 
16636 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16637 	if (!mbox) {
16638 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16639 				"2745 Failed to allocate mbox for "
16640 				"requesting FCF rediscover.\n");
16641 		return -ENOMEM;
16642 	}
16643 
16644 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
16645 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16646 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16647 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
16648 			 length, LPFC_SLI4_MBX_EMBED);
16649 
16650 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
16651 	/* Set count to 0 for invalidating the entire FCF database */
16652 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
16653 
16654 	/* Issue the mailbox command asynchronously */
16655 	mbox->vport = phba->pport;
16656 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
16657 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
16658 
16659 	if (rc == MBX_NOT_FINISHED) {
16660 		mempool_free(mbox, phba->mbox_mem_pool);
16661 		return -EIO;
16662 	}
16663 	return 0;
16664 }
16665 
16666 /**
16667  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
16668  * @phba: pointer to lpfc hba data structure.
16669  *
16670  * This function is the failover routine as a last resort to the FCF DEAD
16671  * event when driver failed to perform fast FCF failover.
16672  **/
16673 void
16674 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
16675 {
16676 	uint32_t link_state;
16677 
16678 	/*
16679 	 * Last resort as FCF DEAD event failover will treat this as
16680 	 * a link down, but save the link state because we don't want
16681 	 * it to be changed to Link Down unless it is already down.
16682 	 */
16683 	link_state = phba->link_state;
16684 	lpfc_linkdown(phba);
16685 	phba->link_state = link_state;
16686 
16687 	/* Unregister FCF if no devices connected to it */
16688 	lpfc_unregister_unused_fcf(phba);
16689 }
16690 
16691 /**
16692  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
16693  * @phba: pointer to lpfc hba data structure.
16694  * @rgn23_data: pointer to configure region 23 data.
16695  *
16696  * This function gets SLI3 port configure region 23 data through memory dump
16697  * mailbox command. When it successfully retrieves data, the size of the data
16698  * will be returned, otherwise, 0 will be returned.
16699  **/
16700 static uint32_t
16701 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
16702 {
16703 	LPFC_MBOXQ_t *pmb = NULL;
16704 	MAILBOX_t *mb;
16705 	uint32_t offset = 0;
16706 	int rc;
16707 
16708 	if (!rgn23_data)
16709 		return 0;
16710 
16711 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16712 	if (!pmb) {
16713 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16714 				"2600 failed to allocate mailbox memory\n");
16715 		return 0;
16716 	}
16717 	mb = &pmb->u.mb;
16718 
16719 	do {
16720 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
16721 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
16722 
16723 		if (rc != MBX_SUCCESS) {
16724 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16725 					"2601 failed to read config "
16726 					"region 23, rc 0x%x Status 0x%x\n",
16727 					rc, mb->mbxStatus);
16728 			mb->un.varDmp.word_cnt = 0;
16729 		}
16730 		/*
16731 		 * dump mem may return a zero when finished or we got a
16732 		 * mailbox error, either way we are done.
16733 		 */
16734 		if (mb->un.varDmp.word_cnt == 0)
16735 			break;
16736 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
16737 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
16738 
16739 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
16740 				       rgn23_data + offset,
16741 				       mb->un.varDmp.word_cnt);
16742 		offset += mb->un.varDmp.word_cnt;
16743 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
16744 
16745 	mempool_free(pmb, phba->mbox_mem_pool);
16746 	return offset;
16747 }
16748 
16749 /**
16750  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
16751  * @phba: pointer to lpfc hba data structure.
16752  * @rgn23_data: pointer to configure region 23 data.
16753  *
16754  * This function gets SLI4 port configure region 23 data through memory dump
16755  * mailbox command. When it successfully retrieves data, the size of the data
16756  * will be returned, otherwise, 0 will be returned.
16757  **/
16758 static uint32_t
16759 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
16760 {
16761 	LPFC_MBOXQ_t *mboxq = NULL;
16762 	struct lpfc_dmabuf *mp = NULL;
16763 	struct lpfc_mqe *mqe;
16764 	uint32_t data_length = 0;
16765 	int rc;
16766 
16767 	if (!rgn23_data)
16768 		return 0;
16769 
16770 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16771 	if (!mboxq) {
16772 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16773 				"3105 failed to allocate mailbox memory\n");
16774 		return 0;
16775 	}
16776 
16777 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
16778 		goto out;
16779 	mqe = &mboxq->u.mqe;
16780 	mp = (struct lpfc_dmabuf *) mboxq->context1;
16781 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
16782 	if (rc)
16783 		goto out;
16784 	data_length = mqe->un.mb_words[5];
16785 	if (data_length == 0)
16786 		goto out;
16787 	if (data_length > DMP_RGN23_SIZE) {
16788 		data_length = 0;
16789 		goto out;
16790 	}
16791 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
16792 out:
16793 	mempool_free(mboxq, phba->mbox_mem_pool);
16794 	if (mp) {
16795 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
16796 		kfree(mp);
16797 	}
16798 	return data_length;
16799 }
16800 
16801 /**
16802  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
16803  * @phba: pointer to lpfc hba data structure.
16804  *
16805  * This function read region 23 and parse TLV for port status to
16806  * decide if the user disaled the port. If the TLV indicates the
16807  * port is disabled, the hba_flag is set accordingly.
16808  **/
16809 void
16810 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
16811 {
16812 	uint8_t *rgn23_data = NULL;
16813 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
16814 	uint32_t offset = 0;
16815 
16816 	/* Get adapter Region 23 data */
16817 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
16818 	if (!rgn23_data)
16819 		goto out;
16820 
16821 	if (phba->sli_rev < LPFC_SLI_REV4)
16822 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
16823 	else {
16824 		if_type = bf_get(lpfc_sli_intf_if_type,
16825 				 &phba->sli4_hba.sli_intf);
16826 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
16827 			goto out;
16828 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
16829 	}
16830 
16831 	if (!data_size)
16832 		goto out;
16833 
16834 	/* Check the region signature first */
16835 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
16836 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16837 			"2619 Config region 23 has bad signature\n");
16838 			goto out;
16839 	}
16840 	offset += 4;
16841 
16842 	/* Check the data structure version */
16843 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
16844 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16845 			"2620 Config region 23 has bad version\n");
16846 		goto out;
16847 	}
16848 	offset += 4;
16849 
16850 	/* Parse TLV entries in the region */
16851 	while (offset < data_size) {
16852 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
16853 			break;
16854 		/*
16855 		 * If the TLV is not driver specific TLV or driver id is
16856 		 * not linux driver id, skip the record.
16857 		 */
16858 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
16859 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
16860 		    (rgn23_data[offset + 3] != 0)) {
16861 			offset += rgn23_data[offset + 1] * 4 + 4;
16862 			continue;
16863 		}
16864 
16865 		/* Driver found a driver specific TLV in the config region */
16866 		sub_tlv_len = rgn23_data[offset + 1] * 4;
16867 		offset += 4;
16868 		tlv_offset = 0;
16869 
16870 		/*
16871 		 * Search for configured port state sub-TLV.
16872 		 */
16873 		while ((offset < data_size) &&
16874 			(tlv_offset < sub_tlv_len)) {
16875 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
16876 				offset += 4;
16877 				tlv_offset += 4;
16878 				break;
16879 			}
16880 			if (rgn23_data[offset] != PORT_STE_TYPE) {
16881 				offset += rgn23_data[offset + 1] * 4 + 4;
16882 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
16883 				continue;
16884 			}
16885 
16886 			/* This HBA contains PORT_STE configured */
16887 			if (!rgn23_data[offset + 2])
16888 				phba->hba_flag |= LINK_DISABLED;
16889 
16890 			goto out;
16891 		}
16892 	}
16893 
16894 out:
16895 	kfree(rgn23_data);
16896 	return;
16897 }
16898 
16899 /**
16900  * lpfc_wr_object - write an object to the firmware
16901  * @phba: HBA structure that indicates port to create a queue on.
16902  * @dmabuf_list: list of dmabufs to write to the port.
16903  * @size: the total byte value of the objects to write to the port.
16904  * @offset: the current offset to be used to start the transfer.
16905  *
16906  * This routine will create a wr_object mailbox command to send to the port.
16907  * the mailbox command will be constructed using the dma buffers described in
16908  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
16909  * BDEs that the imbedded mailbox can support. The @offset variable will be
16910  * used to indicate the starting offset of the transfer and will also return
16911  * the offset after the write object mailbox has completed. @size is used to
16912  * determine the end of the object and whether the eof bit should be set.
16913  *
16914  * Return 0 is successful and offset will contain the the new offset to use
16915  * for the next write.
16916  * Return negative value for error cases.
16917  **/
16918 int
16919 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
16920 	       uint32_t size, uint32_t *offset)
16921 {
16922 	struct lpfc_mbx_wr_object *wr_object;
16923 	LPFC_MBOXQ_t *mbox;
16924 	int rc = 0, i = 0;
16925 	uint32_t shdr_status, shdr_add_status;
16926 	uint32_t mbox_tmo;
16927 	union lpfc_sli4_cfg_shdr *shdr;
16928 	struct lpfc_dmabuf *dmabuf;
16929 	uint32_t written = 0;
16930 
16931 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16932 	if (!mbox)
16933 		return -ENOMEM;
16934 
16935 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16936 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
16937 			sizeof(struct lpfc_mbx_wr_object) -
16938 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
16939 
16940 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
16941 	wr_object->u.request.write_offset = *offset;
16942 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
16943 	wr_object->u.request.object_name[0] =
16944 		cpu_to_le32(wr_object->u.request.object_name[0]);
16945 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
16946 	list_for_each_entry(dmabuf, dmabuf_list, list) {
16947 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
16948 			break;
16949 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
16950 		wr_object->u.request.bde[i].addrHigh =
16951 			putPaddrHigh(dmabuf->phys);
16952 		if (written + SLI4_PAGE_SIZE >= size) {
16953 			wr_object->u.request.bde[i].tus.f.bdeSize =
16954 				(size - written);
16955 			written += (size - written);
16956 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
16957 		} else {
16958 			wr_object->u.request.bde[i].tus.f.bdeSize =
16959 				SLI4_PAGE_SIZE;
16960 			written += SLI4_PAGE_SIZE;
16961 		}
16962 		i++;
16963 	}
16964 	wr_object->u.request.bde_count = i;
16965 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
16966 	if (!phba->sli4_hba.intr_enable)
16967 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16968 	else {
16969 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16970 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16971 	}
16972 	/* The IOCTL status is embedded in the mailbox subheader. */
16973 	shdr = (union lpfc_sli4_cfg_shdr *) &wr_object->header.cfg_shdr;
16974 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16975 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16976 	if (rc != MBX_TIMEOUT)
16977 		mempool_free(mbox, phba->mbox_mem_pool);
16978 	if (shdr_status || shdr_add_status || rc) {
16979 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16980 				"3025 Write Object mailbox failed with "
16981 				"status x%x add_status x%x, mbx status x%x\n",
16982 				shdr_status, shdr_add_status, rc);
16983 		rc = -ENXIO;
16984 	} else
16985 		*offset += wr_object->u.response.actual_write_length;
16986 	return rc;
16987 }
16988 
16989 /**
16990  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
16991  * @vport: pointer to vport data structure.
16992  *
16993  * This function iterate through the mailboxq and clean up all REG_LOGIN
16994  * and REG_VPI mailbox commands associated with the vport. This function
16995  * is called when driver want to restart discovery of the vport due to
16996  * a Clear Virtual Link event.
16997  **/
16998 void
16999 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
17000 {
17001 	struct lpfc_hba *phba = vport->phba;
17002 	LPFC_MBOXQ_t *mb, *nextmb;
17003 	struct lpfc_dmabuf *mp;
17004 	struct lpfc_nodelist *ndlp;
17005 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
17006 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
17007 	LIST_HEAD(mbox_cmd_list);
17008 	uint8_t restart_loop;
17009 
17010 	/* Clean up internally queued mailbox commands with the vport */
17011 	spin_lock_irq(&phba->hbalock);
17012 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
17013 		if (mb->vport != vport)
17014 			continue;
17015 
17016 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
17017 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
17018 			continue;
17019 
17020 		list_del(&mb->list);
17021 		list_add_tail(&mb->list, &mbox_cmd_list);
17022 	}
17023 	/* Clean up active mailbox command with the vport */
17024 	mb = phba->sli.mbox_active;
17025 	if (mb && (mb->vport == vport)) {
17026 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
17027 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
17028 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17029 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
17030 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->context2;
17031 			/* Put reference count for delayed processing */
17032 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
17033 			/* Unregister the RPI when mailbox complete */
17034 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
17035 		}
17036 	}
17037 	/* Cleanup any mailbox completions which are not yet processed */
17038 	do {
17039 		restart_loop = 0;
17040 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
17041 			/*
17042 			 * If this mailox is already processed or it is
17043 			 * for another vport ignore it.
17044 			 */
17045 			if ((mb->vport != vport) ||
17046 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
17047 				continue;
17048 
17049 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
17050 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
17051 				continue;
17052 
17053 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17054 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
17055 				ndlp = (struct lpfc_nodelist *)mb->context2;
17056 				/* Unregister the RPI when mailbox complete */
17057 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
17058 				restart_loop = 1;
17059 				spin_unlock_irq(&phba->hbalock);
17060 				spin_lock(shost->host_lock);
17061 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
17062 				spin_unlock(shost->host_lock);
17063 				spin_lock_irq(&phba->hbalock);
17064 				break;
17065 			}
17066 		}
17067 	} while (restart_loop);
17068 
17069 	spin_unlock_irq(&phba->hbalock);
17070 
17071 	/* Release the cleaned-up mailbox commands */
17072 	while (!list_empty(&mbox_cmd_list)) {
17073 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
17074 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
17075 			mp = (struct lpfc_dmabuf *) (mb->context1);
17076 			if (mp) {
17077 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
17078 				kfree(mp);
17079 			}
17080 			ndlp = (struct lpfc_nodelist *) mb->context2;
17081 			mb->context2 = NULL;
17082 			if (ndlp) {
17083 				spin_lock(shost->host_lock);
17084 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
17085 				spin_unlock(shost->host_lock);
17086 				lpfc_nlp_put(ndlp);
17087 			}
17088 		}
17089 		mempool_free(mb, phba->mbox_mem_pool);
17090 	}
17091 
17092 	/* Release the ndlp with the cleaned-up active mailbox command */
17093 	if (act_mbx_ndlp) {
17094 		spin_lock(shost->host_lock);
17095 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
17096 		spin_unlock(shost->host_lock);
17097 		lpfc_nlp_put(act_mbx_ndlp);
17098 	}
17099 }
17100 
17101 /**
17102  * lpfc_drain_txq - Drain the txq
17103  * @phba: Pointer to HBA context object.
17104  *
17105  * This function attempt to submit IOCBs on the txq
17106  * to the adapter.  For SLI4 adapters, the txq contains
17107  * ELS IOCBs that have been deferred because the there
17108  * are no SGLs.  This congestion can occur with large
17109  * vport counts during node discovery.
17110  **/
17111 
17112 uint32_t
17113 lpfc_drain_txq(struct lpfc_hba *phba)
17114 {
17115 	LIST_HEAD(completions);
17116 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
17117 	struct lpfc_iocbq *piocbq = NULL;
17118 	unsigned long iflags = 0;
17119 	char *fail_msg = NULL;
17120 	struct lpfc_sglq *sglq;
17121 	union lpfc_wqe wqe;
17122 	uint32_t txq_cnt = 0;
17123 
17124 	spin_lock_irqsave(&pring->ring_lock, iflags);
17125 	list_for_each_entry(piocbq, &pring->txq, list) {
17126 		txq_cnt++;
17127 	}
17128 
17129 	if (txq_cnt > pring->txq_max)
17130 		pring->txq_max = txq_cnt;
17131 
17132 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
17133 
17134 	while (!list_empty(&pring->txq)) {
17135 		spin_lock_irqsave(&pring->ring_lock, iflags);
17136 
17137 		piocbq = lpfc_sli_ringtx_get(phba, pring);
17138 		if (!piocbq) {
17139 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
17140 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17141 				"2823 txq empty and txq_cnt is %d\n ",
17142 				txq_cnt);
17143 			break;
17144 		}
17145 		sglq = __lpfc_sli_get_sglq(phba, piocbq);
17146 		if (!sglq) {
17147 			__lpfc_sli_ringtx_put(phba, pring, piocbq);
17148 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
17149 			break;
17150 		}
17151 		txq_cnt--;
17152 
17153 		/* The xri and iocb resources secured,
17154 		 * attempt to issue request
17155 		 */
17156 		piocbq->sli4_lxritag = sglq->sli4_lxritag;
17157 		piocbq->sli4_xritag = sglq->sli4_xritag;
17158 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
17159 			fail_msg = "to convert bpl to sgl";
17160 		else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
17161 			fail_msg = "to convert iocb to wqe";
17162 		else if (lpfc_sli4_wq_put(phba->sli4_hba.els_wq, &wqe))
17163 			fail_msg = " - Wq is full";
17164 		else
17165 			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
17166 
17167 		if (fail_msg) {
17168 			/* Failed means we can't issue and need to cancel */
17169 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17170 					"2822 IOCB failed %s iotag 0x%x "
17171 					"xri 0x%x\n",
17172 					fail_msg,
17173 					piocbq->iotag, piocbq->sli4_xritag);
17174 			list_add_tail(&piocbq->list, &completions);
17175 		}
17176 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
17177 	}
17178 
17179 	/* Cancel all the IOCBs that cannot be issued */
17180 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
17181 				IOERR_SLI_ABORTED);
17182 
17183 	return txq_cnt;
17184 }
17185